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/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/LiteralSupport.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Designator.h"
44 #include "clang/Sema/Initialization.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaFixItUtils.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
59 
60 using namespace clang;
61 using namespace sema;
62 
63 /// Determine whether the use of this declaration is valid, without
64 /// emitting diagnostics.
65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66   // See if this is an auto-typed variable whose initializer we are parsing.
67   if (ParsingInitForAutoVars.count(D))
68     return false;
69 
70   // See if this is a deleted function.
71   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72     if (FD->isDeleted())
73       return false;
74 
75     // If the function has a deduced return type, and we can't deduce it,
76     // then we can't use it either.
77     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79       return false;
80 
81     // See if this is an aligned allocation/deallocation function that is
82     // unavailable.
83     if (TreatUnavailableAsInvalid &&
84         isUnavailableAlignedAllocationFunction(*FD))
85       return false;
86   }
87 
88   // See if this function is unavailable.
89   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91     return false;
92 
93   if (isa<UnresolvedUsingIfExistsDecl>(D))
94     return false;
95 
96   return true;
97 }
98 
99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100   // Warn if this is used but marked unused.
101   if (const auto *A = D->getAttr<UnusedAttr>()) {
102     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103     // should diagnose them.
104     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107       if (DC && !DC->hasAttr<UnusedAttr>())
108         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109     }
110   }
111 }
112 
113 /// Emit a note explaining that this function is deleted.
114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115   assert(Decl && Decl->isDeleted());
116 
117   if (Decl->isDefaulted()) {
118     // If the method was explicitly defaulted, point at that declaration.
119     if (!Decl->isImplicit())
120       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121 
122     // Try to diagnose why this special member function was implicitly
123     // deleted. This might fail, if that reason no longer applies.
124     DiagnoseDeletedDefaultedFunction(Decl);
125     return;
126   }
127 
128   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129   if (Ctor && Ctor->isInheritingConstructor())
130     return NoteDeletedInheritingConstructor(Ctor);
131 
132   Diag(Decl->getLocation(), diag::note_availability_specified_here)
133     << Decl << 1;
134 }
135 
136 /// Determine whether a FunctionDecl was ever declared with an
137 /// explicit storage class.
138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139   for (auto I : D->redecls()) {
140     if (I->getStorageClass() != SC_None)
141       return true;
142   }
143   return false;
144 }
145 
146 /// Check whether we're in an extern inline function and referring to a
147 /// variable or function with internal linkage (C11 6.7.4p3).
148 ///
149 /// This is only a warning because we used to silently accept this code, but
150 /// in many cases it will not behave correctly. This is not enabled in C++ mode
151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152 /// and so while there may still be user mistakes, most of the time we can't
153 /// prove that there are errors.
154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155                                                       const NamedDecl *D,
156                                                       SourceLocation Loc) {
157   // This is disabled under C++; there are too many ways for this to fire in
158   // contexts where the warning is a false positive, or where it is technically
159   // correct but benign.
160   if (S.getLangOpts().CPlusPlus)
161     return;
162 
163   // Check if this is an inlined function or method.
164   FunctionDecl *Current = S.getCurFunctionDecl();
165   if (!Current)
166     return;
167   if (!Current->isInlined())
168     return;
169   if (!Current->isExternallyVisible())
170     return;
171 
172   // Check if the decl has internal linkage.
173   if (D->getFormalLinkage() != InternalLinkage)
174     return;
175 
176   // Downgrade from ExtWarn to Extension if
177   //  (1) the supposedly external inline function is in the main file,
178   //      and probably won't be included anywhere else.
179   //  (2) the thing we're referencing is a pure function.
180   //  (3) the thing we're referencing is another inline function.
181   // This last can give us false negatives, but it's better than warning on
182   // wrappers for simple C library functions.
183   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185   if (!DowngradeWarning && UsedFn)
186     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
187 
188   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189                                : diag::ext_internal_in_extern_inline)
190     << /*IsVar=*/!UsedFn << D;
191 
192   S.MaybeSuggestAddingStaticToDecl(Current);
193 
194   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195       << D;
196 }
197 
198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199   const FunctionDecl *First = Cur->getFirstDecl();
200 
201   // Suggest "static" on the function, if possible.
202   if (!hasAnyExplicitStorageClass(First)) {
203     SourceLocation DeclBegin = First->getSourceRange().getBegin();
204     Diag(DeclBegin, diag::note_convert_inline_to_static)
205       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206   }
207 }
208 
209 /// Determine whether the use of this declaration is valid, and
210 /// emit any corresponding diagnostics.
211 ///
212 /// This routine diagnoses various problems with referencing
213 /// declarations that can occur when using a declaration. For example,
214 /// it might warn if a deprecated or unavailable declaration is being
215 /// used, or produce an error (and return true) if a C++0x deleted
216 /// function is being used.
217 ///
218 /// \returns true if there was an error (this declaration cannot be
219 /// referenced), false otherwise.
220 ///
221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222                              const ObjCInterfaceDecl *UnknownObjCClass,
223                              bool ObjCPropertyAccess,
224                              bool AvoidPartialAvailabilityChecks,
225                              ObjCInterfaceDecl *ClassReceiver) {
226   SourceLocation Loc = Locs.front();
227   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228     // If there were any diagnostics suppressed by template argument deduction,
229     // emit them now.
230     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231     if (Pos != SuppressedDiagnostics.end()) {
232       for (const PartialDiagnosticAt &Suppressed : Pos->second)
233         Diag(Suppressed.first, Suppressed.second);
234 
235       // Clear out the list of suppressed diagnostics, so that we don't emit
236       // them again for this specialization. However, we don't obsolete this
237       // entry from the table, because we want to avoid ever emitting these
238       // diagnostics again.
239       Pos->second.clear();
240     }
241 
242     // C++ [basic.start.main]p3:
243     //   The function 'main' shall not be used within a program.
244     if (cast<FunctionDecl>(D)->isMain())
245       Diag(Loc, diag::ext_main_used);
246 
247     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248   }
249 
250   // See if this is an auto-typed variable whose initializer we are parsing.
251   if (ParsingInitForAutoVars.count(D)) {
252     if (isa<BindingDecl>(D)) {
253       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254         << D->getDeclName();
255     } else {
256       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257         << D->getDeclName() << cast<VarDecl>(D)->getType();
258     }
259     return true;
260   }
261 
262   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263     // See if this is a deleted function.
264     if (FD->isDeleted()) {
265       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266       if (Ctor && Ctor->isInheritingConstructor())
267         Diag(Loc, diag::err_deleted_inherited_ctor_use)
268             << Ctor->getParent()
269             << Ctor->getInheritedConstructor().getConstructor()->getParent();
270       else
271         Diag(Loc, diag::err_deleted_function_use);
272       NoteDeletedFunction(FD);
273       return true;
274     }
275 
276     // [expr.prim.id]p4
277     //   A program that refers explicitly or implicitly to a function with a
278     //   trailing requires-clause whose constraint-expression is not satisfied,
279     //   other than to declare it, is ill-formed. [...]
280     //
281     // See if this is a function with constraints that need to be satisfied.
282     // Check this before deducing the return type, as it might instantiate the
283     // definition.
284     if (FD->getTrailingRequiresClause()) {
285       ConstraintSatisfaction Satisfaction;
286       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287         // A diagnostic will have already been generated (non-constant
288         // constraint expression, for example)
289         return true;
290       if (!Satisfaction.IsSatisfied) {
291         Diag(Loc,
292              diag::err_reference_to_function_with_unsatisfied_constraints)
293             << D;
294         DiagnoseUnsatisfiedConstraint(Satisfaction);
295         return true;
296       }
297     }
298 
299     // If the function has a deduced return type, and we can't deduce it,
300     // then we can't use it either.
301     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302         DeduceReturnType(FD, Loc))
303       return true;
304 
305     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306       return true;
307 
308     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309       return true;
310   }
311 
312   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313     // Lambdas are only default-constructible or assignable in C++2a onwards.
314     if (MD->getParent()->isLambda() &&
315         ((isa<CXXConstructorDecl>(MD) &&
316           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319         << !isa<CXXConstructorDecl>(MD);
320     }
321   }
322 
323   auto getReferencedObjCProp = [](const NamedDecl *D) ->
324                                       const ObjCPropertyDecl * {
325     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326       return MD->findPropertyDecl();
327     return nullptr;
328   };
329   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331       return true;
332   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333       return true;
334   }
335 
336   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337   // Only the variables omp_in and omp_out are allowed in the combiner.
338   // Only the variables omp_priv and omp_orig are allowed in the
339   // initializer-clause.
340   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342       isa<VarDecl>(D)) {
343     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344         << getCurFunction()->HasOMPDeclareReductionCombiner;
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350   //  List-items in map clauses on this construct may only refer to the declared
351   //  variable var and entities that could be referenced by a procedure defined
352   //  at the same location
353   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356         << getOpenMPDeclareMapperVarName();
357     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358     return true;
359   }
360 
361   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362     Diag(Loc, diag::err_use_of_empty_using_if_exists);
363     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364     return true;
365   }
366 
367   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368                              AvoidPartialAvailabilityChecks, ClassReceiver);
369 
370   DiagnoseUnusedOfDecl(*this, D, Loc);
371 
372   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373 
374   if (auto *VD = dyn_cast<ValueDecl>(D))
375     checkTypeSupport(VD->getType(), Loc, VD);
376 
377   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378     if (!Context.getTargetInfo().isTLSSupported())
379       if (const auto *VD = dyn_cast<VarDecl>(D))
380         if (VD->getTLSKind() != VarDecl::TLS_None)
381           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382   }
383 
384   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385       !isUnevaluatedContext()) {
386     // C++ [expr.prim.req.nested] p3
387     //   A local parameter shall only appear as an unevaluated operand
388     //   (Clause 8) within the constraint-expression.
389     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390         << D;
391     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392     return true;
393   }
394 
395   return false;
396 }
397 
398 /// DiagnoseSentinelCalls - This routine checks whether a call or
399 /// message-send is to a declaration with the sentinel attribute, and
400 /// if so, it checks that the requirements of the sentinel are
401 /// satisfied.
402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403                                  ArrayRef<Expr *> Args) {
404   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405   if (!attr)
406     return;
407 
408   // The number of formal parameters of the declaration.
409   unsigned numFormalParams;
410 
411   // The kind of declaration.  This is also an index into a %select in
412   // the diagnostic.
413   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414 
415   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416     numFormalParams = MD->param_size();
417     calleeType = CT_Method;
418   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419     numFormalParams = FD->param_size();
420     calleeType = CT_Function;
421   } else if (isa<VarDecl>(D)) {
422     QualType type = cast<ValueDecl>(D)->getType();
423     const FunctionType *fn = nullptr;
424     if (const PointerType *ptr = type->getAs<PointerType>()) {
425       fn = ptr->getPointeeType()->getAs<FunctionType>();
426       if (!fn) return;
427       calleeType = CT_Function;
428     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429       fn = ptr->getPointeeType()->castAs<FunctionType>();
430       calleeType = CT_Block;
431     } else {
432       return;
433     }
434 
435     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436       numFormalParams = proto->getNumParams();
437     } else {
438       numFormalParams = 0;
439     }
440   } else {
441     return;
442   }
443 
444   // "nullPos" is the number of formal parameters at the end which
445   // effectively count as part of the variadic arguments.  This is
446   // useful if you would prefer to not have *any* formal parameters,
447   // but the language forces you to have at least one.
448   unsigned nullPos = attr->getNullPos();
449   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
450   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
451 
452   // The number of arguments which should follow the sentinel.
453   unsigned numArgsAfterSentinel = attr->getSentinel();
454 
455   // If there aren't enough arguments for all the formal parameters,
456   // the sentinel, and the args after the sentinel, complain.
457   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460     return;
461   }
462 
463   // Otherwise, find the sentinel expression.
464   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465   if (!sentinelExpr) return;
466   if (sentinelExpr->isValueDependent()) return;
467   if (Context.isSentinelNullExpr(sentinelExpr)) return;
468 
469   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
470   // or 'NULL' if those are actually defined in the context.  Only use
471   // 'nil' for ObjC methods, where it's much more likely that the
472   // variadic arguments form a list of object pointers.
473   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474   std::string NullValue;
475   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476     NullValue = "nil";
477   else if (getLangOpts().CPlusPlus11)
478     NullValue = "nullptr";
479   else if (PP.isMacroDefined("NULL"))
480     NullValue = "NULL";
481   else
482     NullValue = "(void*) 0";
483 
484   if (MissingNilLoc.isInvalid())
485     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486   else
487     Diag(MissingNilLoc, diag::warn_missing_sentinel)
488       << int(calleeType)
489       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491 }
492 
493 SourceRange Sema::getExprRange(Expr *E) const {
494   return E ? E->getSourceRange() : SourceRange();
495 }
496 
497 //===----------------------------------------------------------------------===//
498 //  Standard Promotions and Conversions
499 //===----------------------------------------------------------------------===//
500 
501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503   // Handle any placeholder expressions which made it here.
504   if (E->hasPlaceholderType()) {
505     ExprResult result = CheckPlaceholderExpr(E);
506     if (result.isInvalid()) return ExprError();
507     E = result.get();
508   }
509 
510   QualType Ty = E->getType();
511   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
512 
513   if (Ty->isFunctionType()) {
514     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517           return ExprError();
518 
519     E = ImpCastExprToType(E, Context.getPointerType(Ty),
520                           CK_FunctionToPointerDecay).get();
521   } else if (Ty->isArrayType()) {
522     // In C90 mode, arrays only promote to pointers if the array expression is
523     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524     // type 'array of type' is converted to an expression that has type 'pointer
525     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
526     // that has type 'array of type' ...".  The relevant change is "an lvalue"
527     // (C90) to "an expression" (C99).
528     //
529     // C++ 4.2p1:
530     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531     // T" can be converted to an rvalue of type "pointer to T".
532     //
533     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535                                          CK_ArrayToPointerDecay);
536       if (Res.isInvalid())
537         return ExprError();
538       E = Res.get();
539     }
540   }
541   return E;
542 }
543 
544 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545   // Check to see if we are dereferencing a null pointer.  If so,
546   // and if not volatile-qualified, this is undefined behavior that the
547   // optimizer will delete, so warn about it.  People sometimes try to use this
548   // to get a deterministic trap and are surprised by clang's behavior.  This
549   // only handles the pattern "*null", which is a very syntactic check.
550   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551   if (UO && UO->getOpcode() == UO_Deref &&
552       UO->getSubExpr()->getType()->isPointerType()) {
553     const LangAS AS =
554         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555     if ((!isTargetAddressSpace(AS) ||
556          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559         !UO->getType().isVolatileQualified()) {
560       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561                             S.PDiag(diag::warn_indirection_through_null)
562                                 << UO->getSubExpr()->getSourceRange());
563       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                             S.PDiag(diag::note_indirection_through_null));
565     }
566   }
567 }
568 
569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570                                     SourceLocation AssignLoc,
571                                     const Expr* RHS) {
572   const ObjCIvarDecl *IV = OIRE->getDecl();
573   if (!IV)
574     return;
575 
576   DeclarationName MemberName = IV->getDeclName();
577   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578   if (!Member || !Member->isStr("isa"))
579     return;
580 
581   const Expr *Base = OIRE->getBase();
582   QualType BaseType = Base->getType();
583   if (OIRE->isArrow())
584     BaseType = BaseType->getPointeeType();
585   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587       ObjCInterfaceDecl *ClassDeclared = nullptr;
588       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589       if (!ClassDeclared->getSuperClass()
590           && (*ClassDeclared->ivar_begin()) == IV) {
591         if (RHS) {
592           NamedDecl *ObjectSetClass =
593             S.LookupSingleName(S.TUScope,
594                                &S.Context.Idents.get("object_setClass"),
595                                SourceLocation(), S.LookupOrdinaryName);
596           if (ObjectSetClass) {
597             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600                                               "object_setClass(")
601                 << FixItHint::CreateReplacement(
602                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
604           }
605           else
606             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607         } else {
608           NamedDecl *ObjectGetClass =
609             S.LookupSingleName(S.TUScope,
610                                &S.Context.Idents.get("object_getClass"),
611                                SourceLocation(), S.LookupOrdinaryName);
612           if (ObjectGetClass)
613             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615                                               "object_getClass(")
616                 << FixItHint::CreateReplacement(
617                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618           else
619             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620         }
621         S.Diag(IV->getLocation(), diag::note_ivar_decl);
622       }
623     }
624 }
625 
626 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627   // Handle any placeholder expressions which made it here.
628   if (E->hasPlaceholderType()) {
629     ExprResult result = CheckPlaceholderExpr(E);
630     if (result.isInvalid()) return ExprError();
631     E = result.get();
632   }
633 
634   // C++ [conv.lval]p1:
635   //   A glvalue of a non-function, non-array type T can be
636   //   converted to a prvalue.
637   if (!E->isGLValue()) return E;
638 
639   QualType T = E->getType();
640   assert(!T.isNull() && "r-value conversion on typeless expression?");
641 
642   // lvalue-to-rvalue conversion cannot be applied to function or array types.
643   if (T->isFunctionType() || T->isArrayType())
644     return E;
645 
646   // We don't want to throw lvalue-to-rvalue casts on top of
647   // expressions of certain types in C++.
648   if (getLangOpts().CPlusPlus &&
649       (E->getType() == Context.OverloadTy ||
650        T->isDependentType() ||
651        T->isRecordType()))
652     return E;
653 
654   // The C standard is actually really unclear on this point, and
655   // DR106 tells us what the result should be but not why.  It's
656   // generally best to say that void types just doesn't undergo
657   // lvalue-to-rvalue at all.  Note that expressions of unqualified
658   // 'void' type are never l-values, but qualified void can be.
659   if (T->isVoidType())
660     return E;
661 
662   // OpenCL usually rejects direct accesses to values of 'half' type.
663   if (getLangOpts().OpenCL &&
664       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665       T->isHalfType()) {
666     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667       << 0 << T;
668     return ExprError();
669   }
670 
671   CheckForNullPointerDereference(*this, E);
672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674                                      &Context.Idents.get("object_getClass"),
675                                      SourceLocation(), LookupOrdinaryName);
676     if (ObjectGetClass)
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679           << FixItHint::CreateReplacement(
680                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681     else
682       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683   }
684   else if (const ObjCIvarRefExpr *OIRE =
685             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687 
688   // C++ [conv.lval]p1:
689   //   [...] If T is a non-class type, the type of the prvalue is the
690   //   cv-unqualified version of T. Otherwise, the type of the
691   //   rvalue is T.
692   //
693   // C99 6.3.2.1p2:
694   //   If the lvalue has qualified type, the value has the unqualified
695   //   version of the type of the lvalue; otherwise, the value has the
696   //   type of the lvalue.
697   if (T.hasQualifiers())
698     T = T.getUnqualifiedType();
699 
700   // Under the MS ABI, lock down the inheritance model now.
701   if (T->isMemberPointerType() &&
702       Context.getTargetInfo().getCXXABI().isMicrosoft())
703     (void)isCompleteType(E->getExprLoc(), T);
704 
705   ExprResult Res = CheckLValueToRValueConversionOperand(E);
706   if (Res.isInvalid())
707     return Res;
708   E = Res.get();
709 
710   // Loading a __weak object implicitly retains the value, so we need a cleanup to
711   // balance that.
712   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716     Cleanup.setExprNeedsCleanups(true);
717 
718   // C++ [conv.lval]p3:
719   //   If T is cv std::nullptr_t, the result is a null pointer constant.
720   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722                                  CurFPFeatureOverrides());
723 
724   // C11 6.3.2.1p2:
725   //   ... if the lvalue has atomic type, the value has the non-atomic version
726   //   of the type of the lvalue ...
727   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728     T = Atomic->getValueType().getUnqualifiedType();
729     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730                                    nullptr, VK_PRValue, FPOptionsOverride());
731   }
732 
733   return Res;
734 }
735 
736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738   if (Res.isInvalid())
739     return ExprError();
740   Res = DefaultLvalueConversion(Res.get());
741   if (Res.isInvalid())
742     return ExprError();
743   return Res;
744 }
745 
746 /// CallExprUnaryConversions - a special case of an unary conversion
747 /// performed on a function designator of a call expression.
748 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749   QualType Ty = E->getType();
750   ExprResult Res = E;
751   // Only do implicit cast for a function type, but not for a pointer
752   // to function type.
753   if (Ty->isFunctionType()) {
754     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755                             CK_FunctionToPointerDecay);
756     if (Res.isInvalid())
757       return ExprError();
758   }
759   Res = DefaultLvalueConversion(Res.get());
760   if (Res.isInvalid())
761     return ExprError();
762   return Res.get();
763 }
764 
765 /// UsualUnaryConversions - Performs various conversions that are common to most
766 /// operators (C99 6.3). The conversions of array and function types are
767 /// sometimes suppressed. For example, the array->pointer conversion doesn't
768 /// apply if the array is an argument to the sizeof or address (&) operators.
769 /// In these instances, this routine should *not* be called.
770 ExprResult Sema::UsualUnaryConversions(Expr *E) {
771   // First, convert to an r-value.
772   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773   if (Res.isInvalid())
774     return ExprError();
775   E = Res.get();
776 
777   QualType Ty = E->getType();
778   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
779 
780   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782       (getLangOpts().getFPEvalMethod() !=
783            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784        PP.getLastFPEvalPragmaLocation().isValid())) {
785     switch (EvalMethod) {
786     default:
787       llvm_unreachable("Unrecognized float evaluation method");
788       break;
789     case LangOptions::FEM_UnsetOnCommandLine:
790       llvm_unreachable("Float evaluation method should be set by now");
791       break;
792     case LangOptions::FEM_Double:
793       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794         // Widen the expression to double.
795         return Ty->isComplexType()
796                    ? ImpCastExprToType(E,
797                                        Context.getComplexType(Context.DoubleTy),
798                                        CK_FloatingComplexCast)
799                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800       break;
801     case LangOptions::FEM_Extended:
802       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803         // Widen the expression to long double.
804         return Ty->isComplexType()
805                    ? ImpCastExprToType(
806                          E, Context.getComplexType(Context.LongDoubleTy),
807                          CK_FloatingComplexCast)
808                    : ImpCastExprToType(E, Context.LongDoubleTy,
809                                        CK_FloatingCast);
810       break;
811     }
812   }
813 
814   // Half FP have to be promoted to float unless it is natively supported
815   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817 
818   // Try to perform integral promotions if the object has a theoretically
819   // promotable type.
820   if (Ty->isIntegralOrUnscopedEnumerationType()) {
821     // C99 6.3.1.1p2:
822     //
823     //   The following may be used in an expression wherever an int or
824     //   unsigned int may be used:
825     //     - an object or expression with an integer type whose integer
826     //       conversion rank is less than or equal to the rank of int
827     //       and unsigned int.
828     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
829     //
830     //   If an int can represent all values of the original type, the
831     //   value is converted to an int; otherwise, it is converted to an
832     //   unsigned int. These are called the integer promotions. All
833     //   other types are unchanged by the integer promotions.
834 
835     QualType PTy = Context.isPromotableBitField(E);
836     if (!PTy.isNull()) {
837       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838       return E;
839     }
840     if (Ty->isPromotableIntegerType()) {
841       QualType PT = Context.getPromotedIntegerType(Ty);
842       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843       return E;
844     }
845   }
846   return E;
847 }
848 
849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850 /// do not have a prototype. Arguments that have type float or __fp16
851 /// are promoted to double. All other argument types are converted by
852 /// UsualUnaryConversions().
853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854   QualType Ty = E->getType();
855   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
856 
857   ExprResult Res = UsualUnaryConversions(E);
858   if (Res.isInvalid())
859     return ExprError();
860   E = Res.get();
861 
862   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
863   // promote to double.
864   // Note that default argument promotion applies only to float (and
865   // half/fp16); it does not apply to _Float16.
866   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867   if (BTy && (BTy->getKind() == BuiltinType::Half ||
868               BTy->getKind() == BuiltinType::Float)) {
869     if (getLangOpts().OpenCL &&
870         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871       if (BTy->getKind() == BuiltinType::Half) {
872         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873       }
874     } else {
875       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876     }
877   }
878   if (BTy &&
879       getLangOpts().getExtendIntArgs() ==
880           LangOptions::ExtendArgsKind::ExtendTo64 &&
881       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882       Context.getTypeSizeInChars(BTy) <
883           Context.getTypeSizeInChars(Context.LongLongTy)) {
884     E = (Ty->isUnsignedIntegerType())
885             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886                   .get()
887             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
889            "Unexpected typesize for LongLongTy");
890   }
891 
892   // C++ performs lvalue-to-rvalue conversion as a default argument
893   // promotion, even on class types, but note:
894   //   C++11 [conv.lval]p2:
895   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
896   //     operand or a subexpression thereof the value contained in the
897   //     referenced object is not accessed. Otherwise, if the glvalue
898   //     has a class type, the conversion copy-initializes a temporary
899   //     of type T from the glvalue and the result of the conversion
900   //     is a prvalue for the temporary.
901   // FIXME: add some way to gate this entire thing for correctness in
902   // potentially potentially evaluated contexts.
903   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904     ExprResult Temp = PerformCopyInitialization(
905                        InitializedEntity::InitializeTemporary(E->getType()),
906                                                 E->getExprLoc(), E);
907     if (Temp.isInvalid())
908       return ExprError();
909     E = Temp.get();
910   }
911 
912   return E;
913 }
914 
915 /// Determine the degree of POD-ness for an expression.
916 /// Incomplete types are considered POD, since this check can be performed
917 /// when we're in an unevaluated context.
918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919   if (Ty->isIncompleteType()) {
920     // C++11 [expr.call]p7:
921     //   After these conversions, if the argument does not have arithmetic,
922     //   enumeration, pointer, pointer to member, or class type, the program
923     //   is ill-formed.
924     //
925     // Since we've already performed array-to-pointer and function-to-pointer
926     // decay, the only such type in C++ is cv void. This also handles
927     // initializer lists as variadic arguments.
928     if (Ty->isVoidType())
929       return VAK_Invalid;
930 
931     if (Ty->isObjCObjectType())
932       return VAK_Invalid;
933     return VAK_Valid;
934   }
935 
936   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937     return VAK_Invalid;
938 
939   if (Ty.isCXX98PODType(Context))
940     return VAK_Valid;
941 
942   // C++11 [expr.call]p7:
943   //   Passing a potentially-evaluated argument of class type (Clause 9)
944   //   having a non-trivial copy constructor, a non-trivial move constructor,
945   //   or a non-trivial destructor, with no corresponding parameter,
946   //   is conditionally-supported with implementation-defined semantics.
947   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949       if (!Record->hasNonTrivialCopyConstructor() &&
950           !Record->hasNonTrivialMoveConstructor() &&
951           !Record->hasNonTrivialDestructor())
952         return VAK_ValidInCXX11;
953 
954   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955     return VAK_Valid;
956 
957   if (Ty->isObjCObjectType())
958     return VAK_Invalid;
959 
960   if (getLangOpts().MSVCCompat)
961     return VAK_MSVCUndefined;
962 
963   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964   // permitted to reject them. We should consider doing so.
965   return VAK_Undefined;
966 }
967 
968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969   // Don't allow one to pass an Objective-C interface to a vararg.
970   const QualType &Ty = E->getType();
971   VarArgKind VAK = isValidVarArgType(Ty);
972 
973   // Complain about passing non-POD types through varargs.
974   switch (VAK) {
975   case VAK_ValidInCXX11:
976     DiagRuntimeBehavior(
977         E->getBeginLoc(), nullptr,
978         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979     LLVM_FALLTHROUGH;
980   case VAK_Valid:
981     if (Ty->isRecordType()) {
982       // This is unlikely to be what the user intended. If the class has a
983       // 'c_str' member function, the user probably meant to call that.
984       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985                           PDiag(diag::warn_pass_class_arg_to_vararg)
986                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
987     }
988     break;
989 
990   case VAK_Undefined:
991   case VAK_MSVCUndefined:
992     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994                             << getLangOpts().CPlusPlus11 << Ty << CT);
995     break;
996 
997   case VAK_Invalid:
998     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999       Diag(E->getBeginLoc(),
1000            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001           << Ty << CT;
1002     else if (Ty->isObjCObjectType())
1003       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005                               << Ty << CT);
1006     else
1007       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008           << isa<InitListExpr>(E) << Ty << CT;
1009     break;
1010   }
1011 }
1012 
1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014 /// will create a trap if the resulting type is not a POD type.
1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016                                                   FunctionDecl *FDecl) {
1017   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018     // Strip the unbridged-cast placeholder expression off, if applicable.
1019     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020         (CT == VariadicMethod ||
1021          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022       E = stripARCUnbridgedCast(E);
1023 
1024     // Otherwise, do normal placeholder checking.
1025     } else {
1026       ExprResult ExprRes = CheckPlaceholderExpr(E);
1027       if (ExprRes.isInvalid())
1028         return ExprError();
1029       E = ExprRes.get();
1030     }
1031   }
1032 
1033   ExprResult ExprRes = DefaultArgumentPromotion(E);
1034   if (ExprRes.isInvalid())
1035     return ExprError();
1036 
1037   // Copy blocks to the heap.
1038   if (ExprRes.get()->getType()->isBlockPointerType())
1039     maybeExtendBlockObject(ExprRes);
1040 
1041   E = ExprRes.get();
1042 
1043   // Diagnostics regarding non-POD argument types are
1044   // emitted along with format string checking in Sema::CheckFunctionCall().
1045   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046     // Turn this into a trap.
1047     CXXScopeSpec SS;
1048     SourceLocation TemplateKWLoc;
1049     UnqualifiedId Name;
1050     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051                        E->getBeginLoc());
1052     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053                                           /*HasTrailingLParen=*/true,
1054                                           /*IsAddressOfOperand=*/false);
1055     if (TrapFn.isInvalid())
1056       return ExprError();
1057 
1058     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059                                     None, E->getEndLoc());
1060     if (Call.isInvalid())
1061       return ExprError();
1062 
1063     ExprResult Comma =
1064         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065     if (Comma.isInvalid())
1066       return ExprError();
1067     return Comma.get();
1068   }
1069 
1070   if (!getLangOpts().CPlusPlus &&
1071       RequireCompleteType(E->getExprLoc(), E->getType(),
1072                           diag::err_call_incomplete_argument))
1073     return ExprError();
1074 
1075   return E;
1076 }
1077 
1078 /// Converts an integer to complex float type.  Helper function of
1079 /// UsualArithmeticConversions()
1080 ///
1081 /// \return false if the integer expression is an integer type and is
1082 /// successfully converted to the complex type.
1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084                                                   ExprResult &ComplexExpr,
1085                                                   QualType IntTy,
1086                                                   QualType ComplexTy,
1087                                                   bool SkipCast) {
1088   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089   if (SkipCast) return false;
1090   if (IntTy->isIntegerType()) {
1091     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094                                   CK_FloatingRealToComplex);
1095   } else {
1096     assert(IntTy->isComplexIntegerType());
1097     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098                                   CK_IntegralComplexToFloatingComplex);
1099   }
1100   return false;
1101 }
1102 
1103 /// Handle arithmetic conversion with complex types.  Helper function of
1104 /// UsualArithmeticConversions()
1105 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106                                              ExprResult &RHS, QualType LHSType,
1107                                              QualType RHSType,
1108                                              bool IsCompAssign) {
1109   // if we have an integer operand, the result is the complex type.
1110   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111                                              /*skipCast*/false))
1112     return LHSType;
1113   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114                                              /*skipCast*/IsCompAssign))
1115     return RHSType;
1116 
1117   // This handles complex/complex, complex/float, or float/complex.
1118   // When both operands are complex, the shorter operand is converted to the
1119   // type of the longer, and that is the type of the result. This corresponds
1120   // to what is done when combining two real floating-point operands.
1121   // The fun begins when size promotion occur across type domains.
1122   // From H&S 6.3.4: When one operand is complex and the other is a real
1123   // floating-point type, the less precise type is converted, within it's
1124   // real or complex domain, to the precision of the other type. For example,
1125   // when combining a "long double" with a "double _Complex", the
1126   // "double _Complex" is promoted to "long double _Complex".
1127 
1128   // Compute the rank of the two types, regardless of whether they are complex.
1129   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130 
1131   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133   QualType LHSElementType =
1134       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1135   QualType RHSElementType =
1136       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1137 
1138   QualType ResultType = S.Context.getComplexType(LHSElementType);
1139   if (Order < 0) {
1140     // Promote the precision of the LHS if not an assignment.
1141     ResultType = S.Context.getComplexType(RHSElementType);
1142     if (!IsCompAssign) {
1143       if (LHSComplexType)
1144         LHS =
1145             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146       else
1147         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148     }
1149   } else if (Order > 0) {
1150     // Promote the precision of the RHS.
1151     if (RHSComplexType)
1152       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153     else
1154       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155   }
1156   return ResultType;
1157 }
1158 
1159 /// Handle arithmetic conversion from integer to float.  Helper function
1160 /// of UsualArithmeticConversions()
1161 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162                                            ExprResult &IntExpr,
1163                                            QualType FloatTy, QualType IntTy,
1164                                            bool ConvertFloat, bool ConvertInt) {
1165   if (IntTy->isIntegerType()) {
1166     if (ConvertInt)
1167       // Convert intExpr to the lhs floating point type.
1168       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169                                     CK_IntegralToFloating);
1170     return FloatTy;
1171   }
1172 
1173   // Convert both sides to the appropriate complex float.
1174   assert(IntTy->isComplexIntegerType());
1175   QualType result = S.Context.getComplexType(FloatTy);
1176 
1177   // _Complex int -> _Complex float
1178   if (ConvertInt)
1179     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180                                   CK_IntegralComplexToFloatingComplex);
1181 
1182   // float -> _Complex float
1183   if (ConvertFloat)
1184     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185                                     CK_FloatingRealToComplex);
1186 
1187   return result;
1188 }
1189 
1190 /// Handle arithmethic conversion with floating point types.  Helper
1191 /// function of UsualArithmeticConversions()
1192 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193                                       ExprResult &RHS, QualType LHSType,
1194                                       QualType RHSType, bool IsCompAssign) {
1195   bool LHSFloat = LHSType->isRealFloatingType();
1196   bool RHSFloat = RHSType->isRealFloatingType();
1197 
1198   // N1169 4.1.4: If one of the operands has a floating type and the other
1199   //              operand has a fixed-point type, the fixed-point operand
1200   //              is converted to the floating type [...]
1201   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1202     if (LHSFloat)
1203       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204     else if (!IsCompAssign)
1205       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206     return LHSFloat ? LHSType : RHSType;
1207   }
1208 
1209   // If we have two real floating types, convert the smaller operand
1210   // to the bigger result.
1211   if (LHSFloat && RHSFloat) {
1212     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213     if (order > 0) {
1214       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215       return LHSType;
1216     }
1217 
1218     assert(order < 0 && "illegal float comparison");
1219     if (!IsCompAssign)
1220       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221     return RHSType;
1222   }
1223 
1224   if (LHSFloat) {
1225     // Half FP has to be promoted to float unless it is natively supported
1226     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1227       LHSType = S.Context.FloatTy;
1228 
1229     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230                                       /*ConvertFloat=*/!IsCompAssign,
1231                                       /*ConvertInt=*/ true);
1232   }
1233   assert(RHSFloat);
1234   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235                                     /*ConvertFloat=*/ true,
1236                                     /*ConvertInt=*/!IsCompAssign);
1237 }
1238 
1239 /// Diagnose attempts to convert between __float128, __ibm128 and
1240 /// long double if there is no support for such conversion.
1241 /// Helper function of UsualArithmeticConversions().
1242 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243                                       QualType RHSType) {
1244   // No issue if either is not a floating point type.
1245   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1246     return false;
1247 
1248   // No issue if both have the same 128-bit float semantics.
1249   auto *LHSComplex = LHSType->getAs<ComplexType>();
1250   auto *RHSComplex = RHSType->getAs<ComplexType>();
1251 
1252   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1253   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254 
1255   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257 
1258   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1260       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1261        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1262     return false;
1263 
1264   return true;
1265 }
1266 
1267 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268 
1269 namespace {
1270 /// These helper callbacks are placed in an anonymous namespace to
1271 /// permit their use as function template parameters.
1272 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274 }
1275 
1276 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278                              CK_IntegralComplexCast);
1279 }
1280 }
1281 
1282 /// Handle integer arithmetic conversions.  Helper function of
1283 /// UsualArithmeticConversions()
1284 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286                                         ExprResult &RHS, QualType LHSType,
1287                                         QualType RHSType, bool IsCompAssign) {
1288   // The rules for this case are in C99 6.3.1.8
1289   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292   if (LHSSigned == RHSSigned) {
1293     // Same signedness; use the higher-ranked type
1294     if (order >= 0) {
1295       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296       return LHSType;
1297     } else if (!IsCompAssign)
1298       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299     return RHSType;
1300   } else if (order != (LHSSigned ? 1 : -1)) {
1301     // The unsigned type has greater than or equal rank to the
1302     // signed type, so use the unsigned type
1303     if (RHSSigned) {
1304       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305       return LHSType;
1306     } else if (!IsCompAssign)
1307       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308     return RHSType;
1309   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1310     // The two types are different widths; if we are here, that
1311     // means the signed type is larger than the unsigned type, so
1312     // use the signed type.
1313     if (LHSSigned) {
1314       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315       return LHSType;
1316     } else if (!IsCompAssign)
1317       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318     return RHSType;
1319   } else {
1320     // The signed type is higher-ranked than the unsigned type,
1321     // but isn't actually any bigger (like unsigned int and long
1322     // on most 32-bit systems).  Use the unsigned type corresponding
1323     // to the signed type.
1324     QualType result =
1325       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326     RHS = (*doRHSCast)(S, RHS.get(), result);
1327     if (!IsCompAssign)
1328       LHS = (*doLHSCast)(S, LHS.get(), result);
1329     return result;
1330   }
1331 }
1332 
1333 /// Handle conversions with GCC complex int extension.  Helper function
1334 /// of UsualArithmeticConversions()
1335 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336                                            ExprResult &RHS, QualType LHSType,
1337                                            QualType RHSType,
1338                                            bool IsCompAssign) {
1339   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341 
1342   if (LHSComplexInt && RHSComplexInt) {
1343     QualType LHSEltType = LHSComplexInt->getElementType();
1344     QualType RHSEltType = RHSComplexInt->getElementType();
1345     QualType ScalarType =
1346       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348 
1349     return S.Context.getComplexType(ScalarType);
1350   }
1351 
1352   if (LHSComplexInt) {
1353     QualType LHSEltType = LHSComplexInt->getElementType();
1354     QualType ScalarType =
1355       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357     QualType ComplexType = S.Context.getComplexType(ScalarType);
1358     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359                               CK_IntegralRealToComplex);
1360 
1361     return ComplexType;
1362   }
1363 
1364   assert(RHSComplexInt);
1365 
1366   QualType RHSEltType = RHSComplexInt->getElementType();
1367   QualType ScalarType =
1368     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370   QualType ComplexType = S.Context.getComplexType(ScalarType);
1371 
1372   if (!IsCompAssign)
1373     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374                               CK_IntegralRealToComplex);
1375   return ComplexType;
1376 }
1377 
1378 /// Return the rank of a given fixed point or integer type. The value itself
1379 /// doesn't matter, but the values must be increasing with proper increasing
1380 /// rank as described in N1169 4.1.1.
1381 static unsigned GetFixedPointRank(QualType Ty) {
1382   const auto *BTy = Ty->getAs<BuiltinType>();
1383   assert(BTy && "Expected a builtin type.");
1384 
1385   switch (BTy->getKind()) {
1386   case BuiltinType::ShortFract:
1387   case BuiltinType::UShortFract:
1388   case BuiltinType::SatShortFract:
1389   case BuiltinType::SatUShortFract:
1390     return 1;
1391   case BuiltinType::Fract:
1392   case BuiltinType::UFract:
1393   case BuiltinType::SatFract:
1394   case BuiltinType::SatUFract:
1395     return 2;
1396   case BuiltinType::LongFract:
1397   case BuiltinType::ULongFract:
1398   case BuiltinType::SatLongFract:
1399   case BuiltinType::SatULongFract:
1400     return 3;
1401   case BuiltinType::ShortAccum:
1402   case BuiltinType::UShortAccum:
1403   case BuiltinType::SatShortAccum:
1404   case BuiltinType::SatUShortAccum:
1405     return 4;
1406   case BuiltinType::Accum:
1407   case BuiltinType::UAccum:
1408   case BuiltinType::SatAccum:
1409   case BuiltinType::SatUAccum:
1410     return 5;
1411   case BuiltinType::LongAccum:
1412   case BuiltinType::ULongAccum:
1413   case BuiltinType::SatLongAccum:
1414   case BuiltinType::SatULongAccum:
1415     return 6;
1416   default:
1417     if (BTy->isInteger())
1418       return 0;
1419     llvm_unreachable("Unexpected fixed point or integer type");
1420   }
1421 }
1422 
1423 /// handleFixedPointConversion - Fixed point operations between fixed
1424 /// point types and integers or other fixed point types do not fall under
1425 /// usual arithmetic conversion since these conversions could result in loss
1426 /// of precsision (N1169 4.1.4). These operations should be calculated with
1427 /// the full precision of their result type (N1169 4.1.6.2.1).
1428 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429                                            QualType RHSTy) {
1430   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1431          "Expected at least one of the operands to be a fixed point type");
1432   assert((LHSTy->isFixedPointOrIntegerType() ||
1433           RHSTy->isFixedPointOrIntegerType()) &&
1434          "Special fixed point arithmetic operation conversions are only "
1435          "applied to ints or other fixed point types");
1436 
1437   // If one operand has signed fixed-point type and the other operand has
1438   // unsigned fixed-point type, then the unsigned fixed-point operand is
1439   // converted to its corresponding signed fixed-point type and the resulting
1440   // type is the type of the converted operand.
1441   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1442     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1444     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445 
1446   // The result type is the type with the highest rank, whereby a fixed-point
1447   // conversion rank is always greater than an integer conversion rank; if the
1448   // type of either of the operands is a saturating fixedpoint type, the result
1449   // type shall be the saturating fixed-point type corresponding to the type
1450   // with the highest rank; the resulting value is converted (taking into
1451   // account rounding and overflow) to the precision of the resulting type.
1452   // Same ranks between signed and unsigned types are resolved earlier, so both
1453   // types are either signed or both unsigned at this point.
1454   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456 
1457   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458 
1459   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1460     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461 
1462   return ResultTy;
1463 }
1464 
1465 /// Check that the usual arithmetic conversions can be performed on this pair of
1466 /// expressions that might be of enumeration type.
1467 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468                                            SourceLocation Loc,
1469                                            Sema::ArithConvKind ACK) {
1470   // C++2a [expr.arith.conv]p1:
1471   //   If one operand is of enumeration type and the other operand is of a
1472   //   different enumeration type or a floating-point type, this behavior is
1473   //   deprecated ([depr.arith.conv.enum]).
1474   //
1475   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476   // Eventually we will presumably reject these cases (in C++23 onwards?).
1477   QualType L = LHS->getType(), R = RHS->getType();
1478   bool LEnum = L->isUnscopedEnumerationType(),
1479        REnum = R->isUnscopedEnumerationType();
1480   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1482       (REnum && L->isFloatingType())) {
1483     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484                     ? diag::warn_arith_conv_enum_float_cxx20
1485                     : diag::warn_arith_conv_enum_float)
1486         << LHS->getSourceRange() << RHS->getSourceRange()
1487         << (int)ACK << LEnum << L << R;
1488   } else if (!IsCompAssign && LEnum && REnum &&
1489              !S.Context.hasSameUnqualifiedType(L, R)) {
1490     unsigned DiagID;
1491     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1493       // If either enumeration type is unnamed, it's less likely that the
1494       // user cares about this, but this situation is still deprecated in
1495       // C++2a. Use a different warning group.
1496       DiagID = S.getLangOpts().CPlusPlus20
1497                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1498                     : diag::warn_arith_conv_mixed_anon_enum_types;
1499     } else if (ACK == Sema::ACK_Conditional) {
1500       // Conditional expressions are separated out because they have
1501       // historically had a different warning flag.
1502       DiagID = S.getLangOpts().CPlusPlus20
1503                    ? diag::warn_conditional_mixed_enum_types_cxx20
1504                    : diag::warn_conditional_mixed_enum_types;
1505     } else if (ACK == Sema::ACK_Comparison) {
1506       // Comparison expressions are separated out because they have
1507       // historically had a different warning flag.
1508       DiagID = S.getLangOpts().CPlusPlus20
1509                    ? diag::warn_comparison_mixed_enum_types_cxx20
1510                    : diag::warn_comparison_mixed_enum_types;
1511     } else {
1512       DiagID = S.getLangOpts().CPlusPlus20
1513                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1514                    : diag::warn_arith_conv_mixed_enum_types;
1515     }
1516     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517                         << (int)ACK << L << R;
1518   }
1519 }
1520 
1521 /// UsualArithmeticConversions - Performs various conversions that are common to
1522 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523 /// routine returns the first non-arithmetic type found. The client is
1524 /// responsible for emitting appropriate error diagnostics.
1525 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526                                           SourceLocation Loc,
1527                                           ArithConvKind ACK) {
1528   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529 
1530   if (ACK != ACK_CompAssign) {
1531     LHS = UsualUnaryConversions(LHS.get());
1532     if (LHS.isInvalid())
1533       return QualType();
1534   }
1535 
1536   RHS = UsualUnaryConversions(RHS.get());
1537   if (RHS.isInvalid())
1538     return QualType();
1539 
1540   // For conversion purposes, we ignore any qualifiers.
1541   // For example, "const float" and "float" are equivalent.
1542   QualType LHSType =
1543     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544   QualType RHSType =
1545     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546 
1547   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549     LHSType = AtomicLHS->getValueType();
1550 
1551   // If both types are identical, no conversion is needed.
1552   if (LHSType == RHSType)
1553     return LHSType;
1554 
1555   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556   // The caller can deal with this (e.g. pointer + int).
1557   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1558     return QualType();
1559 
1560   // Apply unary and bitfield promotions to the LHS's type.
1561   QualType LHSUnpromotedType = LHSType;
1562   if (LHSType->isPromotableIntegerType())
1563     LHSType = Context.getPromotedIntegerType(LHSType);
1564   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565   if (!LHSBitfieldPromoteTy.isNull())
1566     LHSType = LHSBitfieldPromoteTy;
1567   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1568     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569 
1570   // If both types are identical, no conversion is needed.
1571   if (LHSType == RHSType)
1572     return LHSType;
1573 
1574   // At this point, we have two different arithmetic types.
1575 
1576   // Diagnose attempts to convert between __ibm128, __float128 and long double
1577   // where such conversions currently can't be handled.
1578   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579     return QualType();
1580 
1581   // Handle complex types first (C99 6.3.1.8p1).
1582   if (LHSType->isComplexType() || RHSType->isComplexType())
1583     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584                                         ACK == ACK_CompAssign);
1585 
1586   // Now handle "real" floating types (i.e. float, double, long double).
1587   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1588     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589                                  ACK == ACK_CompAssign);
1590 
1591   // Handle GCC complex int extension.
1592   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1593     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594                                       ACK == ACK_CompAssign);
1595 
1596   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1597     return handleFixedPointConversion(*this, LHSType, RHSType);
1598 
1599   // Finally, we have two differing integer types.
1600   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602 }
1603 
1604 //===----------------------------------------------------------------------===//
1605 //  Semantic Analysis for various Expression Types
1606 //===----------------------------------------------------------------------===//
1607 
1608 
1609 ExprResult
1610 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611                                 SourceLocation DefaultLoc,
1612                                 SourceLocation RParenLoc,
1613                                 Expr *ControllingExpr,
1614                                 ArrayRef<ParsedType> ArgTypes,
1615                                 ArrayRef<Expr *> ArgExprs) {
1616   unsigned NumAssocs = ArgTypes.size();
1617   assert(NumAssocs == ArgExprs.size());
1618 
1619   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620   for (unsigned i = 0; i < NumAssocs; ++i) {
1621     if (ArgTypes[i])
1622       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623     else
1624       Types[i] = nullptr;
1625   }
1626 
1627   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628                                              ControllingExpr,
1629                                              llvm::makeArrayRef(Types, NumAssocs),
1630                                              ArgExprs);
1631   delete [] Types;
1632   return ER;
1633 }
1634 
1635 ExprResult
1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637                                  SourceLocation DefaultLoc,
1638                                  SourceLocation RParenLoc,
1639                                  Expr *ControllingExpr,
1640                                  ArrayRef<TypeSourceInfo *> Types,
1641                                  ArrayRef<Expr *> Exprs) {
1642   unsigned NumAssocs = Types.size();
1643   assert(NumAssocs == Exprs.size());
1644 
1645   // Decay and strip qualifiers for the controlling expression type, and handle
1646   // placeholder type replacement. See committee discussion from WG14 DR423.
1647   {
1648     EnterExpressionEvaluationContext Unevaluated(
1649         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651     if (R.isInvalid())
1652       return ExprError();
1653     ControllingExpr = R.get();
1654   }
1655 
1656   bool TypeErrorFound = false,
1657        IsResultDependent = ControllingExpr->isTypeDependent(),
1658        ContainsUnexpandedParameterPack
1659          = ControllingExpr->containsUnexpandedParameterPack();
1660 
1661   // The controlling expression is an unevaluated operand, so side effects are
1662   // likely unintended.
1663   if (!inTemplateInstantiation() && !IsResultDependent &&
1664       ControllingExpr->HasSideEffects(Context, false))
1665     Diag(ControllingExpr->getExprLoc(),
1666          diag::warn_side_effects_unevaluated_context);
1667 
1668   for (unsigned i = 0; i < NumAssocs; ++i) {
1669     if (Exprs[i]->containsUnexpandedParameterPack())
1670       ContainsUnexpandedParameterPack = true;
1671 
1672     if (Types[i]) {
1673       if (Types[i]->getType()->containsUnexpandedParameterPack())
1674         ContainsUnexpandedParameterPack = true;
1675 
1676       if (Types[i]->getType()->isDependentType()) {
1677         IsResultDependent = true;
1678       } else {
1679         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680         // complete object type other than a variably modified type."
1681         unsigned D = 0;
1682         if (Types[i]->getType()->isIncompleteType())
1683           D = diag::err_assoc_type_incomplete;
1684         else if (!Types[i]->getType()->isObjectType())
1685           D = diag::err_assoc_type_nonobject;
1686         else if (Types[i]->getType()->isVariablyModifiedType())
1687           D = diag::err_assoc_type_variably_modified;
1688         else {
1689           // Because the controlling expression undergoes lvalue conversion,
1690           // array conversion, and function conversion, an association which is
1691           // of array type, function type, or is qualified can never be
1692           // reached. We will warn about this so users are less surprised by
1693           // the unreachable association. However, we don't have to handle
1694           // function types; that's not an object type, so it's handled above.
1695           //
1696           // The logic is somewhat different for C++ because C++ has different
1697           // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1698           // If T is a non-class type, the type of the prvalue is the cv-
1699           // unqualified version of T. Otherwise, the type of the prvalue is T.
1700           // The result of these rules is that all qualified types in an
1701           // association in C are unreachable, and in C++, only qualified non-
1702           // class types are unreachable.
1703           unsigned Reason = 0;
1704           QualType QT = Types[i]->getType();
1705           if (QT->isArrayType())
1706             Reason = 1;
1707           else if (QT.hasQualifiers() &&
1708                    (!LangOpts.CPlusPlus || !QT->isRecordType()))
1709             Reason = 2;
1710 
1711           if (Reason)
1712             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1713                  diag::warn_unreachable_association)
1714                 << QT << (Reason - 1);
1715         }
1716 
1717         if (D != 0) {
1718           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1719             << Types[i]->getTypeLoc().getSourceRange()
1720             << Types[i]->getType();
1721           TypeErrorFound = true;
1722         }
1723 
1724         // C11 6.5.1.1p2 "No two generic associations in the same generic
1725         // selection shall specify compatible types."
1726         for (unsigned j = i+1; j < NumAssocs; ++j)
1727           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1728               Context.typesAreCompatible(Types[i]->getType(),
1729                                          Types[j]->getType())) {
1730             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1731                  diag::err_assoc_compatible_types)
1732               << Types[j]->getTypeLoc().getSourceRange()
1733               << Types[j]->getType()
1734               << Types[i]->getType();
1735             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1736                  diag::note_compat_assoc)
1737               << Types[i]->getTypeLoc().getSourceRange()
1738               << Types[i]->getType();
1739             TypeErrorFound = true;
1740           }
1741       }
1742     }
1743   }
1744   if (TypeErrorFound)
1745     return ExprError();
1746 
1747   // If we determined that the generic selection is result-dependent, don't
1748   // try to compute the result expression.
1749   if (IsResultDependent)
1750     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1751                                         Exprs, DefaultLoc, RParenLoc,
1752                                         ContainsUnexpandedParameterPack);
1753 
1754   SmallVector<unsigned, 1> CompatIndices;
1755   unsigned DefaultIndex = -1U;
1756   for (unsigned i = 0; i < NumAssocs; ++i) {
1757     if (!Types[i])
1758       DefaultIndex = i;
1759     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1760                                         Types[i]->getType()))
1761       CompatIndices.push_back(i);
1762   }
1763 
1764   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1765   // type compatible with at most one of the types named in its generic
1766   // association list."
1767   if (CompatIndices.size() > 1) {
1768     // We strip parens here because the controlling expression is typically
1769     // parenthesized in macro definitions.
1770     ControllingExpr = ControllingExpr->IgnoreParens();
1771     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1772         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1773         << (unsigned)CompatIndices.size();
1774     for (unsigned I : CompatIndices) {
1775       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1776            diag::note_compat_assoc)
1777         << Types[I]->getTypeLoc().getSourceRange()
1778         << Types[I]->getType();
1779     }
1780     return ExprError();
1781   }
1782 
1783   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1784   // its controlling expression shall have type compatible with exactly one of
1785   // the types named in its generic association list."
1786   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1787     // We strip parens here because the controlling expression is typically
1788     // parenthesized in macro definitions.
1789     ControllingExpr = ControllingExpr->IgnoreParens();
1790     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1791         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1792     return ExprError();
1793   }
1794 
1795   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1796   // type name that is compatible with the type of the controlling expression,
1797   // then the result expression of the generic selection is the expression
1798   // in that generic association. Otherwise, the result expression of the
1799   // generic selection is the expression in the default generic association."
1800   unsigned ResultIndex =
1801     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1802 
1803   return GenericSelectionExpr::Create(
1804       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1805       ContainsUnexpandedParameterPack, ResultIndex);
1806 }
1807 
1808 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1809 /// location of the token and the offset of the ud-suffix within it.
1810 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1811                                      unsigned Offset) {
1812   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1813                                         S.getLangOpts());
1814 }
1815 
1816 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1817 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1818 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1819                                                  IdentifierInfo *UDSuffix,
1820                                                  SourceLocation UDSuffixLoc,
1821                                                  ArrayRef<Expr*> Args,
1822                                                  SourceLocation LitEndLoc) {
1823   assert(Args.size() <= 2 && "too many arguments for literal operator");
1824 
1825   QualType ArgTy[2];
1826   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1827     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1828     if (ArgTy[ArgIdx]->isArrayType())
1829       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1830   }
1831 
1832   DeclarationName OpName =
1833     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1834   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1835   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1836 
1837   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1838   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1839                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1840                               /*AllowStringTemplatePack*/ false,
1841                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1842     return ExprError();
1843 
1844   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1845 }
1846 
1847 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1848 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1849 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1850 /// multiple tokens.  However, the common case is that StringToks points to one
1851 /// string.
1852 ///
1853 ExprResult
1854 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1855   assert(!StringToks.empty() && "Must have at least one string!");
1856 
1857   StringLiteralParser Literal(StringToks, PP);
1858   if (Literal.hadError)
1859     return ExprError();
1860 
1861   SmallVector<SourceLocation, 4> StringTokLocs;
1862   for (const Token &Tok : StringToks)
1863     StringTokLocs.push_back(Tok.getLocation());
1864 
1865   QualType CharTy = Context.CharTy;
1866   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1867   if (Literal.isWide()) {
1868     CharTy = Context.getWideCharType();
1869     Kind = StringLiteral::Wide;
1870   } else if (Literal.isUTF8()) {
1871     if (getLangOpts().Char8)
1872       CharTy = Context.Char8Ty;
1873     Kind = StringLiteral::UTF8;
1874   } else if (Literal.isUTF16()) {
1875     CharTy = Context.Char16Ty;
1876     Kind = StringLiteral::UTF16;
1877   } else if (Literal.isUTF32()) {
1878     CharTy = Context.Char32Ty;
1879     Kind = StringLiteral::UTF32;
1880   } else if (Literal.isPascal()) {
1881     CharTy = Context.UnsignedCharTy;
1882   }
1883 
1884   // Warn on initializing an array of char from a u8 string literal; this
1885   // becomes ill-formed in C++2a.
1886   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1887       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1888     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1889 
1890     // Create removals for all 'u8' prefixes in the string literal(s). This
1891     // ensures C++2a compatibility (but may change the program behavior when
1892     // built by non-Clang compilers for which the execution character set is
1893     // not always UTF-8).
1894     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1895     SourceLocation RemovalDiagLoc;
1896     for (const Token &Tok : StringToks) {
1897       if (Tok.getKind() == tok::utf8_string_literal) {
1898         if (RemovalDiagLoc.isInvalid())
1899           RemovalDiagLoc = Tok.getLocation();
1900         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1901             Tok.getLocation(),
1902             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1903                                            getSourceManager(), getLangOpts())));
1904       }
1905     }
1906     Diag(RemovalDiagLoc, RemovalDiag);
1907   }
1908 
1909   QualType StrTy =
1910       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1911 
1912   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1913   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1914                                              Kind, Literal.Pascal, StrTy,
1915                                              &StringTokLocs[0],
1916                                              StringTokLocs.size());
1917   if (Literal.getUDSuffix().empty())
1918     return Lit;
1919 
1920   // We're building a user-defined literal.
1921   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1922   SourceLocation UDSuffixLoc =
1923     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1924                    Literal.getUDSuffixOffset());
1925 
1926   // Make sure we're allowed user-defined literals here.
1927   if (!UDLScope)
1928     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1929 
1930   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1931   //   operator "" X (str, len)
1932   QualType SizeType = Context.getSizeType();
1933 
1934   DeclarationName OpName =
1935     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1936   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1937   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1938 
1939   QualType ArgTy[] = {
1940     Context.getArrayDecayedType(StrTy), SizeType
1941   };
1942 
1943   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1944   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1945                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1946                                 /*AllowStringTemplatePack*/ true,
1947                                 /*DiagnoseMissing*/ true, Lit)) {
1948 
1949   case LOLR_Cooked: {
1950     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1951     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1952                                                     StringTokLocs[0]);
1953     Expr *Args[] = { Lit, LenArg };
1954 
1955     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1956   }
1957 
1958   case LOLR_Template: {
1959     TemplateArgumentListInfo ExplicitArgs;
1960     TemplateArgument Arg(Lit);
1961     TemplateArgumentLocInfo ArgInfo(Lit);
1962     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1963     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1964                                     &ExplicitArgs);
1965   }
1966 
1967   case LOLR_StringTemplatePack: {
1968     TemplateArgumentListInfo ExplicitArgs;
1969 
1970     unsigned CharBits = Context.getIntWidth(CharTy);
1971     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1972     llvm::APSInt Value(CharBits, CharIsUnsigned);
1973 
1974     TemplateArgument TypeArg(CharTy);
1975     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1976     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1977 
1978     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1979       Value = Lit->getCodeUnit(I);
1980       TemplateArgument Arg(Context, Value, CharTy);
1981       TemplateArgumentLocInfo ArgInfo;
1982       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1983     }
1984     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1985                                     &ExplicitArgs);
1986   }
1987   case LOLR_Raw:
1988   case LOLR_ErrorNoDiagnostic:
1989     llvm_unreachable("unexpected literal operator lookup result");
1990   case LOLR_Error:
1991     return ExprError();
1992   }
1993   llvm_unreachable("unexpected literal operator lookup result");
1994 }
1995 
1996 DeclRefExpr *
1997 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1998                        SourceLocation Loc,
1999                        const CXXScopeSpec *SS) {
2000   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2001   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2002 }
2003 
2004 DeclRefExpr *
2005 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2006                        const DeclarationNameInfo &NameInfo,
2007                        const CXXScopeSpec *SS, NamedDecl *FoundD,
2008                        SourceLocation TemplateKWLoc,
2009                        const TemplateArgumentListInfo *TemplateArgs) {
2010   NestedNameSpecifierLoc NNS =
2011       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2012   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2013                           TemplateArgs);
2014 }
2015 
2016 // CUDA/HIP: Check whether a captured reference variable is referencing a
2017 // host variable in a device or host device lambda.
2018 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2019                                                             VarDecl *VD) {
2020   if (!S.getLangOpts().CUDA || !VD->hasInit())
2021     return false;
2022   assert(VD->getType()->isReferenceType());
2023 
2024   // Check whether the reference variable is referencing a host variable.
2025   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2026   if (!DRE)
2027     return false;
2028   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2029   if (!Referee || !Referee->hasGlobalStorage() ||
2030       Referee->hasAttr<CUDADeviceAttr>())
2031     return false;
2032 
2033   // Check whether the current function is a device or host device lambda.
2034   // Check whether the reference variable is a capture by getDeclContext()
2035   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2036   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2037   if (MD && MD->getParent()->isLambda() &&
2038       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2039       VD->getDeclContext() != MD)
2040     return true;
2041 
2042   return false;
2043 }
2044 
2045 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2046   // A declaration named in an unevaluated operand never constitutes an odr-use.
2047   if (isUnevaluatedContext())
2048     return NOUR_Unevaluated;
2049 
2050   // C++2a [basic.def.odr]p4:
2051   //   A variable x whose name appears as a potentially-evaluated expression e
2052   //   is odr-used by e unless [...] x is a reference that is usable in
2053   //   constant expressions.
2054   // CUDA/HIP:
2055   //   If a reference variable referencing a host variable is captured in a
2056   //   device or host device lambda, the value of the referee must be copied
2057   //   to the capture and the reference variable must be treated as odr-use
2058   //   since the value of the referee is not known at compile time and must
2059   //   be loaded from the captured.
2060   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2061     if (VD->getType()->isReferenceType() &&
2062         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2063         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2064         VD->isUsableInConstantExpressions(Context))
2065       return NOUR_Constant;
2066   }
2067 
2068   // All remaining non-variable cases constitute an odr-use. For variables, we
2069   // need to wait and see how the expression is used.
2070   return NOUR_None;
2071 }
2072 
2073 /// BuildDeclRefExpr - Build an expression that references a
2074 /// declaration that does not require a closure capture.
2075 DeclRefExpr *
2076 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2077                        const DeclarationNameInfo &NameInfo,
2078                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2079                        SourceLocation TemplateKWLoc,
2080                        const TemplateArgumentListInfo *TemplateArgs) {
2081   bool RefersToCapturedVariable =
2082       isa<VarDecl>(D) &&
2083       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2084 
2085   DeclRefExpr *E = DeclRefExpr::Create(
2086       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2087       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2088   MarkDeclRefReferenced(E);
2089 
2090   // C++ [except.spec]p17:
2091   //   An exception-specification is considered to be needed when:
2092   //   - in an expression, the function is the unique lookup result or
2093   //     the selected member of a set of overloaded functions.
2094   //
2095   // We delay doing this until after we've built the function reference and
2096   // marked it as used so that:
2097   //  a) if the function is defaulted, we get errors from defining it before /
2098   //     instead of errors from computing its exception specification, and
2099   //  b) if the function is a defaulted comparison, we can use the body we
2100   //     build when defining it as input to the exception specification
2101   //     computation rather than computing a new body.
2102   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2103     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2104       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2105         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2106     }
2107   }
2108 
2109   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2110       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2111       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2112     getCurFunction()->recordUseOfWeak(E);
2113 
2114   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2115   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2116     FD = IFD->getAnonField();
2117   if (FD) {
2118     UnusedPrivateFields.remove(FD);
2119     // Just in case we're building an illegal pointer-to-member.
2120     if (FD->isBitField())
2121       E->setObjectKind(OK_BitField);
2122   }
2123 
2124   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2125   // designates a bit-field.
2126   if (auto *BD = dyn_cast<BindingDecl>(D))
2127     if (auto *BE = BD->getBinding())
2128       E->setObjectKind(BE->getObjectKind());
2129 
2130   return E;
2131 }
2132 
2133 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2134 /// possibly a list of template arguments.
2135 ///
2136 /// If this produces template arguments, it is permitted to call
2137 /// DecomposeTemplateName.
2138 ///
2139 /// This actually loses a lot of source location information for
2140 /// non-standard name kinds; we should consider preserving that in
2141 /// some way.
2142 void
2143 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2144                              TemplateArgumentListInfo &Buffer,
2145                              DeclarationNameInfo &NameInfo,
2146                              const TemplateArgumentListInfo *&TemplateArgs) {
2147   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2148     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2149     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2150 
2151     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2152                                        Id.TemplateId->NumArgs);
2153     translateTemplateArguments(TemplateArgsPtr, Buffer);
2154 
2155     TemplateName TName = Id.TemplateId->Template.get();
2156     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2157     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2158     TemplateArgs = &Buffer;
2159   } else {
2160     NameInfo = GetNameFromUnqualifiedId(Id);
2161     TemplateArgs = nullptr;
2162   }
2163 }
2164 
2165 static void emitEmptyLookupTypoDiagnostic(
2166     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2167     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2168     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2169   DeclContext *Ctx =
2170       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2171   if (!TC) {
2172     // Emit a special diagnostic for failed member lookups.
2173     // FIXME: computing the declaration context might fail here (?)
2174     if (Ctx)
2175       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2176                                                  << SS.getRange();
2177     else
2178       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2179     return;
2180   }
2181 
2182   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2183   bool DroppedSpecifier =
2184       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2185   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2186                         ? diag::note_implicit_param_decl
2187                         : diag::note_previous_decl;
2188   if (!Ctx)
2189     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2190                          SemaRef.PDiag(NoteID));
2191   else
2192     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2193                                  << Typo << Ctx << DroppedSpecifier
2194                                  << SS.getRange(),
2195                          SemaRef.PDiag(NoteID));
2196 }
2197 
2198 /// Diagnose a lookup that found results in an enclosing class during error
2199 /// recovery. This usually indicates that the results were found in a dependent
2200 /// base class that could not be searched as part of a template definition.
2201 /// Always issues a diagnostic (though this may be only a warning in MS
2202 /// compatibility mode).
2203 ///
2204 /// Return \c true if the error is unrecoverable, or \c false if the caller
2205 /// should attempt to recover using these lookup results.
2206 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2207   // During a default argument instantiation the CurContext points
2208   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2209   // function parameter list, hence add an explicit check.
2210   bool isDefaultArgument =
2211       !CodeSynthesisContexts.empty() &&
2212       CodeSynthesisContexts.back().Kind ==
2213           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2214   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2215   bool isInstance = CurMethod && CurMethod->isInstance() &&
2216                     R.getNamingClass() == CurMethod->getParent() &&
2217                     !isDefaultArgument;
2218 
2219   // There are two ways we can find a class-scope declaration during template
2220   // instantiation that we did not find in the template definition: if it is a
2221   // member of a dependent base class, or if it is declared after the point of
2222   // use in the same class. Distinguish these by comparing the class in which
2223   // the member was found to the naming class of the lookup.
2224   unsigned DiagID = diag::err_found_in_dependent_base;
2225   unsigned NoteID = diag::note_member_declared_at;
2226   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2227     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2228                                       : diag::err_found_later_in_class;
2229   } else if (getLangOpts().MSVCCompat) {
2230     DiagID = diag::ext_found_in_dependent_base;
2231     NoteID = diag::note_dependent_member_use;
2232   }
2233 
2234   if (isInstance) {
2235     // Give a code modification hint to insert 'this->'.
2236     Diag(R.getNameLoc(), DiagID)
2237         << R.getLookupName()
2238         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2239     CheckCXXThisCapture(R.getNameLoc());
2240   } else {
2241     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2242     // they're not shadowed).
2243     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2244   }
2245 
2246   for (NamedDecl *D : R)
2247     Diag(D->getLocation(), NoteID);
2248 
2249   // Return true if we are inside a default argument instantiation
2250   // and the found name refers to an instance member function, otherwise
2251   // the caller will try to create an implicit member call and this is wrong
2252   // for default arguments.
2253   //
2254   // FIXME: Is this special case necessary? We could allow the caller to
2255   // diagnose this.
2256   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2257     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2258     return true;
2259   }
2260 
2261   // Tell the callee to try to recover.
2262   return false;
2263 }
2264 
2265 /// Diagnose an empty lookup.
2266 ///
2267 /// \return false if new lookup candidates were found
2268 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2269                                CorrectionCandidateCallback &CCC,
2270                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2271                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2272   DeclarationName Name = R.getLookupName();
2273 
2274   unsigned diagnostic = diag::err_undeclared_var_use;
2275   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2276   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2277       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2278       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2279     diagnostic = diag::err_undeclared_use;
2280     diagnostic_suggest = diag::err_undeclared_use_suggest;
2281   }
2282 
2283   // If the original lookup was an unqualified lookup, fake an
2284   // unqualified lookup.  This is useful when (for example) the
2285   // original lookup would not have found something because it was a
2286   // dependent name.
2287   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2288   while (DC) {
2289     if (isa<CXXRecordDecl>(DC)) {
2290       LookupQualifiedName(R, DC);
2291 
2292       if (!R.empty()) {
2293         // Don't give errors about ambiguities in this lookup.
2294         R.suppressDiagnostics();
2295 
2296         // If there's a best viable function among the results, only mention
2297         // that one in the notes.
2298         OverloadCandidateSet Candidates(R.getNameLoc(),
2299                                         OverloadCandidateSet::CSK_Normal);
2300         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2301         OverloadCandidateSet::iterator Best;
2302         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2303             OR_Success) {
2304           R.clear();
2305           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2306           R.resolveKind();
2307         }
2308 
2309         return DiagnoseDependentMemberLookup(R);
2310       }
2311 
2312       R.clear();
2313     }
2314 
2315     DC = DC->getLookupParent();
2316   }
2317 
2318   // We didn't find anything, so try to correct for a typo.
2319   TypoCorrection Corrected;
2320   if (S && Out) {
2321     SourceLocation TypoLoc = R.getNameLoc();
2322     assert(!ExplicitTemplateArgs &&
2323            "Diagnosing an empty lookup with explicit template args!");
2324     *Out = CorrectTypoDelayed(
2325         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2326         [=](const TypoCorrection &TC) {
2327           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2328                                         diagnostic, diagnostic_suggest);
2329         },
2330         nullptr, CTK_ErrorRecovery);
2331     if (*Out)
2332       return true;
2333   } else if (S &&
2334              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2335                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2336     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2337     bool DroppedSpecifier =
2338         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2339     R.setLookupName(Corrected.getCorrection());
2340 
2341     bool AcceptableWithRecovery = false;
2342     bool AcceptableWithoutRecovery = false;
2343     NamedDecl *ND = Corrected.getFoundDecl();
2344     if (ND) {
2345       if (Corrected.isOverloaded()) {
2346         OverloadCandidateSet OCS(R.getNameLoc(),
2347                                  OverloadCandidateSet::CSK_Normal);
2348         OverloadCandidateSet::iterator Best;
2349         for (NamedDecl *CD : Corrected) {
2350           if (FunctionTemplateDecl *FTD =
2351                    dyn_cast<FunctionTemplateDecl>(CD))
2352             AddTemplateOverloadCandidate(
2353                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2354                 Args, OCS);
2355           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2356             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2357               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2358                                    Args, OCS);
2359         }
2360         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2361         case OR_Success:
2362           ND = Best->FoundDecl;
2363           Corrected.setCorrectionDecl(ND);
2364           break;
2365         default:
2366           // FIXME: Arbitrarily pick the first declaration for the note.
2367           Corrected.setCorrectionDecl(ND);
2368           break;
2369         }
2370       }
2371       R.addDecl(ND);
2372       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2373         CXXRecordDecl *Record = nullptr;
2374         if (Corrected.getCorrectionSpecifier()) {
2375           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2376           Record = Ty->getAsCXXRecordDecl();
2377         }
2378         if (!Record)
2379           Record = cast<CXXRecordDecl>(
2380               ND->getDeclContext()->getRedeclContext());
2381         R.setNamingClass(Record);
2382       }
2383 
2384       auto *UnderlyingND = ND->getUnderlyingDecl();
2385       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2386                                isa<FunctionTemplateDecl>(UnderlyingND);
2387       // FIXME: If we ended up with a typo for a type name or
2388       // Objective-C class name, we're in trouble because the parser
2389       // is in the wrong place to recover. Suggest the typo
2390       // correction, but don't make it a fix-it since we're not going
2391       // to recover well anyway.
2392       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2393                                   getAsTypeTemplateDecl(UnderlyingND) ||
2394                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2395     } else {
2396       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2397       // because we aren't able to recover.
2398       AcceptableWithoutRecovery = true;
2399     }
2400 
2401     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2402       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2403                             ? diag::note_implicit_param_decl
2404                             : diag::note_previous_decl;
2405       if (SS.isEmpty())
2406         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2407                      PDiag(NoteID), AcceptableWithRecovery);
2408       else
2409         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2410                                   << Name << computeDeclContext(SS, false)
2411                                   << DroppedSpecifier << SS.getRange(),
2412                      PDiag(NoteID), AcceptableWithRecovery);
2413 
2414       // Tell the callee whether to try to recover.
2415       return !AcceptableWithRecovery;
2416     }
2417   }
2418   R.clear();
2419 
2420   // Emit a special diagnostic for failed member lookups.
2421   // FIXME: computing the declaration context might fail here (?)
2422   if (!SS.isEmpty()) {
2423     Diag(R.getNameLoc(), diag::err_no_member)
2424       << Name << computeDeclContext(SS, false)
2425       << SS.getRange();
2426     return true;
2427   }
2428 
2429   // Give up, we can't recover.
2430   Diag(R.getNameLoc(), diagnostic) << Name;
2431   return true;
2432 }
2433 
2434 /// In Microsoft mode, if we are inside a template class whose parent class has
2435 /// dependent base classes, and we can't resolve an unqualified identifier, then
2436 /// assume the identifier is a member of a dependent base class.  We can only
2437 /// recover successfully in static methods, instance methods, and other contexts
2438 /// where 'this' is available.  This doesn't precisely match MSVC's
2439 /// instantiation model, but it's close enough.
2440 static Expr *
2441 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2442                                DeclarationNameInfo &NameInfo,
2443                                SourceLocation TemplateKWLoc,
2444                                const TemplateArgumentListInfo *TemplateArgs) {
2445   // Only try to recover from lookup into dependent bases in static methods or
2446   // contexts where 'this' is available.
2447   QualType ThisType = S.getCurrentThisType();
2448   const CXXRecordDecl *RD = nullptr;
2449   if (!ThisType.isNull())
2450     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2451   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2452     RD = MD->getParent();
2453   if (!RD || !RD->hasAnyDependentBases())
2454     return nullptr;
2455 
2456   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2457   // is available, suggest inserting 'this->' as a fixit.
2458   SourceLocation Loc = NameInfo.getLoc();
2459   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2460   DB << NameInfo.getName() << RD;
2461 
2462   if (!ThisType.isNull()) {
2463     DB << FixItHint::CreateInsertion(Loc, "this->");
2464     return CXXDependentScopeMemberExpr::Create(
2465         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2466         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2467         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2468   }
2469 
2470   // Synthesize a fake NNS that points to the derived class.  This will
2471   // perform name lookup during template instantiation.
2472   CXXScopeSpec SS;
2473   auto *NNS =
2474       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2475   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2476   return DependentScopeDeclRefExpr::Create(
2477       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2478       TemplateArgs);
2479 }
2480 
2481 ExprResult
2482 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2483                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2484                         bool HasTrailingLParen, bool IsAddressOfOperand,
2485                         CorrectionCandidateCallback *CCC,
2486                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2487   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2488          "cannot be direct & operand and have a trailing lparen");
2489   if (SS.isInvalid())
2490     return ExprError();
2491 
2492   TemplateArgumentListInfo TemplateArgsBuffer;
2493 
2494   // Decompose the UnqualifiedId into the following data.
2495   DeclarationNameInfo NameInfo;
2496   const TemplateArgumentListInfo *TemplateArgs;
2497   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2498 
2499   DeclarationName Name = NameInfo.getName();
2500   IdentifierInfo *II = Name.getAsIdentifierInfo();
2501   SourceLocation NameLoc = NameInfo.getLoc();
2502 
2503   if (II && II->isEditorPlaceholder()) {
2504     // FIXME: When typed placeholders are supported we can create a typed
2505     // placeholder expression node.
2506     return ExprError();
2507   }
2508 
2509   // C++ [temp.dep.expr]p3:
2510   //   An id-expression is type-dependent if it contains:
2511   //     -- an identifier that was declared with a dependent type,
2512   //        (note: handled after lookup)
2513   //     -- a template-id that is dependent,
2514   //        (note: handled in BuildTemplateIdExpr)
2515   //     -- a conversion-function-id that specifies a dependent type,
2516   //     -- a nested-name-specifier that contains a class-name that
2517   //        names a dependent type.
2518   // Determine whether this is a member of an unknown specialization;
2519   // we need to handle these differently.
2520   bool DependentID = false;
2521   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2522       Name.getCXXNameType()->isDependentType()) {
2523     DependentID = true;
2524   } else if (SS.isSet()) {
2525     if (DeclContext *DC = computeDeclContext(SS, false)) {
2526       if (RequireCompleteDeclContext(SS, DC))
2527         return ExprError();
2528     } else {
2529       DependentID = true;
2530     }
2531   }
2532 
2533   if (DependentID)
2534     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2535                                       IsAddressOfOperand, TemplateArgs);
2536 
2537   // Perform the required lookup.
2538   LookupResult R(*this, NameInfo,
2539                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2540                      ? LookupObjCImplicitSelfParam
2541                      : LookupOrdinaryName);
2542   if (TemplateKWLoc.isValid() || TemplateArgs) {
2543     // Lookup the template name again to correctly establish the context in
2544     // which it was found. This is really unfortunate as we already did the
2545     // lookup to determine that it was a template name in the first place. If
2546     // this becomes a performance hit, we can work harder to preserve those
2547     // results until we get here but it's likely not worth it.
2548     bool MemberOfUnknownSpecialization;
2549     AssumedTemplateKind AssumedTemplate;
2550     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2551                            MemberOfUnknownSpecialization, TemplateKWLoc,
2552                            &AssumedTemplate))
2553       return ExprError();
2554 
2555     if (MemberOfUnknownSpecialization ||
2556         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2557       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2558                                         IsAddressOfOperand, TemplateArgs);
2559   } else {
2560     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2561     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2562 
2563     // If the result might be in a dependent base class, this is a dependent
2564     // id-expression.
2565     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2566       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2567                                         IsAddressOfOperand, TemplateArgs);
2568 
2569     // If this reference is in an Objective-C method, then we need to do
2570     // some special Objective-C lookup, too.
2571     if (IvarLookupFollowUp) {
2572       ExprResult E(LookupInObjCMethod(R, S, II, true));
2573       if (E.isInvalid())
2574         return ExprError();
2575 
2576       if (Expr *Ex = E.getAs<Expr>())
2577         return Ex;
2578     }
2579   }
2580 
2581   if (R.isAmbiguous())
2582     return ExprError();
2583 
2584   // This could be an implicitly declared function reference if the language
2585   // mode allows it as a feature.
2586   if (R.empty() && HasTrailingLParen && II &&
2587       getLangOpts().implicitFunctionsAllowed()) {
2588     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2589     if (D) R.addDecl(D);
2590   }
2591 
2592   // Determine whether this name might be a candidate for
2593   // argument-dependent lookup.
2594   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2595 
2596   if (R.empty() && !ADL) {
2597     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2598       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2599                                                    TemplateKWLoc, TemplateArgs))
2600         return E;
2601     }
2602 
2603     // Don't diagnose an empty lookup for inline assembly.
2604     if (IsInlineAsmIdentifier)
2605       return ExprError();
2606 
2607     // If this name wasn't predeclared and if this is not a function
2608     // call, diagnose the problem.
2609     TypoExpr *TE = nullptr;
2610     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2611                                                        : nullptr);
2612     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2613     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2614            "Typo correction callback misconfigured");
2615     if (CCC) {
2616       // Make sure the callback knows what the typo being diagnosed is.
2617       CCC->setTypoName(II);
2618       if (SS.isValid())
2619         CCC->setTypoNNS(SS.getScopeRep());
2620     }
2621     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2622     // a template name, but we happen to have always already looked up the name
2623     // before we get here if it must be a template name.
2624     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2625                             None, &TE)) {
2626       if (TE && KeywordReplacement) {
2627         auto &State = getTypoExprState(TE);
2628         auto BestTC = State.Consumer->getNextCorrection();
2629         if (BestTC.isKeyword()) {
2630           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2631           if (State.DiagHandler)
2632             State.DiagHandler(BestTC);
2633           KeywordReplacement->startToken();
2634           KeywordReplacement->setKind(II->getTokenID());
2635           KeywordReplacement->setIdentifierInfo(II);
2636           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2637           // Clean up the state associated with the TypoExpr, since it has
2638           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2639           clearDelayedTypo(TE);
2640           // Signal that a correction to a keyword was performed by returning a
2641           // valid-but-null ExprResult.
2642           return (Expr*)nullptr;
2643         }
2644         State.Consumer->resetCorrectionStream();
2645       }
2646       return TE ? TE : ExprError();
2647     }
2648 
2649     assert(!R.empty() &&
2650            "DiagnoseEmptyLookup returned false but added no results");
2651 
2652     // If we found an Objective-C instance variable, let
2653     // LookupInObjCMethod build the appropriate expression to
2654     // reference the ivar.
2655     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2656       R.clear();
2657       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2658       // In a hopelessly buggy code, Objective-C instance variable
2659       // lookup fails and no expression will be built to reference it.
2660       if (!E.isInvalid() && !E.get())
2661         return ExprError();
2662       return E;
2663     }
2664   }
2665 
2666   // This is guaranteed from this point on.
2667   assert(!R.empty() || ADL);
2668 
2669   // Check whether this might be a C++ implicit instance member access.
2670   // C++ [class.mfct.non-static]p3:
2671   //   When an id-expression that is not part of a class member access
2672   //   syntax and not used to form a pointer to member is used in the
2673   //   body of a non-static member function of class X, if name lookup
2674   //   resolves the name in the id-expression to a non-static non-type
2675   //   member of some class C, the id-expression is transformed into a
2676   //   class member access expression using (*this) as the
2677   //   postfix-expression to the left of the . operator.
2678   //
2679   // But we don't actually need to do this for '&' operands if R
2680   // resolved to a function or overloaded function set, because the
2681   // expression is ill-formed if it actually works out to be a
2682   // non-static member function:
2683   //
2684   // C++ [expr.ref]p4:
2685   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2686   //   [t]he expression can be used only as the left-hand operand of a
2687   //   member function call.
2688   //
2689   // There are other safeguards against such uses, but it's important
2690   // to get this right here so that we don't end up making a
2691   // spuriously dependent expression if we're inside a dependent
2692   // instance method.
2693   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2694     bool MightBeImplicitMember;
2695     if (!IsAddressOfOperand)
2696       MightBeImplicitMember = true;
2697     else if (!SS.isEmpty())
2698       MightBeImplicitMember = false;
2699     else if (R.isOverloadedResult())
2700       MightBeImplicitMember = false;
2701     else if (R.isUnresolvableResult())
2702       MightBeImplicitMember = true;
2703     else
2704       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2705                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2706                               isa<MSPropertyDecl>(R.getFoundDecl());
2707 
2708     if (MightBeImplicitMember)
2709       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2710                                              R, TemplateArgs, S);
2711   }
2712 
2713   if (TemplateArgs || TemplateKWLoc.isValid()) {
2714 
2715     // In C++1y, if this is a variable template id, then check it
2716     // in BuildTemplateIdExpr().
2717     // The single lookup result must be a variable template declaration.
2718     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2719         Id.TemplateId->Kind == TNK_Var_template) {
2720       assert(R.getAsSingle<VarTemplateDecl>() &&
2721              "There should only be one declaration found.");
2722     }
2723 
2724     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2725   }
2726 
2727   return BuildDeclarationNameExpr(SS, R, ADL);
2728 }
2729 
2730 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2731 /// declaration name, generally during template instantiation.
2732 /// There's a large number of things which don't need to be done along
2733 /// this path.
2734 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2735     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2736     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2737   DeclContext *DC = computeDeclContext(SS, false);
2738   if (!DC)
2739     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2740                                      NameInfo, /*TemplateArgs=*/nullptr);
2741 
2742   if (RequireCompleteDeclContext(SS, DC))
2743     return ExprError();
2744 
2745   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2746   LookupQualifiedName(R, DC);
2747 
2748   if (R.isAmbiguous())
2749     return ExprError();
2750 
2751   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2752     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2753                                      NameInfo, /*TemplateArgs=*/nullptr);
2754 
2755   if (R.empty()) {
2756     // Don't diagnose problems with invalid record decl, the secondary no_member
2757     // diagnostic during template instantiation is likely bogus, e.g. if a class
2758     // is invalid because it's derived from an invalid base class, then missing
2759     // members were likely supposed to be inherited.
2760     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2761       if (CD->isInvalidDecl())
2762         return ExprError();
2763     Diag(NameInfo.getLoc(), diag::err_no_member)
2764       << NameInfo.getName() << DC << SS.getRange();
2765     return ExprError();
2766   }
2767 
2768   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2769     // Diagnose a missing typename if this resolved unambiguously to a type in
2770     // a dependent context.  If we can recover with a type, downgrade this to
2771     // a warning in Microsoft compatibility mode.
2772     unsigned DiagID = diag::err_typename_missing;
2773     if (RecoveryTSI && getLangOpts().MSVCCompat)
2774       DiagID = diag::ext_typename_missing;
2775     SourceLocation Loc = SS.getBeginLoc();
2776     auto D = Diag(Loc, DiagID);
2777     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2778       << SourceRange(Loc, NameInfo.getEndLoc());
2779 
2780     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2781     // context.
2782     if (!RecoveryTSI)
2783       return ExprError();
2784 
2785     // Only issue the fixit if we're prepared to recover.
2786     D << FixItHint::CreateInsertion(Loc, "typename ");
2787 
2788     // Recover by pretending this was an elaborated type.
2789     QualType Ty = Context.getTypeDeclType(TD);
2790     TypeLocBuilder TLB;
2791     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2792 
2793     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2794     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2795     QTL.setElaboratedKeywordLoc(SourceLocation());
2796     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2797 
2798     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2799 
2800     return ExprEmpty();
2801   }
2802 
2803   // Defend against this resolving to an implicit member access. We usually
2804   // won't get here if this might be a legitimate a class member (we end up in
2805   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2806   // a pointer-to-member or in an unevaluated context in C++11.
2807   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2808     return BuildPossibleImplicitMemberExpr(SS,
2809                                            /*TemplateKWLoc=*/SourceLocation(),
2810                                            R, /*TemplateArgs=*/nullptr, S);
2811 
2812   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2813 }
2814 
2815 /// The parser has read a name in, and Sema has detected that we're currently
2816 /// inside an ObjC method. Perform some additional checks and determine if we
2817 /// should form a reference to an ivar.
2818 ///
2819 /// Ideally, most of this would be done by lookup, but there's
2820 /// actually quite a lot of extra work involved.
2821 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2822                                         IdentifierInfo *II) {
2823   SourceLocation Loc = Lookup.getNameLoc();
2824   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2825 
2826   // Check for error condition which is already reported.
2827   if (!CurMethod)
2828     return DeclResult(true);
2829 
2830   // There are two cases to handle here.  1) scoped lookup could have failed,
2831   // in which case we should look for an ivar.  2) scoped lookup could have
2832   // found a decl, but that decl is outside the current instance method (i.e.
2833   // a global variable).  In these two cases, we do a lookup for an ivar with
2834   // this name, if the lookup sucedes, we replace it our current decl.
2835 
2836   // If we're in a class method, we don't normally want to look for
2837   // ivars.  But if we don't find anything else, and there's an
2838   // ivar, that's an error.
2839   bool IsClassMethod = CurMethod->isClassMethod();
2840 
2841   bool LookForIvars;
2842   if (Lookup.empty())
2843     LookForIvars = true;
2844   else if (IsClassMethod)
2845     LookForIvars = false;
2846   else
2847     LookForIvars = (Lookup.isSingleResult() &&
2848                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2849   ObjCInterfaceDecl *IFace = nullptr;
2850   if (LookForIvars) {
2851     IFace = CurMethod->getClassInterface();
2852     ObjCInterfaceDecl *ClassDeclared;
2853     ObjCIvarDecl *IV = nullptr;
2854     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2855       // Diagnose using an ivar in a class method.
2856       if (IsClassMethod) {
2857         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2858         return DeclResult(true);
2859       }
2860 
2861       // Diagnose the use of an ivar outside of the declaring class.
2862       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2863           !declaresSameEntity(ClassDeclared, IFace) &&
2864           !getLangOpts().DebuggerSupport)
2865         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2866 
2867       // Success.
2868       return IV;
2869     }
2870   } else if (CurMethod->isInstanceMethod()) {
2871     // We should warn if a local variable hides an ivar.
2872     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2873       ObjCInterfaceDecl *ClassDeclared;
2874       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2875         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2876             declaresSameEntity(IFace, ClassDeclared))
2877           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2878       }
2879     }
2880   } else if (Lookup.isSingleResult() &&
2881              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2882     // If accessing a stand-alone ivar in a class method, this is an error.
2883     if (const ObjCIvarDecl *IV =
2884             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2885       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2886       return DeclResult(true);
2887     }
2888   }
2889 
2890   // Didn't encounter an error, didn't find an ivar.
2891   return DeclResult(false);
2892 }
2893 
2894 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2895                                   ObjCIvarDecl *IV) {
2896   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2897   assert(CurMethod && CurMethod->isInstanceMethod() &&
2898          "should not reference ivar from this context");
2899 
2900   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2901   assert(IFace && "should not reference ivar from this context");
2902 
2903   // If we're referencing an invalid decl, just return this as a silent
2904   // error node.  The error diagnostic was already emitted on the decl.
2905   if (IV->isInvalidDecl())
2906     return ExprError();
2907 
2908   // Check if referencing a field with __attribute__((deprecated)).
2909   if (DiagnoseUseOfDecl(IV, Loc))
2910     return ExprError();
2911 
2912   // FIXME: This should use a new expr for a direct reference, don't
2913   // turn this into Self->ivar, just return a BareIVarExpr or something.
2914   IdentifierInfo &II = Context.Idents.get("self");
2915   UnqualifiedId SelfName;
2916   SelfName.setImplicitSelfParam(&II);
2917   CXXScopeSpec SelfScopeSpec;
2918   SourceLocation TemplateKWLoc;
2919   ExprResult SelfExpr =
2920       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2921                         /*HasTrailingLParen=*/false,
2922                         /*IsAddressOfOperand=*/false);
2923   if (SelfExpr.isInvalid())
2924     return ExprError();
2925 
2926   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2927   if (SelfExpr.isInvalid())
2928     return ExprError();
2929 
2930   MarkAnyDeclReferenced(Loc, IV, true);
2931 
2932   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2933   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2934       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2935     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2936 
2937   ObjCIvarRefExpr *Result = new (Context)
2938       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2939                       IV->getLocation(), SelfExpr.get(), true, true);
2940 
2941   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2942     if (!isUnevaluatedContext() &&
2943         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2944       getCurFunction()->recordUseOfWeak(Result);
2945   }
2946   if (getLangOpts().ObjCAutoRefCount)
2947     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2948       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2949 
2950   return Result;
2951 }
2952 
2953 /// The parser has read a name in, and Sema has detected that we're currently
2954 /// inside an ObjC method. Perform some additional checks and determine if we
2955 /// should form a reference to an ivar. If so, build an expression referencing
2956 /// that ivar.
2957 ExprResult
2958 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2959                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2960   // FIXME: Integrate this lookup step into LookupParsedName.
2961   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2962   if (Ivar.isInvalid())
2963     return ExprError();
2964   if (Ivar.isUsable())
2965     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2966                             cast<ObjCIvarDecl>(Ivar.get()));
2967 
2968   if (Lookup.empty() && II && AllowBuiltinCreation)
2969     LookupBuiltin(Lookup);
2970 
2971   // Sentinel value saying that we didn't do anything special.
2972   return ExprResult(false);
2973 }
2974 
2975 /// Cast a base object to a member's actual type.
2976 ///
2977 /// There are two relevant checks:
2978 ///
2979 /// C++ [class.access.base]p7:
2980 ///
2981 ///   If a class member access operator [...] is used to access a non-static
2982 ///   data member or non-static member function, the reference is ill-formed if
2983 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2984 ///   naming class of the right operand.
2985 ///
2986 /// C++ [expr.ref]p7:
2987 ///
2988 ///   If E2 is a non-static data member or a non-static member function, the
2989 ///   program is ill-formed if the class of which E2 is directly a member is an
2990 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2991 ///
2992 /// Note that the latter check does not consider access; the access of the
2993 /// "real" base class is checked as appropriate when checking the access of the
2994 /// member name.
2995 ExprResult
2996 Sema::PerformObjectMemberConversion(Expr *From,
2997                                     NestedNameSpecifier *Qualifier,
2998                                     NamedDecl *FoundDecl,
2999                                     NamedDecl *Member) {
3000   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3001   if (!RD)
3002     return From;
3003 
3004   QualType DestRecordType;
3005   QualType DestType;
3006   QualType FromRecordType;
3007   QualType FromType = From->getType();
3008   bool PointerConversions = false;
3009   if (isa<FieldDecl>(Member)) {
3010     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3011     auto FromPtrType = FromType->getAs<PointerType>();
3012     DestRecordType = Context.getAddrSpaceQualType(
3013         DestRecordType, FromPtrType
3014                             ? FromType->getPointeeType().getAddressSpace()
3015                             : FromType.getAddressSpace());
3016 
3017     if (FromPtrType) {
3018       DestType = Context.getPointerType(DestRecordType);
3019       FromRecordType = FromPtrType->getPointeeType();
3020       PointerConversions = true;
3021     } else {
3022       DestType = DestRecordType;
3023       FromRecordType = FromType;
3024     }
3025   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3026     if (Method->isStatic())
3027       return From;
3028 
3029     DestType = Method->getThisType();
3030     DestRecordType = DestType->getPointeeType();
3031 
3032     if (FromType->getAs<PointerType>()) {
3033       FromRecordType = FromType->getPointeeType();
3034       PointerConversions = true;
3035     } else {
3036       FromRecordType = FromType;
3037       DestType = DestRecordType;
3038     }
3039 
3040     LangAS FromAS = FromRecordType.getAddressSpace();
3041     LangAS DestAS = DestRecordType.getAddressSpace();
3042     if (FromAS != DestAS) {
3043       QualType FromRecordTypeWithoutAS =
3044           Context.removeAddrSpaceQualType(FromRecordType);
3045       QualType FromTypeWithDestAS =
3046           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3047       if (PointerConversions)
3048         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3049       From = ImpCastExprToType(From, FromTypeWithDestAS,
3050                                CK_AddressSpaceConversion, From->getValueKind())
3051                  .get();
3052     }
3053   } else {
3054     // No conversion necessary.
3055     return From;
3056   }
3057 
3058   if (DestType->isDependentType() || FromType->isDependentType())
3059     return From;
3060 
3061   // If the unqualified types are the same, no conversion is necessary.
3062   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3063     return From;
3064 
3065   SourceRange FromRange = From->getSourceRange();
3066   SourceLocation FromLoc = FromRange.getBegin();
3067 
3068   ExprValueKind VK = From->getValueKind();
3069 
3070   // C++ [class.member.lookup]p8:
3071   //   [...] Ambiguities can often be resolved by qualifying a name with its
3072   //   class name.
3073   //
3074   // If the member was a qualified name and the qualified referred to a
3075   // specific base subobject type, we'll cast to that intermediate type
3076   // first and then to the object in which the member is declared. That allows
3077   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3078   //
3079   //   class Base { public: int x; };
3080   //   class Derived1 : public Base { };
3081   //   class Derived2 : public Base { };
3082   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3083   //
3084   //   void VeryDerived::f() {
3085   //     x = 17; // error: ambiguous base subobjects
3086   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3087   //   }
3088   if (Qualifier && Qualifier->getAsType()) {
3089     QualType QType = QualType(Qualifier->getAsType(), 0);
3090     assert(QType->isRecordType() && "lookup done with non-record type");
3091 
3092     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3093 
3094     // In C++98, the qualifier type doesn't actually have to be a base
3095     // type of the object type, in which case we just ignore it.
3096     // Otherwise build the appropriate casts.
3097     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3098       CXXCastPath BasePath;
3099       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3100                                        FromLoc, FromRange, &BasePath))
3101         return ExprError();
3102 
3103       if (PointerConversions)
3104         QType = Context.getPointerType(QType);
3105       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3106                                VK, &BasePath).get();
3107 
3108       FromType = QType;
3109       FromRecordType = QRecordType;
3110 
3111       // If the qualifier type was the same as the destination type,
3112       // we're done.
3113       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3114         return From;
3115     }
3116   }
3117 
3118   CXXCastPath BasePath;
3119   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3120                                    FromLoc, FromRange, &BasePath,
3121                                    /*IgnoreAccess=*/true))
3122     return ExprError();
3123 
3124   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3125                            VK, &BasePath);
3126 }
3127 
3128 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3129                                       const LookupResult &R,
3130                                       bool HasTrailingLParen) {
3131   // Only when used directly as the postfix-expression of a call.
3132   if (!HasTrailingLParen)
3133     return false;
3134 
3135   // Never if a scope specifier was provided.
3136   if (SS.isSet())
3137     return false;
3138 
3139   // Only in C++ or ObjC++.
3140   if (!getLangOpts().CPlusPlus)
3141     return false;
3142 
3143   // Turn off ADL when we find certain kinds of declarations during
3144   // normal lookup:
3145   for (NamedDecl *D : R) {
3146     // C++0x [basic.lookup.argdep]p3:
3147     //     -- a declaration of a class member
3148     // Since using decls preserve this property, we check this on the
3149     // original decl.
3150     if (D->isCXXClassMember())
3151       return false;
3152 
3153     // C++0x [basic.lookup.argdep]p3:
3154     //     -- a block-scope function declaration that is not a
3155     //        using-declaration
3156     // NOTE: we also trigger this for function templates (in fact, we
3157     // don't check the decl type at all, since all other decl types
3158     // turn off ADL anyway).
3159     if (isa<UsingShadowDecl>(D))
3160       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3161     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3162       return false;
3163 
3164     // C++0x [basic.lookup.argdep]p3:
3165     //     -- a declaration that is neither a function or a function
3166     //        template
3167     // And also for builtin functions.
3168     if (isa<FunctionDecl>(D)) {
3169       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3170 
3171       // But also builtin functions.
3172       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3173         return false;
3174     } else if (!isa<FunctionTemplateDecl>(D))
3175       return false;
3176   }
3177 
3178   return true;
3179 }
3180 
3181 
3182 /// Diagnoses obvious problems with the use of the given declaration
3183 /// as an expression.  This is only actually called for lookups that
3184 /// were not overloaded, and it doesn't promise that the declaration
3185 /// will in fact be used.
3186 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3187   if (D->isInvalidDecl())
3188     return true;
3189 
3190   if (isa<TypedefNameDecl>(D)) {
3191     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3192     return true;
3193   }
3194 
3195   if (isa<ObjCInterfaceDecl>(D)) {
3196     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3197     return true;
3198   }
3199 
3200   if (isa<NamespaceDecl>(D)) {
3201     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3202     return true;
3203   }
3204 
3205   return false;
3206 }
3207 
3208 // Certain multiversion types should be treated as overloaded even when there is
3209 // only one result.
3210 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3211   assert(R.isSingleResult() && "Expected only a single result");
3212   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3213   return FD &&
3214          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3215 }
3216 
3217 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3218                                           LookupResult &R, bool NeedsADL,
3219                                           bool AcceptInvalidDecl) {
3220   // If this is a single, fully-resolved result and we don't need ADL,
3221   // just build an ordinary singleton decl ref.
3222   if (!NeedsADL && R.isSingleResult() &&
3223       !R.getAsSingle<FunctionTemplateDecl>() &&
3224       !ShouldLookupResultBeMultiVersionOverload(R))
3225     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3226                                     R.getRepresentativeDecl(), nullptr,
3227                                     AcceptInvalidDecl);
3228 
3229   // We only need to check the declaration if there's exactly one
3230   // result, because in the overloaded case the results can only be
3231   // functions and function templates.
3232   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3233       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3234     return ExprError();
3235 
3236   // Otherwise, just build an unresolved lookup expression.  Suppress
3237   // any lookup-related diagnostics; we'll hash these out later, when
3238   // we've picked a target.
3239   R.suppressDiagnostics();
3240 
3241   UnresolvedLookupExpr *ULE
3242     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3243                                    SS.getWithLocInContext(Context),
3244                                    R.getLookupNameInfo(),
3245                                    NeedsADL, R.isOverloadedResult(),
3246                                    R.begin(), R.end());
3247 
3248   return ULE;
3249 }
3250 
3251 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3252                                                ValueDecl *var);
3253 
3254 /// Complete semantic analysis for a reference to the given declaration.
3255 ExprResult Sema::BuildDeclarationNameExpr(
3256     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3257     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3258     bool AcceptInvalidDecl) {
3259   assert(D && "Cannot refer to a NULL declaration");
3260   assert(!isa<FunctionTemplateDecl>(D) &&
3261          "Cannot refer unambiguously to a function template");
3262 
3263   SourceLocation Loc = NameInfo.getLoc();
3264   if (CheckDeclInExpr(*this, Loc, D)) {
3265     // Recovery from invalid cases (e.g. D is an invalid Decl).
3266     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3267     // diagnostics, as invalid decls use int as a fallback type.
3268     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3269   }
3270 
3271   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3272     // Specifically diagnose references to class templates that are missing
3273     // a template argument list.
3274     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3275     return ExprError();
3276   }
3277 
3278   // Make sure that we're referring to a value.
3279   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3280     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3281     Diag(D->getLocation(), diag::note_declared_at);
3282     return ExprError();
3283   }
3284 
3285   // Check whether this declaration can be used. Note that we suppress
3286   // this check when we're going to perform argument-dependent lookup
3287   // on this function name, because this might not be the function
3288   // that overload resolution actually selects.
3289   if (DiagnoseUseOfDecl(D, Loc))
3290     return ExprError();
3291 
3292   auto *VD = cast<ValueDecl>(D);
3293 
3294   // Only create DeclRefExpr's for valid Decl's.
3295   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3296     return ExprError();
3297 
3298   // Handle members of anonymous structs and unions.  If we got here,
3299   // and the reference is to a class member indirect field, then this
3300   // must be the subject of a pointer-to-member expression.
3301   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3302     if (!indirectField->isCXXClassMember())
3303       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3304                                                       indirectField);
3305 
3306   QualType type = VD->getType();
3307   if (type.isNull())
3308     return ExprError();
3309   ExprValueKind valueKind = VK_PRValue;
3310 
3311   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3312   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3313   // is expanded by some outer '...' in the context of the use.
3314   type = type.getNonPackExpansionType();
3315 
3316   switch (D->getKind()) {
3317     // Ignore all the non-ValueDecl kinds.
3318 #define ABSTRACT_DECL(kind)
3319 #define VALUE(type, base)
3320 #define DECL(type, base) case Decl::type:
3321 #include "clang/AST/DeclNodes.inc"
3322     llvm_unreachable("invalid value decl kind");
3323 
3324   // These shouldn't make it here.
3325   case Decl::ObjCAtDefsField:
3326     llvm_unreachable("forming non-member reference to ivar?");
3327 
3328   // Enum constants are always r-values and never references.
3329   // Unresolved using declarations are dependent.
3330   case Decl::EnumConstant:
3331   case Decl::UnresolvedUsingValue:
3332   case Decl::OMPDeclareReduction:
3333   case Decl::OMPDeclareMapper:
3334     valueKind = VK_PRValue;
3335     break;
3336 
3337   // Fields and indirect fields that got here must be for
3338   // pointer-to-member expressions; we just call them l-values for
3339   // internal consistency, because this subexpression doesn't really
3340   // exist in the high-level semantics.
3341   case Decl::Field:
3342   case Decl::IndirectField:
3343   case Decl::ObjCIvar:
3344     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3345 
3346     // These can't have reference type in well-formed programs, but
3347     // for internal consistency we do this anyway.
3348     type = type.getNonReferenceType();
3349     valueKind = VK_LValue;
3350     break;
3351 
3352   // Non-type template parameters are either l-values or r-values
3353   // depending on the type.
3354   case Decl::NonTypeTemplateParm: {
3355     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3356       type = reftype->getPointeeType();
3357       valueKind = VK_LValue; // even if the parameter is an r-value reference
3358       break;
3359     }
3360 
3361     // [expr.prim.id.unqual]p2:
3362     //   If the entity is a template parameter object for a template
3363     //   parameter of type T, the type of the expression is const T.
3364     //   [...] The expression is an lvalue if the entity is a [...] template
3365     //   parameter object.
3366     if (type->isRecordType()) {
3367       type = type.getUnqualifiedType().withConst();
3368       valueKind = VK_LValue;
3369       break;
3370     }
3371 
3372     // For non-references, we need to strip qualifiers just in case
3373     // the template parameter was declared as 'const int' or whatever.
3374     valueKind = VK_PRValue;
3375     type = type.getUnqualifiedType();
3376     break;
3377   }
3378 
3379   case Decl::Var:
3380   case Decl::VarTemplateSpecialization:
3381   case Decl::VarTemplatePartialSpecialization:
3382   case Decl::Decomposition:
3383   case Decl::OMPCapturedExpr:
3384     // In C, "extern void blah;" is valid and is an r-value.
3385     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3386         type->isVoidType()) {
3387       valueKind = VK_PRValue;
3388       break;
3389     }
3390     LLVM_FALLTHROUGH;
3391 
3392   case Decl::ImplicitParam:
3393   case Decl::ParmVar: {
3394     // These are always l-values.
3395     valueKind = VK_LValue;
3396     type = type.getNonReferenceType();
3397 
3398     // FIXME: Does the addition of const really only apply in
3399     // potentially-evaluated contexts? Since the variable isn't actually
3400     // captured in an unevaluated context, it seems that the answer is no.
3401     if (!isUnevaluatedContext()) {
3402       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3403       if (!CapturedType.isNull())
3404         type = CapturedType;
3405     }
3406 
3407     break;
3408   }
3409 
3410   case Decl::Binding: {
3411     // These are always lvalues.
3412     valueKind = VK_LValue;
3413     type = type.getNonReferenceType();
3414     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3415     // decides how that's supposed to work.
3416     auto *BD = cast<BindingDecl>(VD);
3417     if (BD->getDeclContext() != CurContext) {
3418       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3419       if (DD && DD->hasLocalStorage())
3420         diagnoseUncapturableValueReference(*this, Loc, BD);
3421     }
3422     break;
3423   }
3424 
3425   case Decl::Function: {
3426     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3427       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3428         type = Context.BuiltinFnTy;
3429         valueKind = VK_PRValue;
3430         break;
3431       }
3432     }
3433 
3434     const FunctionType *fty = type->castAs<FunctionType>();
3435 
3436     // If we're referring to a function with an __unknown_anytype
3437     // result type, make the entire expression __unknown_anytype.
3438     if (fty->getReturnType() == Context.UnknownAnyTy) {
3439       type = Context.UnknownAnyTy;
3440       valueKind = VK_PRValue;
3441       break;
3442     }
3443 
3444     // Functions are l-values in C++.
3445     if (getLangOpts().CPlusPlus) {
3446       valueKind = VK_LValue;
3447       break;
3448     }
3449 
3450     // C99 DR 316 says that, if a function type comes from a
3451     // function definition (without a prototype), that type is only
3452     // used for checking compatibility. Therefore, when referencing
3453     // the function, we pretend that we don't have the full function
3454     // type.
3455     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3456       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3457                                             fty->getExtInfo());
3458 
3459     // Functions are r-values in C.
3460     valueKind = VK_PRValue;
3461     break;
3462   }
3463 
3464   case Decl::CXXDeductionGuide:
3465     llvm_unreachable("building reference to deduction guide");
3466 
3467   case Decl::MSProperty:
3468   case Decl::MSGuid:
3469   case Decl::TemplateParamObject:
3470     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3471     // capture in OpenMP, or duplicated between host and device?
3472     valueKind = VK_LValue;
3473     break;
3474 
3475   case Decl::UnnamedGlobalConstant:
3476     valueKind = VK_LValue;
3477     break;
3478 
3479   case Decl::CXXMethod:
3480     // If we're referring to a method with an __unknown_anytype
3481     // result type, make the entire expression __unknown_anytype.
3482     // This should only be possible with a type written directly.
3483     if (const FunctionProtoType *proto =
3484             dyn_cast<FunctionProtoType>(VD->getType()))
3485       if (proto->getReturnType() == Context.UnknownAnyTy) {
3486         type = Context.UnknownAnyTy;
3487         valueKind = VK_PRValue;
3488         break;
3489       }
3490 
3491     // C++ methods are l-values if static, r-values if non-static.
3492     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3493       valueKind = VK_LValue;
3494       break;
3495     }
3496     LLVM_FALLTHROUGH;
3497 
3498   case Decl::CXXConversion:
3499   case Decl::CXXDestructor:
3500   case Decl::CXXConstructor:
3501     valueKind = VK_PRValue;
3502     break;
3503   }
3504 
3505   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3506                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3507                           TemplateArgs);
3508 }
3509 
3510 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3511                                     SmallString<32> &Target) {
3512   Target.resize(CharByteWidth * (Source.size() + 1));
3513   char *ResultPtr = &Target[0];
3514   const llvm::UTF8 *ErrorPtr;
3515   bool success =
3516       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3517   (void)success;
3518   assert(success);
3519   Target.resize(ResultPtr - &Target[0]);
3520 }
3521 
3522 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3523                                      PredefinedExpr::IdentKind IK) {
3524   // Pick the current block, lambda, captured statement or function.
3525   Decl *currentDecl = nullptr;
3526   if (const BlockScopeInfo *BSI = getCurBlock())
3527     currentDecl = BSI->TheDecl;
3528   else if (const LambdaScopeInfo *LSI = getCurLambda())
3529     currentDecl = LSI->CallOperator;
3530   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3531     currentDecl = CSI->TheCapturedDecl;
3532   else
3533     currentDecl = getCurFunctionOrMethodDecl();
3534 
3535   if (!currentDecl) {
3536     Diag(Loc, diag::ext_predef_outside_function);
3537     currentDecl = Context.getTranslationUnitDecl();
3538   }
3539 
3540   QualType ResTy;
3541   StringLiteral *SL = nullptr;
3542   if (cast<DeclContext>(currentDecl)->isDependentContext())
3543     ResTy = Context.DependentTy;
3544   else {
3545     // Pre-defined identifiers are of type char[x], where x is the length of
3546     // the string.
3547     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3548     unsigned Length = Str.length();
3549 
3550     llvm::APInt LengthI(32, Length + 1);
3551     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3552       ResTy =
3553           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3554       SmallString<32> RawChars;
3555       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3556                               Str, RawChars);
3557       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3558                                            ArrayType::Normal,
3559                                            /*IndexTypeQuals*/ 0);
3560       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3561                                  /*Pascal*/ false, ResTy, Loc);
3562     } else {
3563       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3564       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3565                                            ArrayType::Normal,
3566                                            /*IndexTypeQuals*/ 0);
3567       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3568                                  /*Pascal*/ false, ResTy, Loc);
3569     }
3570   }
3571 
3572   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3573 }
3574 
3575 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3576                                                SourceLocation LParen,
3577                                                SourceLocation RParen,
3578                                                TypeSourceInfo *TSI) {
3579   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3580 }
3581 
3582 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3583                                                SourceLocation LParen,
3584                                                SourceLocation RParen,
3585                                                ParsedType ParsedTy) {
3586   TypeSourceInfo *TSI = nullptr;
3587   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3588 
3589   if (Ty.isNull())
3590     return ExprError();
3591   if (!TSI)
3592     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3593 
3594   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3595 }
3596 
3597 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3598   PredefinedExpr::IdentKind IK;
3599 
3600   switch (Kind) {
3601   default: llvm_unreachable("Unknown simple primary expr!");
3602   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3603   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3604   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3605   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3606   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3607   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3608   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3609   }
3610 
3611   return BuildPredefinedExpr(Loc, IK);
3612 }
3613 
3614 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3615   SmallString<16> CharBuffer;
3616   bool Invalid = false;
3617   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3618   if (Invalid)
3619     return ExprError();
3620 
3621   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3622                             PP, Tok.getKind());
3623   if (Literal.hadError())
3624     return ExprError();
3625 
3626   QualType Ty;
3627   if (Literal.isWide())
3628     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3629   else if (Literal.isUTF8() && getLangOpts().C2x)
3630     Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3631   else if (Literal.isUTF8() && getLangOpts().Char8)
3632     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3633   else if (Literal.isUTF16())
3634     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3635   else if (Literal.isUTF32())
3636     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3637   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3638     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3639   else
3640     Ty = Context.CharTy; // 'x' -> char in C++;
3641                          // u8'x' -> char in C11-C17 and in C++ without char8_t.
3642 
3643   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3644   if (Literal.isWide())
3645     Kind = CharacterLiteral::Wide;
3646   else if (Literal.isUTF16())
3647     Kind = CharacterLiteral::UTF16;
3648   else if (Literal.isUTF32())
3649     Kind = CharacterLiteral::UTF32;
3650   else if (Literal.isUTF8())
3651     Kind = CharacterLiteral::UTF8;
3652 
3653   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3654                                              Tok.getLocation());
3655 
3656   if (Literal.getUDSuffix().empty())
3657     return Lit;
3658 
3659   // We're building a user-defined literal.
3660   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3661   SourceLocation UDSuffixLoc =
3662     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3663 
3664   // Make sure we're allowed user-defined literals here.
3665   if (!UDLScope)
3666     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3667 
3668   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3669   //   operator "" X (ch)
3670   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3671                                         Lit, Tok.getLocation());
3672 }
3673 
3674 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3675   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3676   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3677                                 Context.IntTy, Loc);
3678 }
3679 
3680 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3681                                   QualType Ty, SourceLocation Loc) {
3682   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3683 
3684   using llvm::APFloat;
3685   APFloat Val(Format);
3686 
3687   APFloat::opStatus result = Literal.GetFloatValue(Val);
3688 
3689   // Overflow is always an error, but underflow is only an error if
3690   // we underflowed to zero (APFloat reports denormals as underflow).
3691   if ((result & APFloat::opOverflow) ||
3692       ((result & APFloat::opUnderflow) && Val.isZero())) {
3693     unsigned diagnostic;
3694     SmallString<20> buffer;
3695     if (result & APFloat::opOverflow) {
3696       diagnostic = diag::warn_float_overflow;
3697       APFloat::getLargest(Format).toString(buffer);
3698     } else {
3699       diagnostic = diag::warn_float_underflow;
3700       APFloat::getSmallest(Format).toString(buffer);
3701     }
3702 
3703     S.Diag(Loc, diagnostic)
3704       << Ty
3705       << StringRef(buffer.data(), buffer.size());
3706   }
3707 
3708   bool isExact = (result == APFloat::opOK);
3709   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3710 }
3711 
3712 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3713   assert(E && "Invalid expression");
3714 
3715   if (E->isValueDependent())
3716     return false;
3717 
3718   QualType QT = E->getType();
3719   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3720     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3721     return true;
3722   }
3723 
3724   llvm::APSInt ValueAPS;
3725   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3726 
3727   if (R.isInvalid())
3728     return true;
3729 
3730   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3731   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3732     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3733         << toString(ValueAPS, 10) << ValueIsPositive;
3734     return true;
3735   }
3736 
3737   return false;
3738 }
3739 
3740 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3741   // Fast path for a single digit (which is quite common).  A single digit
3742   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3743   if (Tok.getLength() == 1) {
3744     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3745     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3746   }
3747 
3748   SmallString<128> SpellingBuffer;
3749   // NumericLiteralParser wants to overread by one character.  Add padding to
3750   // the buffer in case the token is copied to the buffer.  If getSpelling()
3751   // returns a StringRef to the memory buffer, it should have a null char at
3752   // the EOF, so it is also safe.
3753   SpellingBuffer.resize(Tok.getLength() + 1);
3754 
3755   // Get the spelling of the token, which eliminates trigraphs, etc.
3756   bool Invalid = false;
3757   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3758   if (Invalid)
3759     return ExprError();
3760 
3761   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3762                                PP.getSourceManager(), PP.getLangOpts(),
3763                                PP.getTargetInfo(), PP.getDiagnostics());
3764   if (Literal.hadError)
3765     return ExprError();
3766 
3767   if (Literal.hasUDSuffix()) {
3768     // We're building a user-defined literal.
3769     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3770     SourceLocation UDSuffixLoc =
3771       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3772 
3773     // Make sure we're allowed user-defined literals here.
3774     if (!UDLScope)
3775       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3776 
3777     QualType CookedTy;
3778     if (Literal.isFloatingLiteral()) {
3779       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3780       // long double, the literal is treated as a call of the form
3781       //   operator "" X (f L)
3782       CookedTy = Context.LongDoubleTy;
3783     } else {
3784       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3785       // unsigned long long, the literal is treated as a call of the form
3786       //   operator "" X (n ULL)
3787       CookedTy = Context.UnsignedLongLongTy;
3788     }
3789 
3790     DeclarationName OpName =
3791       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3792     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3793     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3794 
3795     SourceLocation TokLoc = Tok.getLocation();
3796 
3797     // Perform literal operator lookup to determine if we're building a raw
3798     // literal or a cooked one.
3799     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3800     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3801                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3802                                   /*AllowStringTemplatePack*/ false,
3803                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3804     case LOLR_ErrorNoDiagnostic:
3805       // Lookup failure for imaginary constants isn't fatal, there's still the
3806       // GNU extension producing _Complex types.
3807       break;
3808     case LOLR_Error:
3809       return ExprError();
3810     case LOLR_Cooked: {
3811       Expr *Lit;
3812       if (Literal.isFloatingLiteral()) {
3813         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3814       } else {
3815         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3816         if (Literal.GetIntegerValue(ResultVal))
3817           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3818               << /* Unsigned */ 1;
3819         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3820                                      Tok.getLocation());
3821       }
3822       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3823     }
3824 
3825     case LOLR_Raw: {
3826       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3827       // literal is treated as a call of the form
3828       //   operator "" X ("n")
3829       unsigned Length = Literal.getUDSuffixOffset();
3830       QualType StrTy = Context.getConstantArrayType(
3831           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3832           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3833       Expr *Lit = StringLiteral::Create(
3834           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3835           /*Pascal*/false, StrTy, &TokLoc, 1);
3836       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3837     }
3838 
3839     case LOLR_Template: {
3840       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3841       // template), L is treated as a call fo the form
3842       //   operator "" X <'c1', 'c2', ... 'ck'>()
3843       // where n is the source character sequence c1 c2 ... ck.
3844       TemplateArgumentListInfo ExplicitArgs;
3845       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3846       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3847       llvm::APSInt Value(CharBits, CharIsUnsigned);
3848       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3849         Value = TokSpelling[I];
3850         TemplateArgument Arg(Context, Value, Context.CharTy);
3851         TemplateArgumentLocInfo ArgInfo;
3852         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3853       }
3854       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3855                                       &ExplicitArgs);
3856     }
3857     case LOLR_StringTemplatePack:
3858       llvm_unreachable("unexpected literal operator lookup result");
3859     }
3860   }
3861 
3862   Expr *Res;
3863 
3864   if (Literal.isFixedPointLiteral()) {
3865     QualType Ty;
3866 
3867     if (Literal.isAccum) {
3868       if (Literal.isHalf) {
3869         Ty = Context.ShortAccumTy;
3870       } else if (Literal.isLong) {
3871         Ty = Context.LongAccumTy;
3872       } else {
3873         Ty = Context.AccumTy;
3874       }
3875     } else if (Literal.isFract) {
3876       if (Literal.isHalf) {
3877         Ty = Context.ShortFractTy;
3878       } else if (Literal.isLong) {
3879         Ty = Context.LongFractTy;
3880       } else {
3881         Ty = Context.FractTy;
3882       }
3883     }
3884 
3885     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3886 
3887     bool isSigned = !Literal.isUnsigned;
3888     unsigned scale = Context.getFixedPointScale(Ty);
3889     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3890 
3891     llvm::APInt Val(bit_width, 0, isSigned);
3892     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3893     bool ValIsZero = Val.isZero() && !Overflowed;
3894 
3895     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3896     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3897       // Clause 6.4.4 - The value of a constant shall be in the range of
3898       // representable values for its type, with exception for constants of a
3899       // fract type with a value of exactly 1; such a constant shall denote
3900       // the maximal value for the type.
3901       --Val;
3902     else if (Val.ugt(MaxVal) || Overflowed)
3903       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3904 
3905     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3906                                               Tok.getLocation(), scale);
3907   } else if (Literal.isFloatingLiteral()) {
3908     QualType Ty;
3909     if (Literal.isHalf){
3910       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3911         Ty = Context.HalfTy;
3912       else {
3913         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3914         return ExprError();
3915       }
3916     } else if (Literal.isFloat)
3917       Ty = Context.FloatTy;
3918     else if (Literal.isLong)
3919       Ty = Context.LongDoubleTy;
3920     else if (Literal.isFloat16)
3921       Ty = Context.Float16Ty;
3922     else if (Literal.isFloat128)
3923       Ty = Context.Float128Ty;
3924     else
3925       Ty = Context.DoubleTy;
3926 
3927     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3928 
3929     if (Ty == Context.DoubleTy) {
3930       if (getLangOpts().SinglePrecisionConstants) {
3931         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3932           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3933         }
3934       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3935                                              "cl_khr_fp64", getLangOpts())) {
3936         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3937         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3938             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3939         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3940       }
3941     }
3942   } else if (!Literal.isIntegerLiteral()) {
3943     return ExprError();
3944   } else {
3945     QualType Ty;
3946 
3947     // 'long long' is a C99 or C++11 feature.
3948     if (!getLangOpts().C99 && Literal.isLongLong) {
3949       if (getLangOpts().CPlusPlus)
3950         Diag(Tok.getLocation(),
3951              getLangOpts().CPlusPlus11 ?
3952              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3953       else
3954         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3955     }
3956 
3957     // 'z/uz' literals are a C++2b feature.
3958     if (Literal.isSizeT)
3959       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3960                                   ? getLangOpts().CPlusPlus2b
3961                                         ? diag::warn_cxx20_compat_size_t_suffix
3962                                         : diag::ext_cxx2b_size_t_suffix
3963                                   : diag::err_cxx2b_size_t_suffix);
3964 
3965     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3966     // but we do not currently support the suffix in C++ mode because it's not
3967     // entirely clear whether WG21 will prefer this suffix to return a library
3968     // type such as std::bit_int instead of returning a _BitInt.
3969     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3970       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3971                                      ? diag::warn_c2x_compat_bitint_suffix
3972                                      : diag::ext_c2x_bitint_suffix);
3973 
3974     // Get the value in the widest-possible width. What is "widest" depends on
3975     // whether the literal is a bit-precise integer or not. For a bit-precise
3976     // integer type, try to scan the source to determine how many bits are
3977     // needed to represent the value. This may seem a bit expensive, but trying
3978     // to get the integer value from an overly-wide APInt is *extremely*
3979     // expensive, so the naive approach of assuming
3980     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3981     unsigned BitsNeeded =
3982         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3983                                Literal.getLiteralDigits(), Literal.getRadix())
3984                          : Context.getTargetInfo().getIntMaxTWidth();
3985     llvm::APInt ResultVal(BitsNeeded, 0);
3986 
3987     if (Literal.GetIntegerValue(ResultVal)) {
3988       // If this value didn't fit into uintmax_t, error and force to ull.
3989       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3990           << /* Unsigned */ 1;
3991       Ty = Context.UnsignedLongLongTy;
3992       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3993              "long long is not intmax_t?");
3994     } else {
3995       // If this value fits into a ULL, try to figure out what else it fits into
3996       // according to the rules of C99 6.4.4.1p5.
3997 
3998       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3999       // be an unsigned int.
4000       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4001 
4002       // Check from smallest to largest, picking the smallest type we can.
4003       unsigned Width = 0;
4004 
4005       // Microsoft specific integer suffixes are explicitly sized.
4006       if (Literal.MicrosoftInteger) {
4007         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4008           Width = 8;
4009           Ty = Context.CharTy;
4010         } else {
4011           Width = Literal.MicrosoftInteger;
4012           Ty = Context.getIntTypeForBitwidth(Width,
4013                                              /*Signed=*/!Literal.isUnsigned);
4014         }
4015       }
4016 
4017       // Bit-precise integer literals are automagically-sized based on the
4018       // width required by the literal.
4019       if (Literal.isBitInt) {
4020         // The signed version has one more bit for the sign value. There are no
4021         // zero-width bit-precise integers, even if the literal value is 0.
4022         Width = std::max(ResultVal.getActiveBits(), 1u) +
4023                 (Literal.isUnsigned ? 0u : 1u);
4024 
4025         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4026         // and reset the type to the largest supported width.
4027         unsigned int MaxBitIntWidth =
4028             Context.getTargetInfo().getMaxBitIntWidth();
4029         if (Width > MaxBitIntWidth) {
4030           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4031               << Literal.isUnsigned;
4032           Width = MaxBitIntWidth;
4033         }
4034 
4035         // Reset the result value to the smaller APInt and select the correct
4036         // type to be used. Note, we zext even for signed values because the
4037         // literal itself is always an unsigned value (a preceeding - is a
4038         // unary operator, not part of the literal).
4039         ResultVal = ResultVal.zextOrTrunc(Width);
4040         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4041       }
4042 
4043       // Check C++2b size_t literals.
4044       if (Literal.isSizeT) {
4045         assert(!Literal.MicrosoftInteger &&
4046                "size_t literals can't be Microsoft literals");
4047         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4048             Context.getTargetInfo().getSizeType());
4049 
4050         // Does it fit in size_t?
4051         if (ResultVal.isIntN(SizeTSize)) {
4052           // Does it fit in ssize_t?
4053           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4054             Ty = Context.getSignedSizeType();
4055           else if (AllowUnsigned)
4056             Ty = Context.getSizeType();
4057           Width = SizeTSize;
4058         }
4059       }
4060 
4061       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4062           !Literal.isSizeT) {
4063         // Are int/unsigned possibilities?
4064         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4065 
4066         // Does it fit in a unsigned int?
4067         if (ResultVal.isIntN(IntSize)) {
4068           // Does it fit in a signed int?
4069           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4070             Ty = Context.IntTy;
4071           else if (AllowUnsigned)
4072             Ty = Context.UnsignedIntTy;
4073           Width = IntSize;
4074         }
4075       }
4076 
4077       // Are long/unsigned long possibilities?
4078       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4079         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4080 
4081         // Does it fit in a unsigned long?
4082         if (ResultVal.isIntN(LongSize)) {
4083           // Does it fit in a signed long?
4084           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4085             Ty = Context.LongTy;
4086           else if (AllowUnsigned)
4087             Ty = Context.UnsignedLongTy;
4088           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4089           // is compatible.
4090           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4091             const unsigned LongLongSize =
4092                 Context.getTargetInfo().getLongLongWidth();
4093             Diag(Tok.getLocation(),
4094                  getLangOpts().CPlusPlus
4095                      ? Literal.isLong
4096                            ? diag::warn_old_implicitly_unsigned_long_cxx
4097                            : /*C++98 UB*/ diag::
4098                                  ext_old_implicitly_unsigned_long_cxx
4099                      : diag::warn_old_implicitly_unsigned_long)
4100                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4101                                             : /*will be ill-formed*/ 1);
4102             Ty = Context.UnsignedLongTy;
4103           }
4104           Width = LongSize;
4105         }
4106       }
4107 
4108       // Check long long if needed.
4109       if (Ty.isNull() && !Literal.isSizeT) {
4110         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4111 
4112         // Does it fit in a unsigned long long?
4113         if (ResultVal.isIntN(LongLongSize)) {
4114           // Does it fit in a signed long long?
4115           // To be compatible with MSVC, hex integer literals ending with the
4116           // LL or i64 suffix are always signed in Microsoft mode.
4117           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4118               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4119             Ty = Context.LongLongTy;
4120           else if (AllowUnsigned)
4121             Ty = Context.UnsignedLongLongTy;
4122           Width = LongLongSize;
4123         }
4124       }
4125 
4126       // If we still couldn't decide a type, we either have 'size_t' literal
4127       // that is out of range, or a decimal literal that does not fit in a
4128       // signed long long and has no U suffix.
4129       if (Ty.isNull()) {
4130         if (Literal.isSizeT)
4131           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4132               << Literal.isUnsigned;
4133         else
4134           Diag(Tok.getLocation(),
4135                diag::ext_integer_literal_too_large_for_signed);
4136         Ty = Context.UnsignedLongLongTy;
4137         Width = Context.getTargetInfo().getLongLongWidth();
4138       }
4139 
4140       if (ResultVal.getBitWidth() != Width)
4141         ResultVal = ResultVal.trunc(Width);
4142     }
4143     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4144   }
4145 
4146   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4147   if (Literal.isImaginary) {
4148     Res = new (Context) ImaginaryLiteral(Res,
4149                                         Context.getComplexType(Res->getType()));
4150 
4151     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4152   }
4153   return Res;
4154 }
4155 
4156 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4157   assert(E && "ActOnParenExpr() missing expr");
4158   QualType ExprTy = E->getType();
4159   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4160       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4161     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4162   return new (Context) ParenExpr(L, R, E);
4163 }
4164 
4165 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4166                                          SourceLocation Loc,
4167                                          SourceRange ArgRange) {
4168   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4169   // scalar or vector data type argument..."
4170   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4171   // type (C99 6.2.5p18) or void.
4172   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4173     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4174       << T << ArgRange;
4175     return true;
4176   }
4177 
4178   assert((T->isVoidType() || !T->isIncompleteType()) &&
4179          "Scalar types should always be complete");
4180   return false;
4181 }
4182 
4183 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4184                                            SourceLocation Loc,
4185                                            SourceRange ArgRange,
4186                                            UnaryExprOrTypeTrait TraitKind) {
4187   // Invalid types must be hard errors for SFINAE in C++.
4188   if (S.LangOpts.CPlusPlus)
4189     return true;
4190 
4191   // C99 6.5.3.4p1:
4192   if (T->isFunctionType() &&
4193       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4194        TraitKind == UETT_PreferredAlignOf)) {
4195     // sizeof(function)/alignof(function) is allowed as an extension.
4196     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4197         << getTraitSpelling(TraitKind) << ArgRange;
4198     return false;
4199   }
4200 
4201   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4202   // this is an error (OpenCL v1.1 s6.3.k)
4203   if (T->isVoidType()) {
4204     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4205                                         : diag::ext_sizeof_alignof_void_type;
4206     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4207     return false;
4208   }
4209 
4210   return true;
4211 }
4212 
4213 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4214                                              SourceLocation Loc,
4215                                              SourceRange ArgRange,
4216                                              UnaryExprOrTypeTrait TraitKind) {
4217   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4218   // runtime doesn't allow it.
4219   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4220     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4221       << T << (TraitKind == UETT_SizeOf)
4222       << ArgRange;
4223     return true;
4224   }
4225 
4226   return false;
4227 }
4228 
4229 /// Check whether E is a pointer from a decayed array type (the decayed
4230 /// pointer type is equal to T) and emit a warning if it is.
4231 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4232                                      Expr *E) {
4233   // Don't warn if the operation changed the type.
4234   if (T != E->getType())
4235     return;
4236 
4237   // Now look for array decays.
4238   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4239   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4240     return;
4241 
4242   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4243                                              << ICE->getType()
4244                                              << ICE->getSubExpr()->getType();
4245 }
4246 
4247 /// Check the constraints on expression operands to unary type expression
4248 /// and type traits.
4249 ///
4250 /// Completes any types necessary and validates the constraints on the operand
4251 /// expression. The logic mostly mirrors the type-based overload, but may modify
4252 /// the expression as it completes the type for that expression through template
4253 /// instantiation, etc.
4254 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4255                                             UnaryExprOrTypeTrait ExprKind) {
4256   QualType ExprTy = E->getType();
4257   assert(!ExprTy->isReferenceType());
4258 
4259   bool IsUnevaluatedOperand =
4260       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4261        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4262   if (IsUnevaluatedOperand) {
4263     ExprResult Result = CheckUnevaluatedOperand(E);
4264     if (Result.isInvalid())
4265       return true;
4266     E = Result.get();
4267   }
4268 
4269   // The operand for sizeof and alignof is in an unevaluated expression context,
4270   // so side effects could result in unintended consequences.
4271   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4272   // used to build SFINAE gadgets.
4273   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4274   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4275       !E->isInstantiationDependent() &&
4276       !E->getType()->isVariableArrayType() &&
4277       E->HasSideEffects(Context, false))
4278     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4279 
4280   if (ExprKind == UETT_VecStep)
4281     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4282                                         E->getSourceRange());
4283 
4284   // Explicitly list some types as extensions.
4285   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4286                                       E->getSourceRange(), ExprKind))
4287     return false;
4288 
4289   // 'alignof' applied to an expression only requires the base element type of
4290   // the expression to be complete. 'sizeof' requires the expression's type to
4291   // be complete (and will attempt to complete it if it's an array of unknown
4292   // bound).
4293   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4294     if (RequireCompleteSizedType(
4295             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4296             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4297             getTraitSpelling(ExprKind), E->getSourceRange()))
4298       return true;
4299   } else {
4300     if (RequireCompleteSizedExprType(
4301             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4302             getTraitSpelling(ExprKind), E->getSourceRange()))
4303       return true;
4304   }
4305 
4306   // Completing the expression's type may have changed it.
4307   ExprTy = E->getType();
4308   assert(!ExprTy->isReferenceType());
4309 
4310   if (ExprTy->isFunctionType()) {
4311     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4312         << getTraitSpelling(ExprKind) << E->getSourceRange();
4313     return true;
4314   }
4315 
4316   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4317                                        E->getSourceRange(), ExprKind))
4318     return true;
4319 
4320   if (ExprKind == UETT_SizeOf) {
4321     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4322       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4323         QualType OType = PVD->getOriginalType();
4324         QualType Type = PVD->getType();
4325         if (Type->isPointerType() && OType->isArrayType()) {
4326           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4327             << Type << OType;
4328           Diag(PVD->getLocation(), diag::note_declared_at);
4329         }
4330       }
4331     }
4332 
4333     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4334     // decays into a pointer and returns an unintended result. This is most
4335     // likely a typo for "sizeof(array) op x".
4336     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4337       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4338                                BO->getLHS());
4339       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4340                                BO->getRHS());
4341     }
4342   }
4343 
4344   return false;
4345 }
4346 
4347 /// Check the constraints on operands to unary expression and type
4348 /// traits.
4349 ///
4350 /// This will complete any types necessary, and validate the various constraints
4351 /// on those operands.
4352 ///
4353 /// The UsualUnaryConversions() function is *not* called by this routine.
4354 /// C99 6.3.2.1p[2-4] all state:
4355 ///   Except when it is the operand of the sizeof operator ...
4356 ///
4357 /// C++ [expr.sizeof]p4
4358 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4359 ///   standard conversions are not applied to the operand of sizeof.
4360 ///
4361 /// This policy is followed for all of the unary trait expressions.
4362 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4363                                             SourceLocation OpLoc,
4364                                             SourceRange ExprRange,
4365                                             UnaryExprOrTypeTrait ExprKind) {
4366   if (ExprType->isDependentType())
4367     return false;
4368 
4369   // C++ [expr.sizeof]p2:
4370   //     When applied to a reference or a reference type, the result
4371   //     is the size of the referenced type.
4372   // C++11 [expr.alignof]p3:
4373   //     When alignof is applied to a reference type, the result
4374   //     shall be the alignment of the referenced type.
4375   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4376     ExprType = Ref->getPointeeType();
4377 
4378   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4379   //   When alignof or _Alignof is applied to an array type, the result
4380   //   is the alignment of the element type.
4381   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4382       ExprKind == UETT_OpenMPRequiredSimdAlign)
4383     ExprType = Context.getBaseElementType(ExprType);
4384 
4385   if (ExprKind == UETT_VecStep)
4386     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4387 
4388   // Explicitly list some types as extensions.
4389   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4390                                       ExprKind))
4391     return false;
4392 
4393   if (RequireCompleteSizedType(
4394           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4395           getTraitSpelling(ExprKind), ExprRange))
4396     return true;
4397 
4398   if (ExprType->isFunctionType()) {
4399     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4400         << getTraitSpelling(ExprKind) << ExprRange;
4401     return true;
4402   }
4403 
4404   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4405                                        ExprKind))
4406     return true;
4407 
4408   return false;
4409 }
4410 
4411 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4412   // Cannot know anything else if the expression is dependent.
4413   if (E->isTypeDependent())
4414     return false;
4415 
4416   if (E->getObjectKind() == OK_BitField) {
4417     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4418        << 1 << E->getSourceRange();
4419     return true;
4420   }
4421 
4422   ValueDecl *D = nullptr;
4423   Expr *Inner = E->IgnoreParens();
4424   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4425     D = DRE->getDecl();
4426   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4427     D = ME->getMemberDecl();
4428   }
4429 
4430   // If it's a field, require the containing struct to have a
4431   // complete definition so that we can compute the layout.
4432   //
4433   // This can happen in C++11 onwards, either by naming the member
4434   // in a way that is not transformed into a member access expression
4435   // (in an unevaluated operand, for instance), or by naming the member
4436   // in a trailing-return-type.
4437   //
4438   // For the record, since __alignof__ on expressions is a GCC
4439   // extension, GCC seems to permit this but always gives the
4440   // nonsensical answer 0.
4441   //
4442   // We don't really need the layout here --- we could instead just
4443   // directly check for all the appropriate alignment-lowing
4444   // attributes --- but that would require duplicating a lot of
4445   // logic that just isn't worth duplicating for such a marginal
4446   // use-case.
4447   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4448     // Fast path this check, since we at least know the record has a
4449     // definition if we can find a member of it.
4450     if (!FD->getParent()->isCompleteDefinition()) {
4451       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4452         << E->getSourceRange();
4453       return true;
4454     }
4455 
4456     // Otherwise, if it's a field, and the field doesn't have
4457     // reference type, then it must have a complete type (or be a
4458     // flexible array member, which we explicitly want to
4459     // white-list anyway), which makes the following checks trivial.
4460     if (!FD->getType()->isReferenceType())
4461       return false;
4462   }
4463 
4464   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4465 }
4466 
4467 bool Sema::CheckVecStepExpr(Expr *E) {
4468   E = E->IgnoreParens();
4469 
4470   // Cannot know anything else if the expression is dependent.
4471   if (E->isTypeDependent())
4472     return false;
4473 
4474   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4475 }
4476 
4477 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4478                                         CapturingScopeInfo *CSI) {
4479   assert(T->isVariablyModifiedType());
4480   assert(CSI != nullptr);
4481 
4482   // We're going to walk down into the type and look for VLA expressions.
4483   do {
4484     const Type *Ty = T.getTypePtr();
4485     switch (Ty->getTypeClass()) {
4486 #define TYPE(Class, Base)
4487 #define ABSTRACT_TYPE(Class, Base)
4488 #define NON_CANONICAL_TYPE(Class, Base)
4489 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4490 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4491 #include "clang/AST/TypeNodes.inc"
4492       T = QualType();
4493       break;
4494     // These types are never variably-modified.
4495     case Type::Builtin:
4496     case Type::Complex:
4497     case Type::Vector:
4498     case Type::ExtVector:
4499     case Type::ConstantMatrix:
4500     case Type::Record:
4501     case Type::Enum:
4502     case Type::Elaborated:
4503     case Type::TemplateSpecialization:
4504     case Type::ObjCObject:
4505     case Type::ObjCInterface:
4506     case Type::ObjCObjectPointer:
4507     case Type::ObjCTypeParam:
4508     case Type::Pipe:
4509     case Type::BitInt:
4510       llvm_unreachable("type class is never variably-modified!");
4511     case Type::Adjusted:
4512       T = cast<AdjustedType>(Ty)->getOriginalType();
4513       break;
4514     case Type::Decayed:
4515       T = cast<DecayedType>(Ty)->getPointeeType();
4516       break;
4517     case Type::Pointer:
4518       T = cast<PointerType>(Ty)->getPointeeType();
4519       break;
4520     case Type::BlockPointer:
4521       T = cast<BlockPointerType>(Ty)->getPointeeType();
4522       break;
4523     case Type::LValueReference:
4524     case Type::RValueReference:
4525       T = cast<ReferenceType>(Ty)->getPointeeType();
4526       break;
4527     case Type::MemberPointer:
4528       T = cast<MemberPointerType>(Ty)->getPointeeType();
4529       break;
4530     case Type::ConstantArray:
4531     case Type::IncompleteArray:
4532       // Losing element qualification here is fine.
4533       T = cast<ArrayType>(Ty)->getElementType();
4534       break;
4535     case Type::VariableArray: {
4536       // Losing element qualification here is fine.
4537       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4538 
4539       // Unknown size indication requires no size computation.
4540       // Otherwise, evaluate and record it.
4541       auto Size = VAT->getSizeExpr();
4542       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4543           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4544         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4545 
4546       T = VAT->getElementType();
4547       break;
4548     }
4549     case Type::FunctionProto:
4550     case Type::FunctionNoProto:
4551       T = cast<FunctionType>(Ty)->getReturnType();
4552       break;
4553     case Type::Paren:
4554     case Type::TypeOf:
4555     case Type::UnaryTransform:
4556     case Type::Attributed:
4557     case Type::BTFTagAttributed:
4558     case Type::SubstTemplateTypeParm:
4559     case Type::MacroQualified:
4560       // Keep walking after single level desugaring.
4561       T = T.getSingleStepDesugaredType(Context);
4562       break;
4563     case Type::Typedef:
4564       T = cast<TypedefType>(Ty)->desugar();
4565       break;
4566     case Type::Decltype:
4567       T = cast<DecltypeType>(Ty)->desugar();
4568       break;
4569     case Type::Using:
4570       T = cast<UsingType>(Ty)->desugar();
4571       break;
4572     case Type::Auto:
4573     case Type::DeducedTemplateSpecialization:
4574       T = cast<DeducedType>(Ty)->getDeducedType();
4575       break;
4576     case Type::TypeOfExpr:
4577       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4578       break;
4579     case Type::Atomic:
4580       T = cast<AtomicType>(Ty)->getValueType();
4581       break;
4582     }
4583   } while (!T.isNull() && T->isVariablyModifiedType());
4584 }
4585 
4586 /// Build a sizeof or alignof expression given a type operand.
4587 ExprResult
4588 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4589                                      SourceLocation OpLoc,
4590                                      UnaryExprOrTypeTrait ExprKind,
4591                                      SourceRange R) {
4592   if (!TInfo)
4593     return ExprError();
4594 
4595   QualType T = TInfo->getType();
4596 
4597   if (!T->isDependentType() &&
4598       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4599     return ExprError();
4600 
4601   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4602     if (auto *TT = T->getAs<TypedefType>()) {
4603       for (auto I = FunctionScopes.rbegin(),
4604                 E = std::prev(FunctionScopes.rend());
4605            I != E; ++I) {
4606         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4607         if (CSI == nullptr)
4608           break;
4609         DeclContext *DC = nullptr;
4610         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4611           DC = LSI->CallOperator;
4612         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4613           DC = CRSI->TheCapturedDecl;
4614         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4615           DC = BSI->TheDecl;
4616         if (DC) {
4617           if (DC->containsDecl(TT->getDecl()))
4618             break;
4619           captureVariablyModifiedType(Context, T, CSI);
4620         }
4621       }
4622     }
4623   }
4624 
4625   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4626   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4627       TInfo->getType()->isVariablyModifiedType())
4628     TInfo = TransformToPotentiallyEvaluated(TInfo);
4629 
4630   return new (Context) UnaryExprOrTypeTraitExpr(
4631       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4632 }
4633 
4634 /// Build a sizeof or alignof expression given an expression
4635 /// operand.
4636 ExprResult
4637 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4638                                      UnaryExprOrTypeTrait ExprKind) {
4639   ExprResult PE = CheckPlaceholderExpr(E);
4640   if (PE.isInvalid())
4641     return ExprError();
4642 
4643   E = PE.get();
4644 
4645   // Verify that the operand is valid.
4646   bool isInvalid = false;
4647   if (E->isTypeDependent()) {
4648     // Delay type-checking for type-dependent expressions.
4649   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4650     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4651   } else if (ExprKind == UETT_VecStep) {
4652     isInvalid = CheckVecStepExpr(E);
4653   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4654       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4655       isInvalid = true;
4656   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4657     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4658     isInvalid = true;
4659   } else {
4660     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4661   }
4662 
4663   if (isInvalid)
4664     return ExprError();
4665 
4666   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4667     PE = TransformToPotentiallyEvaluated(E);
4668     if (PE.isInvalid()) return ExprError();
4669     E = PE.get();
4670   }
4671 
4672   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4673   return new (Context) UnaryExprOrTypeTraitExpr(
4674       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4675 }
4676 
4677 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4678 /// expr and the same for @c alignof and @c __alignof
4679 /// Note that the ArgRange is invalid if isType is false.
4680 ExprResult
4681 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4682                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4683                                     void *TyOrEx, SourceRange ArgRange) {
4684   // If error parsing type, ignore.
4685   if (!TyOrEx) return ExprError();
4686 
4687   if (IsType) {
4688     TypeSourceInfo *TInfo;
4689     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4690     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4691   }
4692 
4693   Expr *ArgEx = (Expr *)TyOrEx;
4694   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4695   return Result;
4696 }
4697 
4698 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4699                                      bool IsReal) {
4700   if (V.get()->isTypeDependent())
4701     return S.Context.DependentTy;
4702 
4703   // _Real and _Imag are only l-values for normal l-values.
4704   if (V.get()->getObjectKind() != OK_Ordinary) {
4705     V = S.DefaultLvalueConversion(V.get());
4706     if (V.isInvalid())
4707       return QualType();
4708   }
4709 
4710   // These operators return the element type of a complex type.
4711   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4712     return CT->getElementType();
4713 
4714   // Otherwise they pass through real integer and floating point types here.
4715   if (V.get()->getType()->isArithmeticType())
4716     return V.get()->getType();
4717 
4718   // Test for placeholders.
4719   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4720   if (PR.isInvalid()) return QualType();
4721   if (PR.get() != V.get()) {
4722     V = PR;
4723     return CheckRealImagOperand(S, V, Loc, IsReal);
4724   }
4725 
4726   // Reject anything else.
4727   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4728     << (IsReal ? "__real" : "__imag");
4729   return QualType();
4730 }
4731 
4732 
4733 
4734 ExprResult
4735 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4736                           tok::TokenKind Kind, Expr *Input) {
4737   UnaryOperatorKind Opc;
4738   switch (Kind) {
4739   default: llvm_unreachable("Unknown unary op!");
4740   case tok::plusplus:   Opc = UO_PostInc; break;
4741   case tok::minusminus: Opc = UO_PostDec; break;
4742   }
4743 
4744   // Since this might is a postfix expression, get rid of ParenListExprs.
4745   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4746   if (Result.isInvalid()) return ExprError();
4747   Input = Result.get();
4748 
4749   return BuildUnaryOp(S, OpLoc, Opc, Input);
4750 }
4751 
4752 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4753 ///
4754 /// \return true on error
4755 static bool checkArithmeticOnObjCPointer(Sema &S,
4756                                          SourceLocation opLoc,
4757                                          Expr *op) {
4758   assert(op->getType()->isObjCObjectPointerType());
4759   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4760       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4761     return false;
4762 
4763   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4764     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4765     << op->getSourceRange();
4766   return true;
4767 }
4768 
4769 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4770   auto *BaseNoParens = Base->IgnoreParens();
4771   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4772     return MSProp->getPropertyDecl()->getType()->isArrayType();
4773   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4774 }
4775 
4776 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4777 // Typically this is DependentTy, but can sometimes be more precise.
4778 //
4779 // There are cases when we could determine a non-dependent type:
4780 //  - LHS and RHS may have non-dependent types despite being type-dependent
4781 //    (e.g. unbounded array static members of the current instantiation)
4782 //  - one may be a dependent-sized array with known element type
4783 //  - one may be a dependent-typed valid index (enum in current instantiation)
4784 //
4785 // We *always* return a dependent type, in such cases it is DependentTy.
4786 // This avoids creating type-dependent expressions with non-dependent types.
4787 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4788 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4789                                                const ASTContext &Ctx) {
4790   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4791   QualType LTy = LHS->getType(), RTy = RHS->getType();
4792   QualType Result = Ctx.DependentTy;
4793   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4794     if (const PointerType *PT = LTy->getAs<PointerType>())
4795       Result = PT->getPointeeType();
4796     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4797       Result = AT->getElementType();
4798   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4799     if (const PointerType *PT = RTy->getAs<PointerType>())
4800       Result = PT->getPointeeType();
4801     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4802       Result = AT->getElementType();
4803   }
4804   // Ensure we return a dependent type.
4805   return Result->isDependentType() ? Result : Ctx.DependentTy;
4806 }
4807 
4808 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4809 
4810 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4811                                          SourceLocation lbLoc,
4812                                          MultiExprArg ArgExprs,
4813                                          SourceLocation rbLoc) {
4814 
4815   if (base && !base->getType().isNull() &&
4816       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4817     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4818                                     SourceLocation(), /*Length*/ nullptr,
4819                                     /*Stride=*/nullptr, rbLoc);
4820 
4821   // Since this might be a postfix expression, get rid of ParenListExprs.
4822   if (isa<ParenListExpr>(base)) {
4823     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4824     if (result.isInvalid())
4825       return ExprError();
4826     base = result.get();
4827   }
4828 
4829   // Check if base and idx form a MatrixSubscriptExpr.
4830   //
4831   // Helper to check for comma expressions, which are not allowed as indices for
4832   // matrix subscript expressions.
4833   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4834     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4835       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4836           << SourceRange(base->getBeginLoc(), rbLoc);
4837       return true;
4838     }
4839     return false;
4840   };
4841   // The matrix subscript operator ([][])is considered a single operator.
4842   // Separating the index expressions by parenthesis is not allowed.
4843   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4844       !isa<MatrixSubscriptExpr>(base)) {
4845     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4846         << SourceRange(base->getBeginLoc(), rbLoc);
4847     return ExprError();
4848   }
4849   // If the base is a MatrixSubscriptExpr, try to create a new
4850   // MatrixSubscriptExpr.
4851   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4852   if (matSubscriptE) {
4853     assert(ArgExprs.size() == 1);
4854     if (CheckAndReportCommaError(ArgExprs.front()))
4855       return ExprError();
4856 
4857     assert(matSubscriptE->isIncomplete() &&
4858            "base has to be an incomplete matrix subscript");
4859     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4860                                             matSubscriptE->getRowIdx(),
4861                                             ArgExprs.front(), rbLoc);
4862   }
4863 
4864   // Handle any non-overload placeholder types in the base and index
4865   // expressions.  We can't handle overloads here because the other
4866   // operand might be an overloadable type, in which case the overload
4867   // resolution for the operator overload should get the first crack
4868   // at the overload.
4869   bool IsMSPropertySubscript = false;
4870   if (base->getType()->isNonOverloadPlaceholderType()) {
4871     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4872     if (!IsMSPropertySubscript) {
4873       ExprResult result = CheckPlaceholderExpr(base);
4874       if (result.isInvalid())
4875         return ExprError();
4876       base = result.get();
4877     }
4878   }
4879 
4880   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4881   if (base->getType()->isMatrixType()) {
4882     assert(ArgExprs.size() == 1);
4883     if (CheckAndReportCommaError(ArgExprs.front()))
4884       return ExprError();
4885 
4886     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4887                                             rbLoc);
4888   }
4889 
4890   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4891     Expr *idx = ArgExprs[0];
4892     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4893         (isa<CXXOperatorCallExpr>(idx) &&
4894          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4895       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4896           << SourceRange(base->getBeginLoc(), rbLoc);
4897     }
4898   }
4899 
4900   if (ArgExprs.size() == 1 &&
4901       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4902     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4903     if (result.isInvalid())
4904       return ExprError();
4905     ArgExprs[0] = result.get();
4906   } else {
4907     if (checkArgsForPlaceholders(*this, ArgExprs))
4908       return ExprError();
4909   }
4910 
4911   // Build an unanalyzed expression if either operand is type-dependent.
4912   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4913       (base->isTypeDependent() ||
4914        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4915     return new (Context) ArraySubscriptExpr(
4916         base, ArgExprs.front(),
4917         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4918         VK_LValue, OK_Ordinary, rbLoc);
4919   }
4920 
4921   // MSDN, property (C++)
4922   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4923   // This attribute can also be used in the declaration of an empty array in a
4924   // class or structure definition. For example:
4925   // __declspec(property(get=GetX, put=PutX)) int x[];
4926   // The above statement indicates that x[] can be used with one or more array
4927   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4928   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4929   if (IsMSPropertySubscript) {
4930     assert(ArgExprs.size() == 1);
4931     // Build MS property subscript expression if base is MS property reference
4932     // or MS property subscript.
4933     return new (Context)
4934         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4935                                 VK_LValue, OK_Ordinary, rbLoc);
4936   }
4937 
4938   // Use C++ overloaded-operator rules if either operand has record
4939   // type.  The spec says to do this if either type is *overloadable*,
4940   // but enum types can't declare subscript operators or conversion
4941   // operators, so there's nothing interesting for overload resolution
4942   // to do if there aren't any record types involved.
4943   //
4944   // ObjC pointers have their own subscripting logic that is not tied
4945   // to overload resolution and so should not take this path.
4946   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4947       ((base->getType()->isRecordType() ||
4948         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4949     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4950   }
4951 
4952   ExprResult Res =
4953       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4954 
4955   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4956     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4957 
4958   return Res;
4959 }
4960 
4961 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4962   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4963   InitializationKind Kind =
4964       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4965   InitializationSequence InitSeq(*this, Entity, Kind, E);
4966   return InitSeq.Perform(*this, Entity, Kind, E);
4967 }
4968 
4969 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4970                                                   Expr *ColumnIdx,
4971                                                   SourceLocation RBLoc) {
4972   ExprResult BaseR = CheckPlaceholderExpr(Base);
4973   if (BaseR.isInvalid())
4974     return BaseR;
4975   Base = BaseR.get();
4976 
4977   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4978   if (RowR.isInvalid())
4979     return RowR;
4980   RowIdx = RowR.get();
4981 
4982   if (!ColumnIdx)
4983     return new (Context) MatrixSubscriptExpr(
4984         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4985 
4986   // Build an unanalyzed expression if any of the operands is type-dependent.
4987   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4988       ColumnIdx->isTypeDependent())
4989     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4990                                              Context.DependentTy, RBLoc);
4991 
4992   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4993   if (ColumnR.isInvalid())
4994     return ColumnR;
4995   ColumnIdx = ColumnR.get();
4996 
4997   // Check that IndexExpr is an integer expression. If it is a constant
4998   // expression, check that it is less than Dim (= the number of elements in the
4999   // corresponding dimension).
5000   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5001                           bool IsColumnIdx) -> Expr * {
5002     if (!IndexExpr->getType()->isIntegerType() &&
5003         !IndexExpr->isTypeDependent()) {
5004       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5005           << IsColumnIdx;
5006       return nullptr;
5007     }
5008 
5009     if (Optional<llvm::APSInt> Idx =
5010             IndexExpr->getIntegerConstantExpr(Context)) {
5011       if ((*Idx < 0 || *Idx >= Dim)) {
5012         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5013             << IsColumnIdx << Dim;
5014         return nullptr;
5015       }
5016     }
5017 
5018     ExprResult ConvExpr =
5019         tryConvertExprToType(IndexExpr, Context.getSizeType());
5020     assert(!ConvExpr.isInvalid() &&
5021            "should be able to convert any integer type to size type");
5022     return ConvExpr.get();
5023   };
5024 
5025   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5026   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5027   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5028   if (!RowIdx || !ColumnIdx)
5029     return ExprError();
5030 
5031   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5032                                            MTy->getElementType(), RBLoc);
5033 }
5034 
5035 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5036   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5037   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5038 
5039   // For expressions like `&(*s).b`, the base is recorded and what should be
5040   // checked.
5041   const MemberExpr *Member = nullptr;
5042   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5043     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5044 
5045   LastRecord.PossibleDerefs.erase(StrippedExpr);
5046 }
5047 
5048 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5049   if (isUnevaluatedContext())
5050     return;
5051 
5052   QualType ResultTy = E->getType();
5053   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5054 
5055   // Bail if the element is an array since it is not memory access.
5056   if (isa<ArrayType>(ResultTy))
5057     return;
5058 
5059   if (ResultTy->hasAttr(attr::NoDeref)) {
5060     LastRecord.PossibleDerefs.insert(E);
5061     return;
5062   }
5063 
5064   // Check if the base type is a pointer to a member access of a struct
5065   // marked with noderef.
5066   const Expr *Base = E->getBase();
5067   QualType BaseTy = Base->getType();
5068   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5069     // Not a pointer access
5070     return;
5071 
5072   const MemberExpr *Member = nullptr;
5073   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5074          Member->isArrow())
5075     Base = Member->getBase();
5076 
5077   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5078     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5079       LastRecord.PossibleDerefs.insert(E);
5080   }
5081 }
5082 
5083 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5084                                           Expr *LowerBound,
5085                                           SourceLocation ColonLocFirst,
5086                                           SourceLocation ColonLocSecond,
5087                                           Expr *Length, Expr *Stride,
5088                                           SourceLocation RBLoc) {
5089   if (Base->hasPlaceholderType() &&
5090       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5091     ExprResult Result = CheckPlaceholderExpr(Base);
5092     if (Result.isInvalid())
5093       return ExprError();
5094     Base = Result.get();
5095   }
5096   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5097     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5098     if (Result.isInvalid())
5099       return ExprError();
5100     Result = DefaultLvalueConversion(Result.get());
5101     if (Result.isInvalid())
5102       return ExprError();
5103     LowerBound = Result.get();
5104   }
5105   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5106     ExprResult Result = CheckPlaceholderExpr(Length);
5107     if (Result.isInvalid())
5108       return ExprError();
5109     Result = DefaultLvalueConversion(Result.get());
5110     if (Result.isInvalid())
5111       return ExprError();
5112     Length = Result.get();
5113   }
5114   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5115     ExprResult Result = CheckPlaceholderExpr(Stride);
5116     if (Result.isInvalid())
5117       return ExprError();
5118     Result = DefaultLvalueConversion(Result.get());
5119     if (Result.isInvalid())
5120       return ExprError();
5121     Stride = Result.get();
5122   }
5123 
5124   // Build an unanalyzed expression if either operand is type-dependent.
5125   if (Base->isTypeDependent() ||
5126       (LowerBound &&
5127        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5128       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5129       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5130     return new (Context) OMPArraySectionExpr(
5131         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5132         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5133   }
5134 
5135   // Perform default conversions.
5136   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5137   QualType ResultTy;
5138   if (OriginalTy->isAnyPointerType()) {
5139     ResultTy = OriginalTy->getPointeeType();
5140   } else if (OriginalTy->isArrayType()) {
5141     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5142   } else {
5143     return ExprError(
5144         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5145         << Base->getSourceRange());
5146   }
5147   // C99 6.5.2.1p1
5148   if (LowerBound) {
5149     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5150                                                       LowerBound);
5151     if (Res.isInvalid())
5152       return ExprError(Diag(LowerBound->getExprLoc(),
5153                             diag::err_omp_typecheck_section_not_integer)
5154                        << 0 << LowerBound->getSourceRange());
5155     LowerBound = Res.get();
5156 
5157     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5158         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5159       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5160           << 0 << LowerBound->getSourceRange();
5161   }
5162   if (Length) {
5163     auto Res =
5164         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5165     if (Res.isInvalid())
5166       return ExprError(Diag(Length->getExprLoc(),
5167                             diag::err_omp_typecheck_section_not_integer)
5168                        << 1 << Length->getSourceRange());
5169     Length = Res.get();
5170 
5171     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5172         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5173       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5174           << 1 << Length->getSourceRange();
5175   }
5176   if (Stride) {
5177     ExprResult Res =
5178         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5179     if (Res.isInvalid())
5180       return ExprError(Diag(Stride->getExprLoc(),
5181                             diag::err_omp_typecheck_section_not_integer)
5182                        << 1 << Stride->getSourceRange());
5183     Stride = Res.get();
5184 
5185     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5186         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5187       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5188           << 1 << Stride->getSourceRange();
5189   }
5190 
5191   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5192   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5193   // type. Note that functions are not objects, and that (in C99 parlance)
5194   // incomplete types are not object types.
5195   if (ResultTy->isFunctionType()) {
5196     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5197         << ResultTy << Base->getSourceRange();
5198     return ExprError();
5199   }
5200 
5201   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5202                           diag::err_omp_section_incomplete_type, Base))
5203     return ExprError();
5204 
5205   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5206     Expr::EvalResult Result;
5207     if (LowerBound->EvaluateAsInt(Result, Context)) {
5208       // OpenMP 5.0, [2.1.5 Array Sections]
5209       // The array section must be a subset of the original array.
5210       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5211       if (LowerBoundValue.isNegative()) {
5212         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5213             << LowerBound->getSourceRange();
5214         return ExprError();
5215       }
5216     }
5217   }
5218 
5219   if (Length) {
5220     Expr::EvalResult Result;
5221     if (Length->EvaluateAsInt(Result, Context)) {
5222       // OpenMP 5.0, [2.1.5 Array Sections]
5223       // The length must evaluate to non-negative integers.
5224       llvm::APSInt LengthValue = Result.Val.getInt();
5225       if (LengthValue.isNegative()) {
5226         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5227             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5228             << Length->getSourceRange();
5229         return ExprError();
5230       }
5231     }
5232   } else if (ColonLocFirst.isValid() &&
5233              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5234                                       !OriginalTy->isVariableArrayType()))) {
5235     // OpenMP 5.0, [2.1.5 Array Sections]
5236     // When the size of the array dimension is not known, the length must be
5237     // specified explicitly.
5238     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5239         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5240     return ExprError();
5241   }
5242 
5243   if (Stride) {
5244     Expr::EvalResult Result;
5245     if (Stride->EvaluateAsInt(Result, Context)) {
5246       // OpenMP 5.0, [2.1.5 Array Sections]
5247       // The stride must evaluate to a positive integer.
5248       llvm::APSInt StrideValue = Result.Val.getInt();
5249       if (!StrideValue.isStrictlyPositive()) {
5250         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5251             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5252             << Stride->getSourceRange();
5253         return ExprError();
5254       }
5255     }
5256   }
5257 
5258   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5259     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5260     if (Result.isInvalid())
5261       return ExprError();
5262     Base = Result.get();
5263   }
5264   return new (Context) OMPArraySectionExpr(
5265       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5266       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5267 }
5268 
5269 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5270                                           SourceLocation RParenLoc,
5271                                           ArrayRef<Expr *> Dims,
5272                                           ArrayRef<SourceRange> Brackets) {
5273   if (Base->hasPlaceholderType()) {
5274     ExprResult Result = CheckPlaceholderExpr(Base);
5275     if (Result.isInvalid())
5276       return ExprError();
5277     Result = DefaultLvalueConversion(Result.get());
5278     if (Result.isInvalid())
5279       return ExprError();
5280     Base = Result.get();
5281   }
5282   QualType BaseTy = Base->getType();
5283   // Delay analysis of the types/expressions if instantiation/specialization is
5284   // required.
5285   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5286     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5287                                        LParenLoc, RParenLoc, Dims, Brackets);
5288   if (!BaseTy->isPointerType() ||
5289       (!Base->isTypeDependent() &&
5290        BaseTy->getPointeeType()->isIncompleteType()))
5291     return ExprError(Diag(Base->getExprLoc(),
5292                           diag::err_omp_non_pointer_type_array_shaping_base)
5293                      << Base->getSourceRange());
5294 
5295   SmallVector<Expr *, 4> NewDims;
5296   bool ErrorFound = false;
5297   for (Expr *Dim : Dims) {
5298     if (Dim->hasPlaceholderType()) {
5299       ExprResult Result = CheckPlaceholderExpr(Dim);
5300       if (Result.isInvalid()) {
5301         ErrorFound = true;
5302         continue;
5303       }
5304       Result = DefaultLvalueConversion(Result.get());
5305       if (Result.isInvalid()) {
5306         ErrorFound = true;
5307         continue;
5308       }
5309       Dim = Result.get();
5310     }
5311     if (!Dim->isTypeDependent()) {
5312       ExprResult Result =
5313           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5314       if (Result.isInvalid()) {
5315         ErrorFound = true;
5316         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5317             << Dim->getSourceRange();
5318         continue;
5319       }
5320       Dim = Result.get();
5321       Expr::EvalResult EvResult;
5322       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5323         // OpenMP 5.0, [2.1.4 Array Shaping]
5324         // Each si is an integral type expression that must evaluate to a
5325         // positive integer.
5326         llvm::APSInt Value = EvResult.Val.getInt();
5327         if (!Value.isStrictlyPositive()) {
5328           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5329               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5330               << Dim->getSourceRange();
5331           ErrorFound = true;
5332           continue;
5333         }
5334       }
5335     }
5336     NewDims.push_back(Dim);
5337   }
5338   if (ErrorFound)
5339     return ExprError();
5340   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5341                                      LParenLoc, RParenLoc, NewDims, Brackets);
5342 }
5343 
5344 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5345                                       SourceLocation LLoc, SourceLocation RLoc,
5346                                       ArrayRef<OMPIteratorData> Data) {
5347   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5348   bool IsCorrect = true;
5349   for (const OMPIteratorData &D : Data) {
5350     TypeSourceInfo *TInfo = nullptr;
5351     SourceLocation StartLoc;
5352     QualType DeclTy;
5353     if (!D.Type.getAsOpaquePtr()) {
5354       // OpenMP 5.0, 2.1.6 Iterators
5355       // In an iterator-specifier, if the iterator-type is not specified then
5356       // the type of that iterator is of int type.
5357       DeclTy = Context.IntTy;
5358       StartLoc = D.DeclIdentLoc;
5359     } else {
5360       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5361       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5362     }
5363 
5364     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5365                              DeclTy->containsUnexpandedParameterPack() ||
5366                              DeclTy->isInstantiationDependentType();
5367     if (!IsDeclTyDependent) {
5368       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5369         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5370         // The iterator-type must be an integral or pointer type.
5371         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5372             << DeclTy;
5373         IsCorrect = false;
5374         continue;
5375       }
5376       if (DeclTy.isConstant(Context)) {
5377         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5378         // The iterator-type must not be const qualified.
5379         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5380             << DeclTy;
5381         IsCorrect = false;
5382         continue;
5383       }
5384     }
5385 
5386     // Iterator declaration.
5387     assert(D.DeclIdent && "Identifier expected.");
5388     // Always try to create iterator declarator to avoid extra error messages
5389     // about unknown declarations use.
5390     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5391                                D.DeclIdent, DeclTy, TInfo, SC_None);
5392     VD->setImplicit();
5393     if (S) {
5394       // Check for conflicting previous declaration.
5395       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5396       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5397                             ForVisibleRedeclaration);
5398       Previous.suppressDiagnostics();
5399       LookupName(Previous, S);
5400 
5401       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5402                            /*AllowInlineNamespace=*/false);
5403       if (!Previous.empty()) {
5404         NamedDecl *Old = Previous.getRepresentativeDecl();
5405         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5406         Diag(Old->getLocation(), diag::note_previous_definition);
5407       } else {
5408         PushOnScopeChains(VD, S);
5409       }
5410     } else {
5411       CurContext->addDecl(VD);
5412     }
5413     Expr *Begin = D.Range.Begin;
5414     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5415       ExprResult BeginRes =
5416           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5417       Begin = BeginRes.get();
5418     }
5419     Expr *End = D.Range.End;
5420     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5421       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5422       End = EndRes.get();
5423     }
5424     Expr *Step = D.Range.Step;
5425     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5426       if (!Step->getType()->isIntegralType(Context)) {
5427         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5428             << Step << Step->getSourceRange();
5429         IsCorrect = false;
5430         continue;
5431       }
5432       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5433       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5434       // If the step expression of a range-specification equals zero, the
5435       // behavior is unspecified.
5436       if (Result && Result->isZero()) {
5437         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5438             << Step << Step->getSourceRange();
5439         IsCorrect = false;
5440         continue;
5441       }
5442     }
5443     if (!Begin || !End || !IsCorrect) {
5444       IsCorrect = false;
5445       continue;
5446     }
5447     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5448     IDElem.IteratorDecl = VD;
5449     IDElem.AssignmentLoc = D.AssignLoc;
5450     IDElem.Range.Begin = Begin;
5451     IDElem.Range.End = End;
5452     IDElem.Range.Step = Step;
5453     IDElem.ColonLoc = D.ColonLoc;
5454     IDElem.SecondColonLoc = D.SecColonLoc;
5455   }
5456   if (!IsCorrect) {
5457     // Invalidate all created iterator declarations if error is found.
5458     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5459       if (Decl *ID = D.IteratorDecl)
5460         ID->setInvalidDecl();
5461     }
5462     return ExprError();
5463   }
5464   SmallVector<OMPIteratorHelperData, 4> Helpers;
5465   if (!CurContext->isDependentContext()) {
5466     // Build number of ityeration for each iteration range.
5467     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5468     // ((Begini-Stepi-1-Endi) / -Stepi);
5469     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5470       // (Endi - Begini)
5471       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5472                                           D.Range.Begin);
5473       if(!Res.isUsable()) {
5474         IsCorrect = false;
5475         continue;
5476       }
5477       ExprResult St, St1;
5478       if (D.Range.Step) {
5479         St = D.Range.Step;
5480         // (Endi - Begini) + Stepi
5481         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5482         if (!Res.isUsable()) {
5483           IsCorrect = false;
5484           continue;
5485         }
5486         // (Endi - Begini) + Stepi - 1
5487         Res =
5488             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5489                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5490         if (!Res.isUsable()) {
5491           IsCorrect = false;
5492           continue;
5493         }
5494         // ((Endi - Begini) + Stepi - 1) / Stepi
5495         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5496         if (!Res.isUsable()) {
5497           IsCorrect = false;
5498           continue;
5499         }
5500         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5501         // (Begini - Endi)
5502         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5503                                              D.Range.Begin, D.Range.End);
5504         if (!Res1.isUsable()) {
5505           IsCorrect = false;
5506           continue;
5507         }
5508         // (Begini - Endi) - Stepi
5509         Res1 =
5510             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5511         if (!Res1.isUsable()) {
5512           IsCorrect = false;
5513           continue;
5514         }
5515         // (Begini - Endi) - Stepi - 1
5516         Res1 =
5517             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5518                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5519         if (!Res1.isUsable()) {
5520           IsCorrect = false;
5521           continue;
5522         }
5523         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5524         Res1 =
5525             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5526         if (!Res1.isUsable()) {
5527           IsCorrect = false;
5528           continue;
5529         }
5530         // Stepi > 0.
5531         ExprResult CmpRes =
5532             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5533                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5534         if (!CmpRes.isUsable()) {
5535           IsCorrect = false;
5536           continue;
5537         }
5538         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5539                                  Res.get(), Res1.get());
5540         if (!Res.isUsable()) {
5541           IsCorrect = false;
5542           continue;
5543         }
5544       }
5545       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5546       if (!Res.isUsable()) {
5547         IsCorrect = false;
5548         continue;
5549       }
5550 
5551       // Build counter update.
5552       // Build counter.
5553       auto *CounterVD =
5554           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5555                           D.IteratorDecl->getBeginLoc(), nullptr,
5556                           Res.get()->getType(), nullptr, SC_None);
5557       CounterVD->setImplicit();
5558       ExprResult RefRes =
5559           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5560                            D.IteratorDecl->getBeginLoc());
5561       // Build counter update.
5562       // I = Begini + counter * Stepi;
5563       ExprResult UpdateRes;
5564       if (D.Range.Step) {
5565         UpdateRes = CreateBuiltinBinOp(
5566             D.AssignmentLoc, BO_Mul,
5567             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5568       } else {
5569         UpdateRes = DefaultLvalueConversion(RefRes.get());
5570       }
5571       if (!UpdateRes.isUsable()) {
5572         IsCorrect = false;
5573         continue;
5574       }
5575       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5576                                      UpdateRes.get());
5577       if (!UpdateRes.isUsable()) {
5578         IsCorrect = false;
5579         continue;
5580       }
5581       ExprResult VDRes =
5582           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5583                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5584                            D.IteratorDecl->getBeginLoc());
5585       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5586                                      UpdateRes.get());
5587       if (!UpdateRes.isUsable()) {
5588         IsCorrect = false;
5589         continue;
5590       }
5591       UpdateRes =
5592           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5593       if (!UpdateRes.isUsable()) {
5594         IsCorrect = false;
5595         continue;
5596       }
5597       ExprResult CounterUpdateRes =
5598           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5599       if (!CounterUpdateRes.isUsable()) {
5600         IsCorrect = false;
5601         continue;
5602       }
5603       CounterUpdateRes =
5604           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5605       if (!CounterUpdateRes.isUsable()) {
5606         IsCorrect = false;
5607         continue;
5608       }
5609       OMPIteratorHelperData &HD = Helpers.emplace_back();
5610       HD.CounterVD = CounterVD;
5611       HD.Upper = Res.get();
5612       HD.Update = UpdateRes.get();
5613       HD.CounterUpdate = CounterUpdateRes.get();
5614     }
5615   } else {
5616     Helpers.assign(ID.size(), {});
5617   }
5618   if (!IsCorrect) {
5619     // Invalidate all created iterator declarations if error is found.
5620     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5621       if (Decl *ID = D.IteratorDecl)
5622         ID->setInvalidDecl();
5623     }
5624     return ExprError();
5625   }
5626   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5627                                  LLoc, RLoc, ID, Helpers);
5628 }
5629 
5630 ExprResult
5631 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5632                                       Expr *Idx, SourceLocation RLoc) {
5633   Expr *LHSExp = Base;
5634   Expr *RHSExp = Idx;
5635 
5636   ExprValueKind VK = VK_LValue;
5637   ExprObjectKind OK = OK_Ordinary;
5638 
5639   // Per C++ core issue 1213, the result is an xvalue if either operand is
5640   // a non-lvalue array, and an lvalue otherwise.
5641   if (getLangOpts().CPlusPlus11) {
5642     for (auto *Op : {LHSExp, RHSExp}) {
5643       Op = Op->IgnoreImplicit();
5644       if (Op->getType()->isArrayType() && !Op->isLValue())
5645         VK = VK_XValue;
5646     }
5647   }
5648 
5649   // Perform default conversions.
5650   if (!LHSExp->getType()->getAs<VectorType>()) {
5651     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5652     if (Result.isInvalid())
5653       return ExprError();
5654     LHSExp = Result.get();
5655   }
5656   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5657   if (Result.isInvalid())
5658     return ExprError();
5659   RHSExp = Result.get();
5660 
5661   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5662 
5663   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5664   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5665   // in the subscript position. As a result, we need to derive the array base
5666   // and index from the expression types.
5667   Expr *BaseExpr, *IndexExpr;
5668   QualType ResultType;
5669   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5670     BaseExpr = LHSExp;
5671     IndexExpr = RHSExp;
5672     ResultType =
5673         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5674   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5675     BaseExpr = LHSExp;
5676     IndexExpr = RHSExp;
5677     ResultType = PTy->getPointeeType();
5678   } else if (const ObjCObjectPointerType *PTy =
5679                LHSTy->getAs<ObjCObjectPointerType>()) {
5680     BaseExpr = LHSExp;
5681     IndexExpr = RHSExp;
5682 
5683     // Use custom logic if this should be the pseudo-object subscript
5684     // expression.
5685     if (!LangOpts.isSubscriptPointerArithmetic())
5686       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5687                                           nullptr);
5688 
5689     ResultType = PTy->getPointeeType();
5690   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5691      // Handle the uncommon case of "123[Ptr]".
5692     BaseExpr = RHSExp;
5693     IndexExpr = LHSExp;
5694     ResultType = PTy->getPointeeType();
5695   } else if (const ObjCObjectPointerType *PTy =
5696                RHSTy->getAs<ObjCObjectPointerType>()) {
5697      // Handle the uncommon case of "123[Ptr]".
5698     BaseExpr = RHSExp;
5699     IndexExpr = LHSExp;
5700     ResultType = PTy->getPointeeType();
5701     if (!LangOpts.isSubscriptPointerArithmetic()) {
5702       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5703         << ResultType << BaseExpr->getSourceRange();
5704       return ExprError();
5705     }
5706   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5707     BaseExpr = LHSExp;    // vectors: V[123]
5708     IndexExpr = RHSExp;
5709     // We apply C++ DR1213 to vector subscripting too.
5710     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5711       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5712       if (Materialized.isInvalid())
5713         return ExprError();
5714       LHSExp = Materialized.get();
5715     }
5716     VK = LHSExp->getValueKind();
5717     if (VK != VK_PRValue)
5718       OK = OK_VectorComponent;
5719 
5720     ResultType = VTy->getElementType();
5721     QualType BaseType = BaseExpr->getType();
5722     Qualifiers BaseQuals = BaseType.getQualifiers();
5723     Qualifiers MemberQuals = ResultType.getQualifiers();
5724     Qualifiers Combined = BaseQuals + MemberQuals;
5725     if (Combined != MemberQuals)
5726       ResultType = Context.getQualifiedType(ResultType, Combined);
5727   } else if (LHSTy->isBuiltinType() &&
5728              LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5729     const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5730     if (BTy->isSVEBool())
5731       return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5732                        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5733 
5734     BaseExpr = LHSExp;
5735     IndexExpr = RHSExp;
5736     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5737       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5738       if (Materialized.isInvalid())
5739         return ExprError();
5740       LHSExp = Materialized.get();
5741     }
5742     VK = LHSExp->getValueKind();
5743     if (VK != VK_PRValue)
5744       OK = OK_VectorComponent;
5745 
5746     ResultType = BTy->getSveEltType(Context);
5747 
5748     QualType BaseType = BaseExpr->getType();
5749     Qualifiers BaseQuals = BaseType.getQualifiers();
5750     Qualifiers MemberQuals = ResultType.getQualifiers();
5751     Qualifiers Combined = BaseQuals + MemberQuals;
5752     if (Combined != MemberQuals)
5753       ResultType = Context.getQualifiedType(ResultType, Combined);
5754   } else if (LHSTy->isArrayType()) {
5755     // If we see an array that wasn't promoted by
5756     // DefaultFunctionArrayLvalueConversion, it must be an array that
5757     // wasn't promoted because of the C90 rule that doesn't
5758     // allow promoting non-lvalue arrays.  Warn, then
5759     // force the promotion here.
5760     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5761         << LHSExp->getSourceRange();
5762     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5763                                CK_ArrayToPointerDecay).get();
5764     LHSTy = LHSExp->getType();
5765 
5766     BaseExpr = LHSExp;
5767     IndexExpr = RHSExp;
5768     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5769   } else if (RHSTy->isArrayType()) {
5770     // Same as previous, except for 123[f().a] case
5771     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5772         << RHSExp->getSourceRange();
5773     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5774                                CK_ArrayToPointerDecay).get();
5775     RHSTy = RHSExp->getType();
5776 
5777     BaseExpr = RHSExp;
5778     IndexExpr = LHSExp;
5779     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5780   } else {
5781     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5782        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5783   }
5784   // C99 6.5.2.1p1
5785   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5786     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5787                      << IndexExpr->getSourceRange());
5788 
5789   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5790        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5791          && !IndexExpr->isTypeDependent())
5792     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5793 
5794   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5795   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5796   // type. Note that Functions are not objects, and that (in C99 parlance)
5797   // incomplete types are not object types.
5798   if (ResultType->isFunctionType()) {
5799     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5800         << ResultType << BaseExpr->getSourceRange();
5801     return ExprError();
5802   }
5803 
5804   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5805     // GNU extension: subscripting on pointer to void
5806     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5807       << BaseExpr->getSourceRange();
5808 
5809     // C forbids expressions of unqualified void type from being l-values.
5810     // See IsCForbiddenLValueType.
5811     if (!ResultType.hasQualifiers())
5812       VK = VK_PRValue;
5813   } else if (!ResultType->isDependentType() &&
5814              RequireCompleteSizedType(
5815                  LLoc, ResultType,
5816                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5817     return ExprError();
5818 
5819   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5820          !ResultType.isCForbiddenLValueType());
5821 
5822   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5823       FunctionScopes.size() > 1) {
5824     if (auto *TT =
5825             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5826       for (auto I = FunctionScopes.rbegin(),
5827                 E = std::prev(FunctionScopes.rend());
5828            I != E; ++I) {
5829         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5830         if (CSI == nullptr)
5831           break;
5832         DeclContext *DC = nullptr;
5833         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5834           DC = LSI->CallOperator;
5835         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5836           DC = CRSI->TheCapturedDecl;
5837         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5838           DC = BSI->TheDecl;
5839         if (DC) {
5840           if (DC->containsDecl(TT->getDecl()))
5841             break;
5842           captureVariablyModifiedType(
5843               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5844         }
5845       }
5846     }
5847   }
5848 
5849   return new (Context)
5850       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5851 }
5852 
5853 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5854                                   ParmVarDecl *Param) {
5855   if (Param->hasUnparsedDefaultArg()) {
5856     // If we've already cleared out the location for the default argument,
5857     // that means we're parsing it right now.
5858     if (!UnparsedDefaultArgLocs.count(Param)) {
5859       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5860       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5861       Param->setInvalidDecl();
5862       return true;
5863     }
5864 
5865     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5866         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5867     Diag(UnparsedDefaultArgLocs[Param],
5868          diag::note_default_argument_declared_here);
5869     return true;
5870   }
5871 
5872   if (Param->hasUninstantiatedDefaultArg() &&
5873       InstantiateDefaultArgument(CallLoc, FD, Param))
5874     return true;
5875 
5876   assert(Param->hasInit() && "default argument but no initializer?");
5877 
5878   // If the default expression creates temporaries, we need to
5879   // push them to the current stack of expression temporaries so they'll
5880   // be properly destroyed.
5881   // FIXME: We should really be rebuilding the default argument with new
5882   // bound temporaries; see the comment in PR5810.
5883   // We don't need to do that with block decls, though, because
5884   // blocks in default argument expression can never capture anything.
5885   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5886     // Set the "needs cleanups" bit regardless of whether there are
5887     // any explicit objects.
5888     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5889 
5890     // Append all the objects to the cleanup list.  Right now, this
5891     // should always be a no-op, because blocks in default argument
5892     // expressions should never be able to capture anything.
5893     assert(!Init->getNumObjects() &&
5894            "default argument expression has capturing blocks?");
5895   }
5896 
5897   // We already type-checked the argument, so we know it works.
5898   // Just mark all of the declarations in this potentially-evaluated expression
5899   // as being "referenced".
5900   EnterExpressionEvaluationContext EvalContext(
5901       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5902   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5903                                    /*SkipLocalVariables=*/true);
5904   return false;
5905 }
5906 
5907 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5908                                         FunctionDecl *FD, ParmVarDecl *Param) {
5909   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5910   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5911     return ExprError();
5912   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5913 }
5914 
5915 Sema::VariadicCallType
5916 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5917                           Expr *Fn) {
5918   if (Proto && Proto->isVariadic()) {
5919     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5920       return VariadicConstructor;
5921     else if (Fn && Fn->getType()->isBlockPointerType())
5922       return VariadicBlock;
5923     else if (FDecl) {
5924       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5925         if (Method->isInstance())
5926           return VariadicMethod;
5927     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5928       return VariadicMethod;
5929     return VariadicFunction;
5930   }
5931   return VariadicDoesNotApply;
5932 }
5933 
5934 namespace {
5935 class FunctionCallCCC final : public FunctionCallFilterCCC {
5936 public:
5937   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5938                   unsigned NumArgs, MemberExpr *ME)
5939       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5940         FunctionName(FuncName) {}
5941 
5942   bool ValidateCandidate(const TypoCorrection &candidate) override {
5943     if (!candidate.getCorrectionSpecifier() ||
5944         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5945       return false;
5946     }
5947 
5948     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5949   }
5950 
5951   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5952     return std::make_unique<FunctionCallCCC>(*this);
5953   }
5954 
5955 private:
5956   const IdentifierInfo *const FunctionName;
5957 };
5958 }
5959 
5960 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5961                                                FunctionDecl *FDecl,
5962                                                ArrayRef<Expr *> Args) {
5963   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5964   DeclarationName FuncName = FDecl->getDeclName();
5965   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5966 
5967   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5968   if (TypoCorrection Corrected = S.CorrectTypo(
5969           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5970           S.getScopeForContext(S.CurContext), nullptr, CCC,
5971           Sema::CTK_ErrorRecovery)) {
5972     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5973       if (Corrected.isOverloaded()) {
5974         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5975         OverloadCandidateSet::iterator Best;
5976         for (NamedDecl *CD : Corrected) {
5977           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5978             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5979                                    OCS);
5980         }
5981         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5982         case OR_Success:
5983           ND = Best->FoundDecl;
5984           Corrected.setCorrectionDecl(ND);
5985           break;
5986         default:
5987           break;
5988         }
5989       }
5990       ND = ND->getUnderlyingDecl();
5991       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5992         return Corrected;
5993     }
5994   }
5995   return TypoCorrection();
5996 }
5997 
5998 /// ConvertArgumentsForCall - Converts the arguments specified in
5999 /// Args/NumArgs to the parameter types of the function FDecl with
6000 /// function prototype Proto. Call is the call expression itself, and
6001 /// Fn is the function expression. For a C++ member function, this
6002 /// routine does not attempt to convert the object argument. Returns
6003 /// true if the call is ill-formed.
6004 bool
6005 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6006                               FunctionDecl *FDecl,
6007                               const FunctionProtoType *Proto,
6008                               ArrayRef<Expr *> Args,
6009                               SourceLocation RParenLoc,
6010                               bool IsExecConfig) {
6011   // Bail out early if calling a builtin with custom typechecking.
6012   if (FDecl)
6013     if (unsigned ID = FDecl->getBuiltinID())
6014       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6015         return false;
6016 
6017   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6018   // assignment, to the types of the corresponding parameter, ...
6019   unsigned NumParams = Proto->getNumParams();
6020   bool Invalid = false;
6021   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6022   unsigned FnKind = Fn->getType()->isBlockPointerType()
6023                        ? 1 /* block */
6024                        : (IsExecConfig ? 3 /* kernel function (exec config) */
6025                                        : 0 /* function */);
6026 
6027   // If too few arguments are available (and we don't have default
6028   // arguments for the remaining parameters), don't make the call.
6029   if (Args.size() < NumParams) {
6030     if (Args.size() < MinArgs) {
6031       TypoCorrection TC;
6032       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6033         unsigned diag_id =
6034             MinArgs == NumParams && !Proto->isVariadic()
6035                 ? diag::err_typecheck_call_too_few_args_suggest
6036                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6037         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6038                                         << static_cast<unsigned>(Args.size())
6039                                         << TC.getCorrectionRange());
6040       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6041         Diag(RParenLoc,
6042              MinArgs == NumParams && !Proto->isVariadic()
6043                  ? diag::err_typecheck_call_too_few_args_one
6044                  : diag::err_typecheck_call_too_few_args_at_least_one)
6045             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6046       else
6047         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6048                             ? diag::err_typecheck_call_too_few_args
6049                             : diag::err_typecheck_call_too_few_args_at_least)
6050             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6051             << Fn->getSourceRange();
6052 
6053       // Emit the location of the prototype.
6054       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6055         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6056 
6057       return true;
6058     }
6059     // We reserve space for the default arguments when we create
6060     // the call expression, before calling ConvertArgumentsForCall.
6061     assert((Call->getNumArgs() == NumParams) &&
6062            "We should have reserved space for the default arguments before!");
6063   }
6064 
6065   // If too many are passed and not variadic, error on the extras and drop
6066   // them.
6067   if (Args.size() > NumParams) {
6068     if (!Proto->isVariadic()) {
6069       TypoCorrection TC;
6070       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6071         unsigned diag_id =
6072             MinArgs == NumParams && !Proto->isVariadic()
6073                 ? diag::err_typecheck_call_too_many_args_suggest
6074                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6075         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6076                                         << static_cast<unsigned>(Args.size())
6077                                         << TC.getCorrectionRange());
6078       } else if (NumParams == 1 && FDecl &&
6079                  FDecl->getParamDecl(0)->getDeclName())
6080         Diag(Args[NumParams]->getBeginLoc(),
6081              MinArgs == NumParams
6082                  ? diag::err_typecheck_call_too_many_args_one
6083                  : diag::err_typecheck_call_too_many_args_at_most_one)
6084             << FnKind << FDecl->getParamDecl(0)
6085             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6086             << SourceRange(Args[NumParams]->getBeginLoc(),
6087                            Args.back()->getEndLoc());
6088       else
6089         Diag(Args[NumParams]->getBeginLoc(),
6090              MinArgs == NumParams
6091                  ? diag::err_typecheck_call_too_many_args
6092                  : diag::err_typecheck_call_too_many_args_at_most)
6093             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6094             << Fn->getSourceRange()
6095             << SourceRange(Args[NumParams]->getBeginLoc(),
6096                            Args.back()->getEndLoc());
6097 
6098       // Emit the location of the prototype.
6099       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6100         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6101 
6102       // This deletes the extra arguments.
6103       Call->shrinkNumArgs(NumParams);
6104       return true;
6105     }
6106   }
6107   SmallVector<Expr *, 8> AllArgs;
6108   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6109 
6110   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6111                                    AllArgs, CallType);
6112   if (Invalid)
6113     return true;
6114   unsigned TotalNumArgs = AllArgs.size();
6115   for (unsigned i = 0; i < TotalNumArgs; ++i)
6116     Call->setArg(i, AllArgs[i]);
6117 
6118   Call->computeDependence();
6119   return false;
6120 }
6121 
6122 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6123                                   const FunctionProtoType *Proto,
6124                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6125                                   SmallVectorImpl<Expr *> &AllArgs,
6126                                   VariadicCallType CallType, bool AllowExplicit,
6127                                   bool IsListInitialization) {
6128   unsigned NumParams = Proto->getNumParams();
6129   bool Invalid = false;
6130   size_t ArgIx = 0;
6131   // Continue to check argument types (even if we have too few/many args).
6132   for (unsigned i = FirstParam; i < NumParams; i++) {
6133     QualType ProtoArgType = Proto->getParamType(i);
6134 
6135     Expr *Arg;
6136     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6137     if (ArgIx < Args.size()) {
6138       Arg = Args[ArgIx++];
6139 
6140       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6141                               diag::err_call_incomplete_argument, Arg))
6142         return true;
6143 
6144       // Strip the unbridged-cast placeholder expression off, if applicable.
6145       bool CFAudited = false;
6146       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6147           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6148           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6149         Arg = stripARCUnbridgedCast(Arg);
6150       else if (getLangOpts().ObjCAutoRefCount &&
6151                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6152                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6153         CFAudited = true;
6154 
6155       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6156           ProtoArgType->isBlockPointerType())
6157         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6158           BE->getBlockDecl()->setDoesNotEscape();
6159 
6160       InitializedEntity Entity =
6161           Param ? InitializedEntity::InitializeParameter(Context, Param,
6162                                                          ProtoArgType)
6163                 : InitializedEntity::InitializeParameter(
6164                       Context, ProtoArgType, Proto->isParamConsumed(i));
6165 
6166       // Remember that parameter belongs to a CF audited API.
6167       if (CFAudited)
6168         Entity.setParameterCFAudited();
6169 
6170       ExprResult ArgE = PerformCopyInitialization(
6171           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6172       if (ArgE.isInvalid())
6173         return true;
6174 
6175       Arg = ArgE.getAs<Expr>();
6176     } else {
6177       assert(Param && "can't use default arguments without a known callee");
6178 
6179       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6180       if (ArgExpr.isInvalid())
6181         return true;
6182 
6183       Arg = ArgExpr.getAs<Expr>();
6184     }
6185 
6186     // Check for array bounds violations for each argument to the call. This
6187     // check only triggers warnings when the argument isn't a more complex Expr
6188     // with its own checking, such as a BinaryOperator.
6189     CheckArrayAccess(Arg);
6190 
6191     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6192     CheckStaticArrayArgument(CallLoc, Param, Arg);
6193 
6194     AllArgs.push_back(Arg);
6195   }
6196 
6197   // If this is a variadic call, handle args passed through "...".
6198   if (CallType != VariadicDoesNotApply) {
6199     // Assume that extern "C" functions with variadic arguments that
6200     // return __unknown_anytype aren't *really* variadic.
6201     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6202         FDecl->isExternC()) {
6203       for (Expr *A : Args.slice(ArgIx)) {
6204         QualType paramType; // ignored
6205         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6206         Invalid |= arg.isInvalid();
6207         AllArgs.push_back(arg.get());
6208       }
6209 
6210     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6211     } else {
6212       for (Expr *A : Args.slice(ArgIx)) {
6213         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6214         Invalid |= Arg.isInvalid();
6215         AllArgs.push_back(Arg.get());
6216       }
6217     }
6218 
6219     // Check for array bounds violations.
6220     for (Expr *A : Args.slice(ArgIx))
6221       CheckArrayAccess(A);
6222   }
6223   return Invalid;
6224 }
6225 
6226 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6227   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6228   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6229     TL = DTL.getOriginalLoc();
6230   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6231     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6232       << ATL.getLocalSourceRange();
6233 }
6234 
6235 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6236 /// array parameter, check that it is non-null, and that if it is formed by
6237 /// array-to-pointer decay, the underlying array is sufficiently large.
6238 ///
6239 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6240 /// array type derivation, then for each call to the function, the value of the
6241 /// corresponding actual argument shall provide access to the first element of
6242 /// an array with at least as many elements as specified by the size expression.
6243 void
6244 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6245                                ParmVarDecl *Param,
6246                                const Expr *ArgExpr) {
6247   // Static array parameters are not supported in C++.
6248   if (!Param || getLangOpts().CPlusPlus)
6249     return;
6250 
6251   QualType OrigTy = Param->getOriginalType();
6252 
6253   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6254   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6255     return;
6256 
6257   if (ArgExpr->isNullPointerConstant(Context,
6258                                      Expr::NPC_NeverValueDependent)) {
6259     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6260     DiagnoseCalleeStaticArrayParam(*this, Param);
6261     return;
6262   }
6263 
6264   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6265   if (!CAT)
6266     return;
6267 
6268   const ConstantArrayType *ArgCAT =
6269     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6270   if (!ArgCAT)
6271     return;
6272 
6273   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6274                                              ArgCAT->getElementType())) {
6275     if (ArgCAT->getSize().ult(CAT->getSize())) {
6276       Diag(CallLoc, diag::warn_static_array_too_small)
6277           << ArgExpr->getSourceRange()
6278           << (unsigned)ArgCAT->getSize().getZExtValue()
6279           << (unsigned)CAT->getSize().getZExtValue() << 0;
6280       DiagnoseCalleeStaticArrayParam(*this, Param);
6281     }
6282     return;
6283   }
6284 
6285   Optional<CharUnits> ArgSize =
6286       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6287   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6288   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6289     Diag(CallLoc, diag::warn_static_array_too_small)
6290         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6291         << (unsigned)ParmSize->getQuantity() << 1;
6292     DiagnoseCalleeStaticArrayParam(*this, Param);
6293   }
6294 }
6295 
6296 /// Given a function expression of unknown-any type, try to rebuild it
6297 /// to have a function type.
6298 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6299 
6300 /// Is the given type a placeholder that we need to lower out
6301 /// immediately during argument processing?
6302 static bool isPlaceholderToRemoveAsArg(QualType type) {
6303   // Placeholders are never sugared.
6304   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6305   if (!placeholder) return false;
6306 
6307   switch (placeholder->getKind()) {
6308   // Ignore all the non-placeholder types.
6309 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6310   case BuiltinType::Id:
6311 #include "clang/Basic/OpenCLImageTypes.def"
6312 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6313   case BuiltinType::Id:
6314 #include "clang/Basic/OpenCLExtensionTypes.def"
6315   // In practice we'll never use this, since all SVE types are sugared
6316   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6317 #define SVE_TYPE(Name, Id, SingletonId) \
6318   case BuiltinType::Id:
6319 #include "clang/Basic/AArch64SVEACLETypes.def"
6320 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6321   case BuiltinType::Id:
6322 #include "clang/Basic/PPCTypes.def"
6323 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6324 #include "clang/Basic/RISCVVTypes.def"
6325 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6326 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6327 #include "clang/AST/BuiltinTypes.def"
6328     return false;
6329 
6330   // We cannot lower out overload sets; they might validly be resolved
6331   // by the call machinery.
6332   case BuiltinType::Overload:
6333     return false;
6334 
6335   // Unbridged casts in ARC can be handled in some call positions and
6336   // should be left in place.
6337   case BuiltinType::ARCUnbridgedCast:
6338     return false;
6339 
6340   // Pseudo-objects should be converted as soon as possible.
6341   case BuiltinType::PseudoObject:
6342     return true;
6343 
6344   // The debugger mode could theoretically but currently does not try
6345   // to resolve unknown-typed arguments based on known parameter types.
6346   case BuiltinType::UnknownAny:
6347     return true;
6348 
6349   // These are always invalid as call arguments and should be reported.
6350   case BuiltinType::BoundMember:
6351   case BuiltinType::BuiltinFn:
6352   case BuiltinType::IncompleteMatrixIdx:
6353   case BuiltinType::OMPArraySection:
6354   case BuiltinType::OMPArrayShaping:
6355   case BuiltinType::OMPIterator:
6356     return true;
6357 
6358   }
6359   llvm_unreachable("bad builtin type kind");
6360 }
6361 
6362 /// Check an argument list for placeholders that we won't try to
6363 /// handle later.
6364 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6365   // Apply this processing to all the arguments at once instead of
6366   // dying at the first failure.
6367   bool hasInvalid = false;
6368   for (size_t i = 0, e = args.size(); i != e; i++) {
6369     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6370       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6371       if (result.isInvalid()) hasInvalid = true;
6372       else args[i] = result.get();
6373     }
6374   }
6375   return hasInvalid;
6376 }
6377 
6378 /// If a builtin function has a pointer argument with no explicit address
6379 /// space, then it should be able to accept a pointer to any address
6380 /// space as input.  In order to do this, we need to replace the
6381 /// standard builtin declaration with one that uses the same address space
6382 /// as the call.
6383 ///
6384 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6385 ///                  it does not contain any pointer arguments without
6386 ///                  an address space qualifer.  Otherwise the rewritten
6387 ///                  FunctionDecl is returned.
6388 /// TODO: Handle pointer return types.
6389 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6390                                                 FunctionDecl *FDecl,
6391                                                 MultiExprArg ArgExprs) {
6392 
6393   QualType DeclType = FDecl->getType();
6394   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6395 
6396   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6397       ArgExprs.size() < FT->getNumParams())
6398     return nullptr;
6399 
6400   bool NeedsNewDecl = false;
6401   unsigned i = 0;
6402   SmallVector<QualType, 8> OverloadParams;
6403 
6404   for (QualType ParamType : FT->param_types()) {
6405 
6406     // Convert array arguments to pointer to simplify type lookup.
6407     ExprResult ArgRes =
6408         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6409     if (ArgRes.isInvalid())
6410       return nullptr;
6411     Expr *Arg = ArgRes.get();
6412     QualType ArgType = Arg->getType();
6413     if (!ParamType->isPointerType() ||
6414         ParamType.hasAddressSpace() ||
6415         !ArgType->isPointerType() ||
6416         !ArgType->getPointeeType().hasAddressSpace()) {
6417       OverloadParams.push_back(ParamType);
6418       continue;
6419     }
6420 
6421     QualType PointeeType = ParamType->getPointeeType();
6422     if (PointeeType.hasAddressSpace())
6423       continue;
6424 
6425     NeedsNewDecl = true;
6426     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6427 
6428     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6429     OverloadParams.push_back(Context.getPointerType(PointeeType));
6430   }
6431 
6432   if (!NeedsNewDecl)
6433     return nullptr;
6434 
6435   FunctionProtoType::ExtProtoInfo EPI;
6436   EPI.Variadic = FT->isVariadic();
6437   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6438                                                 OverloadParams, EPI);
6439   DeclContext *Parent = FDecl->getParent();
6440   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6441       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6442       FDecl->getIdentifier(), OverloadTy,
6443       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6444       false,
6445       /*hasPrototype=*/true);
6446   SmallVector<ParmVarDecl*, 16> Params;
6447   FT = cast<FunctionProtoType>(OverloadTy);
6448   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6449     QualType ParamType = FT->getParamType(i);
6450     ParmVarDecl *Parm =
6451         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6452                                 SourceLocation(), nullptr, ParamType,
6453                                 /*TInfo=*/nullptr, SC_None, nullptr);
6454     Parm->setScopeInfo(0, i);
6455     Params.push_back(Parm);
6456   }
6457   OverloadDecl->setParams(Params);
6458   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6459   return OverloadDecl;
6460 }
6461 
6462 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6463                                     FunctionDecl *Callee,
6464                                     MultiExprArg ArgExprs) {
6465   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6466   // similar attributes) really don't like it when functions are called with an
6467   // invalid number of args.
6468   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6469                          /*PartialOverloading=*/false) &&
6470       !Callee->isVariadic())
6471     return;
6472   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6473     return;
6474 
6475   if (const EnableIfAttr *Attr =
6476           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6477     S.Diag(Fn->getBeginLoc(),
6478            isa<CXXMethodDecl>(Callee)
6479                ? diag::err_ovl_no_viable_member_function_in_call
6480                : diag::err_ovl_no_viable_function_in_call)
6481         << Callee << Callee->getSourceRange();
6482     S.Diag(Callee->getLocation(),
6483            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6484         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6485     return;
6486   }
6487 }
6488 
6489 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6490     const UnresolvedMemberExpr *const UME, Sema &S) {
6491 
6492   const auto GetFunctionLevelDCIfCXXClass =
6493       [](Sema &S) -> const CXXRecordDecl * {
6494     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6495     if (!DC || !DC->getParent())
6496       return nullptr;
6497 
6498     // If the call to some member function was made from within a member
6499     // function body 'M' return return 'M's parent.
6500     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6501       return MD->getParent()->getCanonicalDecl();
6502     // else the call was made from within a default member initializer of a
6503     // class, so return the class.
6504     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6505       return RD->getCanonicalDecl();
6506     return nullptr;
6507   };
6508   // If our DeclContext is neither a member function nor a class (in the
6509   // case of a lambda in a default member initializer), we can't have an
6510   // enclosing 'this'.
6511 
6512   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6513   if (!CurParentClass)
6514     return false;
6515 
6516   // The naming class for implicit member functions call is the class in which
6517   // name lookup starts.
6518   const CXXRecordDecl *const NamingClass =
6519       UME->getNamingClass()->getCanonicalDecl();
6520   assert(NamingClass && "Must have naming class even for implicit access");
6521 
6522   // If the unresolved member functions were found in a 'naming class' that is
6523   // related (either the same or derived from) to the class that contains the
6524   // member function that itself contained the implicit member access.
6525 
6526   return CurParentClass == NamingClass ||
6527          CurParentClass->isDerivedFrom(NamingClass);
6528 }
6529 
6530 static void
6531 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6532     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6533 
6534   if (!UME)
6535     return;
6536 
6537   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6538   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6539   // already been captured, or if this is an implicit member function call (if
6540   // it isn't, an attempt to capture 'this' should already have been made).
6541   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6542       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6543     return;
6544 
6545   // Check if the naming class in which the unresolved members were found is
6546   // related (same as or is a base of) to the enclosing class.
6547 
6548   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6549     return;
6550 
6551 
6552   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6553   // If the enclosing function is not dependent, then this lambda is
6554   // capture ready, so if we can capture this, do so.
6555   if (!EnclosingFunctionCtx->isDependentContext()) {
6556     // If the current lambda and all enclosing lambdas can capture 'this' -
6557     // then go ahead and capture 'this' (since our unresolved overload set
6558     // contains at least one non-static member function).
6559     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6560       S.CheckCXXThisCapture(CallLoc);
6561   } else if (S.CurContext->isDependentContext()) {
6562     // ... since this is an implicit member reference, that might potentially
6563     // involve a 'this' capture, mark 'this' for potential capture in
6564     // enclosing lambdas.
6565     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6566       CurLSI->addPotentialThisCapture(CallLoc);
6567   }
6568 }
6569 
6570 // Once a call is fully resolved, warn for unqualified calls to specific
6571 // C++ standard functions, like move and forward.
6572 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6573   // We are only checking unary move and forward so exit early here.
6574   if (Call->getNumArgs() != 1)
6575     return;
6576 
6577   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6578   if (!E || isa<UnresolvedLookupExpr>(E))
6579     return;
6580   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6581   if (!DRE || !DRE->getLocation().isValid())
6582     return;
6583 
6584   if (DRE->getQualifier())
6585     return;
6586 
6587   const FunctionDecl *FD = Call->getDirectCallee();
6588   if (!FD)
6589     return;
6590 
6591   // Only warn for some functions deemed more frequent or problematic.
6592   unsigned BuiltinID = FD->getBuiltinID();
6593   if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6594     return;
6595 
6596   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6597       << FD->getQualifiedNameAsString()
6598       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6599 }
6600 
6601 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6602                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6603                                Expr *ExecConfig) {
6604   ExprResult Call =
6605       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6606                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6607   if (Call.isInvalid())
6608     return Call;
6609 
6610   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6611   // language modes.
6612   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6613     if (ULE->hasExplicitTemplateArgs() &&
6614         ULE->decls_begin() == ULE->decls_end()) {
6615       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6616                                  ? diag::warn_cxx17_compat_adl_only_template_id
6617                                  : diag::ext_adl_only_template_id)
6618           << ULE->getName();
6619     }
6620   }
6621 
6622   if (LangOpts.OpenMP)
6623     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6624                            ExecConfig);
6625   if (LangOpts.CPlusPlus) {
6626     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6627     if (CE)
6628       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6629   }
6630   return Call;
6631 }
6632 
6633 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6634 /// This provides the location of the left/right parens and a list of comma
6635 /// locations.
6636 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6637                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6638                                Expr *ExecConfig, bool IsExecConfig,
6639                                bool AllowRecovery) {
6640   // Since this might be a postfix expression, get rid of ParenListExprs.
6641   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6642   if (Result.isInvalid()) return ExprError();
6643   Fn = Result.get();
6644 
6645   if (checkArgsForPlaceholders(*this, ArgExprs))
6646     return ExprError();
6647 
6648   if (getLangOpts().CPlusPlus) {
6649     // If this is a pseudo-destructor expression, build the call immediately.
6650     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6651       if (!ArgExprs.empty()) {
6652         // Pseudo-destructor calls should not have any arguments.
6653         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6654             << FixItHint::CreateRemoval(
6655                    SourceRange(ArgExprs.front()->getBeginLoc(),
6656                                ArgExprs.back()->getEndLoc()));
6657       }
6658 
6659       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6660                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6661     }
6662     if (Fn->getType() == Context.PseudoObjectTy) {
6663       ExprResult result = CheckPlaceholderExpr(Fn);
6664       if (result.isInvalid()) return ExprError();
6665       Fn = result.get();
6666     }
6667 
6668     // Determine whether this is a dependent call inside a C++ template,
6669     // in which case we won't do any semantic analysis now.
6670     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6671       if (ExecConfig) {
6672         return CUDAKernelCallExpr::Create(Context, Fn,
6673                                           cast<CallExpr>(ExecConfig), ArgExprs,
6674                                           Context.DependentTy, VK_PRValue,
6675                                           RParenLoc, CurFPFeatureOverrides());
6676       } else {
6677 
6678         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6679             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6680             Fn->getBeginLoc());
6681 
6682         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6683                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6684       }
6685     }
6686 
6687     // Determine whether this is a call to an object (C++ [over.call.object]).
6688     if (Fn->getType()->isRecordType())
6689       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6690                                           RParenLoc);
6691 
6692     if (Fn->getType() == Context.UnknownAnyTy) {
6693       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6694       if (result.isInvalid()) return ExprError();
6695       Fn = result.get();
6696     }
6697 
6698     if (Fn->getType() == Context.BoundMemberTy) {
6699       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6700                                        RParenLoc, ExecConfig, IsExecConfig,
6701                                        AllowRecovery);
6702     }
6703   }
6704 
6705   // Check for overloaded calls.  This can happen even in C due to extensions.
6706   if (Fn->getType() == Context.OverloadTy) {
6707     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6708 
6709     // We aren't supposed to apply this logic if there's an '&' involved.
6710     if (!find.HasFormOfMemberPointer) {
6711       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6712         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6713                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6714       OverloadExpr *ovl = find.Expression;
6715       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6716         return BuildOverloadedCallExpr(
6717             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6718             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6719       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6720                                        RParenLoc, ExecConfig, IsExecConfig,
6721                                        AllowRecovery);
6722     }
6723   }
6724 
6725   // If we're directly calling a function, get the appropriate declaration.
6726   if (Fn->getType() == Context.UnknownAnyTy) {
6727     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6728     if (result.isInvalid()) return ExprError();
6729     Fn = result.get();
6730   }
6731 
6732   Expr *NakedFn = Fn->IgnoreParens();
6733 
6734   bool CallingNDeclIndirectly = false;
6735   NamedDecl *NDecl = nullptr;
6736   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6737     if (UnOp->getOpcode() == UO_AddrOf) {
6738       CallingNDeclIndirectly = true;
6739       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6740     }
6741   }
6742 
6743   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6744     NDecl = DRE->getDecl();
6745 
6746     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6747     if (FDecl && FDecl->getBuiltinID()) {
6748       // Rewrite the function decl for this builtin by replacing parameters
6749       // with no explicit address space with the address space of the arguments
6750       // in ArgExprs.
6751       if ((FDecl =
6752                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6753         NDecl = FDecl;
6754         Fn = DeclRefExpr::Create(
6755             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6756             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6757             nullptr, DRE->isNonOdrUse());
6758       }
6759     }
6760   } else if (isa<MemberExpr>(NakedFn))
6761     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6762 
6763   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6764     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6765                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6766       return ExprError();
6767 
6768     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6769 
6770     // If this expression is a call to a builtin function in HIP device
6771     // compilation, allow a pointer-type argument to default address space to be
6772     // passed as a pointer-type parameter to a non-default address space.
6773     // If Arg is declared in the default address space and Param is declared
6774     // in a non-default address space, perform an implicit address space cast to
6775     // the parameter type.
6776     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6777         FD->getBuiltinID()) {
6778       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6779         ParmVarDecl *Param = FD->getParamDecl(Idx);
6780         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6781             !ArgExprs[Idx]->getType()->isPointerType())
6782           continue;
6783 
6784         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6785         auto ArgTy = ArgExprs[Idx]->getType();
6786         auto ArgPtTy = ArgTy->getPointeeType();
6787         auto ArgAS = ArgPtTy.getAddressSpace();
6788 
6789         // Add address space cast if target address spaces are different
6790         bool NeedImplicitASC =
6791           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6792           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6793                                               // or from specific AS which has target AS matching that of Param.
6794           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6795         if (!NeedImplicitASC)
6796           continue;
6797 
6798         // First, ensure that the Arg is an RValue.
6799         if (ArgExprs[Idx]->isGLValue()) {
6800           ArgExprs[Idx] = ImplicitCastExpr::Create(
6801               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6802               nullptr, VK_PRValue, FPOptionsOverride());
6803         }
6804 
6805         // Construct a new arg type with address space of Param
6806         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6807         ArgPtQuals.setAddressSpace(ParamAS);
6808         auto NewArgPtTy =
6809             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6810         auto NewArgTy =
6811             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6812                                      ArgTy.getQualifiers());
6813 
6814         // Finally perform an implicit address space cast
6815         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6816                                           CK_AddressSpaceConversion)
6817                             .get();
6818       }
6819     }
6820   }
6821 
6822   if (Context.isDependenceAllowed() &&
6823       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6824     assert(!getLangOpts().CPlusPlus);
6825     assert((Fn->containsErrors() ||
6826             llvm::any_of(ArgExprs,
6827                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6828            "should only occur in error-recovery path.");
6829     QualType ReturnType =
6830         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6831             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6832             : Context.DependentTy;
6833     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6834                             Expr::getValueKindForType(ReturnType), RParenLoc,
6835                             CurFPFeatureOverrides());
6836   }
6837   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6838                                ExecConfig, IsExecConfig);
6839 }
6840 
6841 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6842 //  with the specified CallArgs
6843 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6844                                  MultiExprArg CallArgs) {
6845   StringRef Name = Context.BuiltinInfo.getName(Id);
6846   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6847                  Sema::LookupOrdinaryName);
6848   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6849 
6850   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6851   assert(BuiltInDecl && "failed to find builtin declaration");
6852 
6853   ExprResult DeclRef =
6854       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6855   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6856 
6857   ExprResult Call =
6858       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6859 
6860   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6861   return Call.get();
6862 }
6863 
6864 /// Parse a __builtin_astype expression.
6865 ///
6866 /// __builtin_astype( value, dst type )
6867 ///
6868 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6869                                  SourceLocation BuiltinLoc,
6870                                  SourceLocation RParenLoc) {
6871   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6872   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6873 }
6874 
6875 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6876 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6877                                  SourceLocation BuiltinLoc,
6878                                  SourceLocation RParenLoc) {
6879   ExprValueKind VK = VK_PRValue;
6880   ExprObjectKind OK = OK_Ordinary;
6881   QualType SrcTy = E->getType();
6882   if (!SrcTy->isDependentType() &&
6883       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6884     return ExprError(
6885         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6886         << DestTy << SrcTy << E->getSourceRange());
6887   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6888 }
6889 
6890 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6891 /// provided arguments.
6892 ///
6893 /// __builtin_convertvector( value, dst type )
6894 ///
6895 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6896                                         SourceLocation BuiltinLoc,
6897                                         SourceLocation RParenLoc) {
6898   TypeSourceInfo *TInfo;
6899   GetTypeFromParser(ParsedDestTy, &TInfo);
6900   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6901 }
6902 
6903 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6904 /// i.e. an expression not of \p OverloadTy.  The expression should
6905 /// unary-convert to an expression of function-pointer or
6906 /// block-pointer type.
6907 ///
6908 /// \param NDecl the declaration being called, if available
6909 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6910                                        SourceLocation LParenLoc,
6911                                        ArrayRef<Expr *> Args,
6912                                        SourceLocation RParenLoc, Expr *Config,
6913                                        bool IsExecConfig, ADLCallKind UsesADL) {
6914   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6915   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6916 
6917   // Functions with 'interrupt' attribute cannot be called directly.
6918   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6919     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6920     return ExprError();
6921   }
6922 
6923   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6924   // so there's some risk when calling out to non-interrupt handler functions
6925   // that the callee might not preserve them. This is easy to diagnose here,
6926   // but can be very challenging to debug.
6927   // Likewise, X86 interrupt handlers may only call routines with attribute
6928   // no_caller_saved_registers since there is no efficient way to
6929   // save and restore the non-GPR state.
6930   if (auto *Caller = getCurFunctionDecl()) {
6931     if (Caller->hasAttr<ARMInterruptAttr>()) {
6932       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6933       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6934         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6935         if (FDecl)
6936           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6937       }
6938     }
6939     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6940         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6941       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6942       if (FDecl)
6943         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6944     }
6945   }
6946 
6947   // Promote the function operand.
6948   // We special-case function promotion here because we only allow promoting
6949   // builtin functions to function pointers in the callee of a call.
6950   ExprResult Result;
6951   QualType ResultTy;
6952   if (BuiltinID &&
6953       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6954     // Extract the return type from the (builtin) function pointer type.
6955     // FIXME Several builtins still have setType in
6956     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6957     // Builtins.def to ensure they are correct before removing setType calls.
6958     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6959     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6960     ResultTy = FDecl->getCallResultType();
6961   } else {
6962     Result = CallExprUnaryConversions(Fn);
6963     ResultTy = Context.BoolTy;
6964   }
6965   if (Result.isInvalid())
6966     return ExprError();
6967   Fn = Result.get();
6968 
6969   // Check for a valid function type, but only if it is not a builtin which
6970   // requires custom type checking. These will be handled by
6971   // CheckBuiltinFunctionCall below just after creation of the call expression.
6972   const FunctionType *FuncT = nullptr;
6973   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6974   retry:
6975     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6976       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6977       // have type pointer to function".
6978       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6979       if (!FuncT)
6980         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6981                          << Fn->getType() << Fn->getSourceRange());
6982     } else if (const BlockPointerType *BPT =
6983                    Fn->getType()->getAs<BlockPointerType>()) {
6984       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6985     } else {
6986       // Handle calls to expressions of unknown-any type.
6987       if (Fn->getType() == Context.UnknownAnyTy) {
6988         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6989         if (rewrite.isInvalid())
6990           return ExprError();
6991         Fn = rewrite.get();
6992         goto retry;
6993       }
6994 
6995       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6996                        << Fn->getType() << Fn->getSourceRange());
6997     }
6998   }
6999 
7000   // Get the number of parameters in the function prototype, if any.
7001   // We will allocate space for max(Args.size(), NumParams) arguments
7002   // in the call expression.
7003   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7004   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7005 
7006   CallExpr *TheCall;
7007   if (Config) {
7008     assert(UsesADL == ADLCallKind::NotADL &&
7009            "CUDAKernelCallExpr should not use ADL");
7010     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7011                                          Args, ResultTy, VK_PRValue, RParenLoc,
7012                                          CurFPFeatureOverrides(), NumParams);
7013   } else {
7014     TheCall =
7015         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7016                          CurFPFeatureOverrides(), NumParams, UsesADL);
7017   }
7018 
7019   if (!Context.isDependenceAllowed()) {
7020     // Forget about the nulled arguments since typo correction
7021     // do not handle them well.
7022     TheCall->shrinkNumArgs(Args.size());
7023     // C cannot always handle TypoExpr nodes in builtin calls and direct
7024     // function calls as their argument checking don't necessarily handle
7025     // dependent types properly, so make sure any TypoExprs have been
7026     // dealt with.
7027     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7028     if (!Result.isUsable()) return ExprError();
7029     CallExpr *TheOldCall = TheCall;
7030     TheCall = dyn_cast<CallExpr>(Result.get());
7031     bool CorrectedTypos = TheCall != TheOldCall;
7032     if (!TheCall) return Result;
7033     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7034 
7035     // A new call expression node was created if some typos were corrected.
7036     // However it may not have been constructed with enough storage. In this
7037     // case, rebuild the node with enough storage. The waste of space is
7038     // immaterial since this only happens when some typos were corrected.
7039     if (CorrectedTypos && Args.size() < NumParams) {
7040       if (Config)
7041         TheCall = CUDAKernelCallExpr::Create(
7042             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7043             RParenLoc, CurFPFeatureOverrides(), NumParams);
7044       else
7045         TheCall =
7046             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7047                              CurFPFeatureOverrides(), NumParams, UsesADL);
7048     }
7049     // We can now handle the nulled arguments for the default arguments.
7050     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7051   }
7052 
7053   // Bail out early if calling a builtin with custom type checking.
7054   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7055     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7056 
7057   if (getLangOpts().CUDA) {
7058     if (Config) {
7059       // CUDA: Kernel calls must be to global functions
7060       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7061         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7062             << FDecl << Fn->getSourceRange());
7063 
7064       // CUDA: Kernel function must have 'void' return type
7065       if (!FuncT->getReturnType()->isVoidType() &&
7066           !FuncT->getReturnType()->getAs<AutoType>() &&
7067           !FuncT->getReturnType()->isInstantiationDependentType())
7068         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7069             << Fn->getType() << Fn->getSourceRange());
7070     } else {
7071       // CUDA: Calls to global functions must be configured
7072       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7073         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7074             << FDecl << Fn->getSourceRange());
7075     }
7076   }
7077 
7078   // Check for a valid return type
7079   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7080                           FDecl))
7081     return ExprError();
7082 
7083   // We know the result type of the call, set it.
7084   TheCall->setType(FuncT->getCallResultType(Context));
7085   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7086 
7087   if (Proto) {
7088     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7089                                 IsExecConfig))
7090       return ExprError();
7091   } else {
7092     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7093 
7094     if (FDecl) {
7095       // Check if we have too few/too many template arguments, based
7096       // on our knowledge of the function definition.
7097       const FunctionDecl *Def = nullptr;
7098       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7099         Proto = Def->getType()->getAs<FunctionProtoType>();
7100        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7101           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7102           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7103       }
7104 
7105       // If the function we're calling isn't a function prototype, but we have
7106       // a function prototype from a prior declaratiom, use that prototype.
7107       if (!FDecl->hasPrototype())
7108         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7109     }
7110 
7111     // If we still haven't found a prototype to use but there are arguments to
7112     // the call, diagnose this as calling a function without a prototype.
7113     // However, if we found a function declaration, check to see if
7114     // -Wdeprecated-non-prototype was disabled where the function was declared.
7115     // If so, we will silence the diagnostic here on the assumption that this
7116     // interface is intentional and the user knows what they're doing. We will
7117     // also silence the diagnostic if there is a function declaration but it
7118     // was implicitly defined (the user already gets diagnostics about the
7119     // creation of the implicit function declaration, so the additional warning
7120     // is not helpful).
7121     if (!Proto && !Args.empty() &&
7122         (!FDecl || (!FDecl->isImplicit() &&
7123                     !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7124                                      FDecl->getLocation()))))
7125       Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7126           << (FDecl != nullptr) << FDecl;
7127 
7128     // Promote the arguments (C99 6.5.2.2p6).
7129     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7130       Expr *Arg = Args[i];
7131 
7132       if (Proto && i < Proto->getNumParams()) {
7133         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7134             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7135         ExprResult ArgE =
7136             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7137         if (ArgE.isInvalid())
7138           return true;
7139 
7140         Arg = ArgE.getAs<Expr>();
7141 
7142       } else {
7143         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7144 
7145         if (ArgE.isInvalid())
7146           return true;
7147 
7148         Arg = ArgE.getAs<Expr>();
7149       }
7150 
7151       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7152                               diag::err_call_incomplete_argument, Arg))
7153         return ExprError();
7154 
7155       TheCall->setArg(i, Arg);
7156     }
7157     TheCall->computeDependence();
7158   }
7159 
7160   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7161     if (!Method->isStatic())
7162       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7163         << Fn->getSourceRange());
7164 
7165   // Check for sentinels
7166   if (NDecl)
7167     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7168 
7169   // Warn for unions passing across security boundary (CMSE).
7170   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7171     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7172       if (const auto *RT =
7173               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7174         if (RT->getDecl()->isOrContainsUnion())
7175           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7176               << 0 << i;
7177       }
7178     }
7179   }
7180 
7181   // Do special checking on direct calls to functions.
7182   if (FDecl) {
7183     if (CheckFunctionCall(FDecl, TheCall, Proto))
7184       return ExprError();
7185 
7186     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7187 
7188     if (BuiltinID)
7189       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7190   } else if (NDecl) {
7191     if (CheckPointerCall(NDecl, TheCall, Proto))
7192       return ExprError();
7193   } else {
7194     if (CheckOtherCall(TheCall, Proto))
7195       return ExprError();
7196   }
7197 
7198   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7199 }
7200 
7201 ExprResult
7202 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7203                            SourceLocation RParenLoc, Expr *InitExpr) {
7204   assert(Ty && "ActOnCompoundLiteral(): missing type");
7205   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7206 
7207   TypeSourceInfo *TInfo;
7208   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7209   if (!TInfo)
7210     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7211 
7212   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7213 }
7214 
7215 ExprResult
7216 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7217                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7218   QualType literalType = TInfo->getType();
7219 
7220   if (literalType->isArrayType()) {
7221     if (RequireCompleteSizedType(
7222             LParenLoc, Context.getBaseElementType(literalType),
7223             diag::err_array_incomplete_or_sizeless_type,
7224             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7225       return ExprError();
7226     if (literalType->isVariableArrayType()) {
7227       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7228                                            diag::err_variable_object_no_init)) {
7229         return ExprError();
7230       }
7231     }
7232   } else if (!literalType->isDependentType() &&
7233              RequireCompleteType(LParenLoc, literalType,
7234                diag::err_typecheck_decl_incomplete_type,
7235                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7236     return ExprError();
7237 
7238   InitializedEntity Entity
7239     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7240   InitializationKind Kind
7241     = InitializationKind::CreateCStyleCast(LParenLoc,
7242                                            SourceRange(LParenLoc, RParenLoc),
7243                                            /*InitList=*/true);
7244   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7245   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7246                                       &literalType);
7247   if (Result.isInvalid())
7248     return ExprError();
7249   LiteralExpr = Result.get();
7250 
7251   bool isFileScope = !CurContext->isFunctionOrMethod();
7252 
7253   // In C, compound literals are l-values for some reason.
7254   // For GCC compatibility, in C++, file-scope array compound literals with
7255   // constant initializers are also l-values, and compound literals are
7256   // otherwise prvalues.
7257   //
7258   // (GCC also treats C++ list-initialized file-scope array prvalues with
7259   // constant initializers as l-values, but that's non-conforming, so we don't
7260   // follow it there.)
7261   //
7262   // FIXME: It would be better to handle the lvalue cases as materializing and
7263   // lifetime-extending a temporary object, but our materialized temporaries
7264   // representation only supports lifetime extension from a variable, not "out
7265   // of thin air".
7266   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7267   // is bound to the result of applying array-to-pointer decay to the compound
7268   // literal.
7269   // FIXME: GCC supports compound literals of reference type, which should
7270   // obviously have a value kind derived from the kind of reference involved.
7271   ExprValueKind VK =
7272       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7273           ? VK_PRValue
7274           : VK_LValue;
7275 
7276   if (isFileScope)
7277     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7278       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7279         Expr *Init = ILE->getInit(i);
7280         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7281       }
7282 
7283   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7284                                               VK, LiteralExpr, isFileScope);
7285   if (isFileScope) {
7286     if (!LiteralExpr->isTypeDependent() &&
7287         !LiteralExpr->isValueDependent() &&
7288         !literalType->isDependentType()) // C99 6.5.2.5p3
7289       if (CheckForConstantInitializer(LiteralExpr, literalType))
7290         return ExprError();
7291   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7292              literalType.getAddressSpace() != LangAS::Default) {
7293     // Embedded-C extensions to C99 6.5.2.5:
7294     //   "If the compound literal occurs inside the body of a function, the
7295     //   type name shall not be qualified by an address-space qualifier."
7296     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7297       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7298     return ExprError();
7299   }
7300 
7301   if (!isFileScope && !getLangOpts().CPlusPlus) {
7302     // Compound literals that have automatic storage duration are destroyed at
7303     // the end of the scope in C; in C++, they're just temporaries.
7304 
7305     // Emit diagnostics if it is or contains a C union type that is non-trivial
7306     // to destruct.
7307     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7308       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7309                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7310 
7311     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7312     if (literalType.isDestructedType()) {
7313       Cleanup.setExprNeedsCleanups(true);
7314       ExprCleanupObjects.push_back(E);
7315       getCurFunction()->setHasBranchProtectedScope();
7316     }
7317   }
7318 
7319   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7320       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7321     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7322                                        E->getInitializer()->getExprLoc());
7323 
7324   return MaybeBindToTemporary(E);
7325 }
7326 
7327 ExprResult
7328 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7329                     SourceLocation RBraceLoc) {
7330   // Only produce each kind of designated initialization diagnostic once.
7331   SourceLocation FirstDesignator;
7332   bool DiagnosedArrayDesignator = false;
7333   bool DiagnosedNestedDesignator = false;
7334   bool DiagnosedMixedDesignator = false;
7335 
7336   // Check that any designated initializers are syntactically valid in the
7337   // current language mode.
7338   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7339     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7340       if (FirstDesignator.isInvalid())
7341         FirstDesignator = DIE->getBeginLoc();
7342 
7343       if (!getLangOpts().CPlusPlus)
7344         break;
7345 
7346       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7347         DiagnosedNestedDesignator = true;
7348         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7349           << DIE->getDesignatorsSourceRange();
7350       }
7351 
7352       for (auto &Desig : DIE->designators()) {
7353         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7354           DiagnosedArrayDesignator = true;
7355           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7356             << Desig.getSourceRange();
7357         }
7358       }
7359 
7360       if (!DiagnosedMixedDesignator &&
7361           !isa<DesignatedInitExpr>(InitArgList[0])) {
7362         DiagnosedMixedDesignator = true;
7363         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7364           << DIE->getSourceRange();
7365         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7366           << InitArgList[0]->getSourceRange();
7367       }
7368     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7369                isa<DesignatedInitExpr>(InitArgList[0])) {
7370       DiagnosedMixedDesignator = true;
7371       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7372       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7373         << DIE->getSourceRange();
7374       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7375         << InitArgList[I]->getSourceRange();
7376     }
7377   }
7378 
7379   if (FirstDesignator.isValid()) {
7380     // Only diagnose designated initiaization as a C++20 extension if we didn't
7381     // already diagnose use of (non-C++20) C99 designator syntax.
7382     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7383         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7384       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7385                                 ? diag::warn_cxx17_compat_designated_init
7386                                 : diag::ext_cxx_designated_init);
7387     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7388       Diag(FirstDesignator, diag::ext_designated_init);
7389     }
7390   }
7391 
7392   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7393 }
7394 
7395 ExprResult
7396 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7397                     SourceLocation RBraceLoc) {
7398   // Semantic analysis for initializers is done by ActOnDeclarator() and
7399   // CheckInitializer() - it requires knowledge of the object being initialized.
7400 
7401   // Immediately handle non-overload placeholders.  Overloads can be
7402   // resolved contextually, but everything else here can't.
7403   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7404     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7405       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7406 
7407       // Ignore failures; dropping the entire initializer list because
7408       // of one failure would be terrible for indexing/etc.
7409       if (result.isInvalid()) continue;
7410 
7411       InitArgList[I] = result.get();
7412     }
7413   }
7414 
7415   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7416                                                RBraceLoc);
7417   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7418   return E;
7419 }
7420 
7421 /// Do an explicit extend of the given block pointer if we're in ARC.
7422 void Sema::maybeExtendBlockObject(ExprResult &E) {
7423   assert(E.get()->getType()->isBlockPointerType());
7424   assert(E.get()->isPRValue());
7425 
7426   // Only do this in an r-value context.
7427   if (!getLangOpts().ObjCAutoRefCount) return;
7428 
7429   E = ImplicitCastExpr::Create(
7430       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7431       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7432   Cleanup.setExprNeedsCleanups(true);
7433 }
7434 
7435 /// Prepare a conversion of the given expression to an ObjC object
7436 /// pointer type.
7437 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7438   QualType type = E.get()->getType();
7439   if (type->isObjCObjectPointerType()) {
7440     return CK_BitCast;
7441   } else if (type->isBlockPointerType()) {
7442     maybeExtendBlockObject(E);
7443     return CK_BlockPointerToObjCPointerCast;
7444   } else {
7445     assert(type->isPointerType());
7446     return CK_CPointerToObjCPointerCast;
7447   }
7448 }
7449 
7450 /// Prepares for a scalar cast, performing all the necessary stages
7451 /// except the final cast and returning the kind required.
7452 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7453   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7454   // Also, callers should have filtered out the invalid cases with
7455   // pointers.  Everything else should be possible.
7456 
7457   QualType SrcTy = Src.get()->getType();
7458   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7459     return CK_NoOp;
7460 
7461   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7462   case Type::STK_MemberPointer:
7463     llvm_unreachable("member pointer type in C");
7464 
7465   case Type::STK_CPointer:
7466   case Type::STK_BlockPointer:
7467   case Type::STK_ObjCObjectPointer:
7468     switch (DestTy->getScalarTypeKind()) {
7469     case Type::STK_CPointer: {
7470       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7471       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7472       if (SrcAS != DestAS)
7473         return CK_AddressSpaceConversion;
7474       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7475         return CK_NoOp;
7476       return CK_BitCast;
7477     }
7478     case Type::STK_BlockPointer:
7479       return (SrcKind == Type::STK_BlockPointer
7480                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7481     case Type::STK_ObjCObjectPointer:
7482       if (SrcKind == Type::STK_ObjCObjectPointer)
7483         return CK_BitCast;
7484       if (SrcKind == Type::STK_CPointer)
7485         return CK_CPointerToObjCPointerCast;
7486       maybeExtendBlockObject(Src);
7487       return CK_BlockPointerToObjCPointerCast;
7488     case Type::STK_Bool:
7489       return CK_PointerToBoolean;
7490     case Type::STK_Integral:
7491       return CK_PointerToIntegral;
7492     case Type::STK_Floating:
7493     case Type::STK_FloatingComplex:
7494     case Type::STK_IntegralComplex:
7495     case Type::STK_MemberPointer:
7496     case Type::STK_FixedPoint:
7497       llvm_unreachable("illegal cast from pointer");
7498     }
7499     llvm_unreachable("Should have returned before this");
7500 
7501   case Type::STK_FixedPoint:
7502     switch (DestTy->getScalarTypeKind()) {
7503     case Type::STK_FixedPoint:
7504       return CK_FixedPointCast;
7505     case Type::STK_Bool:
7506       return CK_FixedPointToBoolean;
7507     case Type::STK_Integral:
7508       return CK_FixedPointToIntegral;
7509     case Type::STK_Floating:
7510       return CK_FixedPointToFloating;
7511     case Type::STK_IntegralComplex:
7512     case Type::STK_FloatingComplex:
7513       Diag(Src.get()->getExprLoc(),
7514            diag::err_unimplemented_conversion_with_fixed_point_type)
7515           << DestTy;
7516       return CK_IntegralCast;
7517     case Type::STK_CPointer:
7518     case Type::STK_ObjCObjectPointer:
7519     case Type::STK_BlockPointer:
7520     case Type::STK_MemberPointer:
7521       llvm_unreachable("illegal cast to pointer type");
7522     }
7523     llvm_unreachable("Should have returned before this");
7524 
7525   case Type::STK_Bool: // casting from bool is like casting from an integer
7526   case Type::STK_Integral:
7527     switch (DestTy->getScalarTypeKind()) {
7528     case Type::STK_CPointer:
7529     case Type::STK_ObjCObjectPointer:
7530     case Type::STK_BlockPointer:
7531       if (Src.get()->isNullPointerConstant(Context,
7532                                            Expr::NPC_ValueDependentIsNull))
7533         return CK_NullToPointer;
7534       return CK_IntegralToPointer;
7535     case Type::STK_Bool:
7536       return CK_IntegralToBoolean;
7537     case Type::STK_Integral:
7538       return CK_IntegralCast;
7539     case Type::STK_Floating:
7540       return CK_IntegralToFloating;
7541     case Type::STK_IntegralComplex:
7542       Src = ImpCastExprToType(Src.get(),
7543                       DestTy->castAs<ComplexType>()->getElementType(),
7544                       CK_IntegralCast);
7545       return CK_IntegralRealToComplex;
7546     case Type::STK_FloatingComplex:
7547       Src = ImpCastExprToType(Src.get(),
7548                       DestTy->castAs<ComplexType>()->getElementType(),
7549                       CK_IntegralToFloating);
7550       return CK_FloatingRealToComplex;
7551     case Type::STK_MemberPointer:
7552       llvm_unreachable("member pointer type in C");
7553     case Type::STK_FixedPoint:
7554       return CK_IntegralToFixedPoint;
7555     }
7556     llvm_unreachable("Should have returned before this");
7557 
7558   case Type::STK_Floating:
7559     switch (DestTy->getScalarTypeKind()) {
7560     case Type::STK_Floating:
7561       return CK_FloatingCast;
7562     case Type::STK_Bool:
7563       return CK_FloatingToBoolean;
7564     case Type::STK_Integral:
7565       return CK_FloatingToIntegral;
7566     case Type::STK_FloatingComplex:
7567       Src = ImpCastExprToType(Src.get(),
7568                               DestTy->castAs<ComplexType>()->getElementType(),
7569                               CK_FloatingCast);
7570       return CK_FloatingRealToComplex;
7571     case Type::STK_IntegralComplex:
7572       Src = ImpCastExprToType(Src.get(),
7573                               DestTy->castAs<ComplexType>()->getElementType(),
7574                               CK_FloatingToIntegral);
7575       return CK_IntegralRealToComplex;
7576     case Type::STK_CPointer:
7577     case Type::STK_ObjCObjectPointer:
7578     case Type::STK_BlockPointer:
7579       llvm_unreachable("valid float->pointer cast?");
7580     case Type::STK_MemberPointer:
7581       llvm_unreachable("member pointer type in C");
7582     case Type::STK_FixedPoint:
7583       return CK_FloatingToFixedPoint;
7584     }
7585     llvm_unreachable("Should have returned before this");
7586 
7587   case Type::STK_FloatingComplex:
7588     switch (DestTy->getScalarTypeKind()) {
7589     case Type::STK_FloatingComplex:
7590       return CK_FloatingComplexCast;
7591     case Type::STK_IntegralComplex:
7592       return CK_FloatingComplexToIntegralComplex;
7593     case Type::STK_Floating: {
7594       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7595       if (Context.hasSameType(ET, DestTy))
7596         return CK_FloatingComplexToReal;
7597       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7598       return CK_FloatingCast;
7599     }
7600     case Type::STK_Bool:
7601       return CK_FloatingComplexToBoolean;
7602     case Type::STK_Integral:
7603       Src = ImpCastExprToType(Src.get(),
7604                               SrcTy->castAs<ComplexType>()->getElementType(),
7605                               CK_FloatingComplexToReal);
7606       return CK_FloatingToIntegral;
7607     case Type::STK_CPointer:
7608     case Type::STK_ObjCObjectPointer:
7609     case Type::STK_BlockPointer:
7610       llvm_unreachable("valid complex float->pointer cast?");
7611     case Type::STK_MemberPointer:
7612       llvm_unreachable("member pointer type in C");
7613     case Type::STK_FixedPoint:
7614       Diag(Src.get()->getExprLoc(),
7615            diag::err_unimplemented_conversion_with_fixed_point_type)
7616           << SrcTy;
7617       return CK_IntegralCast;
7618     }
7619     llvm_unreachable("Should have returned before this");
7620 
7621   case Type::STK_IntegralComplex:
7622     switch (DestTy->getScalarTypeKind()) {
7623     case Type::STK_FloatingComplex:
7624       return CK_IntegralComplexToFloatingComplex;
7625     case Type::STK_IntegralComplex:
7626       return CK_IntegralComplexCast;
7627     case Type::STK_Integral: {
7628       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7629       if (Context.hasSameType(ET, DestTy))
7630         return CK_IntegralComplexToReal;
7631       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7632       return CK_IntegralCast;
7633     }
7634     case Type::STK_Bool:
7635       return CK_IntegralComplexToBoolean;
7636     case Type::STK_Floating:
7637       Src = ImpCastExprToType(Src.get(),
7638                               SrcTy->castAs<ComplexType>()->getElementType(),
7639                               CK_IntegralComplexToReal);
7640       return CK_IntegralToFloating;
7641     case Type::STK_CPointer:
7642     case Type::STK_ObjCObjectPointer:
7643     case Type::STK_BlockPointer:
7644       llvm_unreachable("valid complex int->pointer cast?");
7645     case Type::STK_MemberPointer:
7646       llvm_unreachable("member pointer type in C");
7647     case Type::STK_FixedPoint:
7648       Diag(Src.get()->getExprLoc(),
7649            diag::err_unimplemented_conversion_with_fixed_point_type)
7650           << SrcTy;
7651       return CK_IntegralCast;
7652     }
7653     llvm_unreachable("Should have returned before this");
7654   }
7655 
7656   llvm_unreachable("Unhandled scalar cast");
7657 }
7658 
7659 static bool breakDownVectorType(QualType type, uint64_t &len,
7660                                 QualType &eltType) {
7661   // Vectors are simple.
7662   if (const VectorType *vecType = type->getAs<VectorType>()) {
7663     len = vecType->getNumElements();
7664     eltType = vecType->getElementType();
7665     assert(eltType->isScalarType());
7666     return true;
7667   }
7668 
7669   // We allow lax conversion to and from non-vector types, but only if
7670   // they're real types (i.e. non-complex, non-pointer scalar types).
7671   if (!type->isRealType()) return false;
7672 
7673   len = 1;
7674   eltType = type;
7675   return true;
7676 }
7677 
7678 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7679 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7680 /// allowed?
7681 ///
7682 /// This will also return false if the two given types do not make sense from
7683 /// the perspective of SVE bitcasts.
7684 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7685   assert(srcTy->isVectorType() || destTy->isVectorType());
7686 
7687   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7688     if (!FirstType->isSizelessBuiltinType())
7689       return false;
7690 
7691     const auto *VecTy = SecondType->getAs<VectorType>();
7692     return VecTy &&
7693            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7694   };
7695 
7696   return ValidScalableConversion(srcTy, destTy) ||
7697          ValidScalableConversion(destTy, srcTy);
7698 }
7699 
7700 /// Are the two types matrix types and do they have the same dimensions i.e.
7701 /// do they have the same number of rows and the same number of columns?
7702 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7703   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7704     return false;
7705 
7706   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7707   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7708 
7709   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7710          matSrcType->getNumColumns() == matDestType->getNumColumns();
7711 }
7712 
7713 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7714   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7715 
7716   uint64_t SrcLen, DestLen;
7717   QualType SrcEltTy, DestEltTy;
7718   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7719     return false;
7720   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7721     return false;
7722 
7723   // ASTContext::getTypeSize will return the size rounded up to a
7724   // power of 2, so instead of using that, we need to use the raw
7725   // element size multiplied by the element count.
7726   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7727   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7728 
7729   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7730 }
7731 
7732 /// Are the two types lax-compatible vector types?  That is, given
7733 /// that one of them is a vector, do they have equal storage sizes,
7734 /// where the storage size is the number of elements times the element
7735 /// size?
7736 ///
7737 /// This will also return false if either of the types is neither a
7738 /// vector nor a real type.
7739 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7740   assert(destTy->isVectorType() || srcTy->isVectorType());
7741 
7742   // Disallow lax conversions between scalars and ExtVectors (these
7743   // conversions are allowed for other vector types because common headers
7744   // depend on them).  Most scalar OP ExtVector cases are handled by the
7745   // splat path anyway, which does what we want (convert, not bitcast).
7746   // What this rules out for ExtVectors is crazy things like char4*float.
7747   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7748   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7749 
7750   return areVectorTypesSameSize(srcTy, destTy);
7751 }
7752 
7753 /// Is this a legal conversion between two types, one of which is
7754 /// known to be a vector type?
7755 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7756   assert(destTy->isVectorType() || srcTy->isVectorType());
7757 
7758   switch (Context.getLangOpts().getLaxVectorConversions()) {
7759   case LangOptions::LaxVectorConversionKind::None:
7760     return false;
7761 
7762   case LangOptions::LaxVectorConversionKind::Integer:
7763     if (!srcTy->isIntegralOrEnumerationType()) {
7764       auto *Vec = srcTy->getAs<VectorType>();
7765       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7766         return false;
7767     }
7768     if (!destTy->isIntegralOrEnumerationType()) {
7769       auto *Vec = destTy->getAs<VectorType>();
7770       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7771         return false;
7772     }
7773     // OK, integer (vector) -> integer (vector) bitcast.
7774     break;
7775 
7776     case LangOptions::LaxVectorConversionKind::All:
7777     break;
7778   }
7779 
7780   return areLaxCompatibleVectorTypes(srcTy, destTy);
7781 }
7782 
7783 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7784                            CastKind &Kind) {
7785   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7786     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7787       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7788              << DestTy << SrcTy << R;
7789     }
7790   } else if (SrcTy->isMatrixType()) {
7791     return Diag(R.getBegin(),
7792                 diag::err_invalid_conversion_between_matrix_and_type)
7793            << SrcTy << DestTy << R;
7794   } else if (DestTy->isMatrixType()) {
7795     return Diag(R.getBegin(),
7796                 diag::err_invalid_conversion_between_matrix_and_type)
7797            << DestTy << SrcTy << R;
7798   }
7799 
7800   Kind = CK_MatrixCast;
7801   return false;
7802 }
7803 
7804 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7805                            CastKind &Kind) {
7806   assert(VectorTy->isVectorType() && "Not a vector type!");
7807 
7808   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7809     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7810       return Diag(R.getBegin(),
7811                   Ty->isVectorType() ?
7812                   diag::err_invalid_conversion_between_vectors :
7813                   diag::err_invalid_conversion_between_vector_and_integer)
7814         << VectorTy << Ty << R;
7815   } else
7816     return Diag(R.getBegin(),
7817                 diag::err_invalid_conversion_between_vector_and_scalar)
7818       << VectorTy << Ty << R;
7819 
7820   Kind = CK_BitCast;
7821   return false;
7822 }
7823 
7824 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7825   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7826 
7827   if (DestElemTy == SplattedExpr->getType())
7828     return SplattedExpr;
7829 
7830   assert(DestElemTy->isFloatingType() ||
7831          DestElemTy->isIntegralOrEnumerationType());
7832 
7833   CastKind CK;
7834   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7835     // OpenCL requires that we convert `true` boolean expressions to -1, but
7836     // only when splatting vectors.
7837     if (DestElemTy->isFloatingType()) {
7838       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7839       // in two steps: boolean to signed integral, then to floating.
7840       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7841                                                  CK_BooleanToSignedIntegral);
7842       SplattedExpr = CastExprRes.get();
7843       CK = CK_IntegralToFloating;
7844     } else {
7845       CK = CK_BooleanToSignedIntegral;
7846     }
7847   } else {
7848     ExprResult CastExprRes = SplattedExpr;
7849     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7850     if (CastExprRes.isInvalid())
7851       return ExprError();
7852     SplattedExpr = CastExprRes.get();
7853   }
7854   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7855 }
7856 
7857 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7858                                     Expr *CastExpr, CastKind &Kind) {
7859   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7860 
7861   QualType SrcTy = CastExpr->getType();
7862 
7863   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7864   // an ExtVectorType.
7865   // In OpenCL, casts between vectors of different types are not allowed.
7866   // (See OpenCL 6.2).
7867   if (SrcTy->isVectorType()) {
7868     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7869         (getLangOpts().OpenCL &&
7870          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7871       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7872         << DestTy << SrcTy << R;
7873       return ExprError();
7874     }
7875     Kind = CK_BitCast;
7876     return CastExpr;
7877   }
7878 
7879   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7880   // conversion will take place first from scalar to elt type, and then
7881   // splat from elt type to vector.
7882   if (SrcTy->isPointerType())
7883     return Diag(R.getBegin(),
7884                 diag::err_invalid_conversion_between_vector_and_scalar)
7885       << DestTy << SrcTy << R;
7886 
7887   Kind = CK_VectorSplat;
7888   return prepareVectorSplat(DestTy, CastExpr);
7889 }
7890 
7891 ExprResult
7892 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7893                     Declarator &D, ParsedType &Ty,
7894                     SourceLocation RParenLoc, Expr *CastExpr) {
7895   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7896          "ActOnCastExpr(): missing type or expr");
7897 
7898   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7899   if (D.isInvalidType())
7900     return ExprError();
7901 
7902   if (getLangOpts().CPlusPlus) {
7903     // Check that there are no default arguments (C++ only).
7904     CheckExtraCXXDefaultArguments(D);
7905   } else {
7906     // Make sure any TypoExprs have been dealt with.
7907     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7908     if (!Res.isUsable())
7909       return ExprError();
7910     CastExpr = Res.get();
7911   }
7912 
7913   checkUnusedDeclAttributes(D);
7914 
7915   QualType castType = castTInfo->getType();
7916   Ty = CreateParsedType(castType, castTInfo);
7917 
7918   bool isVectorLiteral = false;
7919 
7920   // Check for an altivec or OpenCL literal,
7921   // i.e. all the elements are integer constants.
7922   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7923   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7924   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7925        && castType->isVectorType() && (PE || PLE)) {
7926     if (PLE && PLE->getNumExprs() == 0) {
7927       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7928       return ExprError();
7929     }
7930     if (PE || PLE->getNumExprs() == 1) {
7931       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7932       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7933         isVectorLiteral = true;
7934     }
7935     else
7936       isVectorLiteral = true;
7937   }
7938 
7939   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7940   // then handle it as such.
7941   if (isVectorLiteral)
7942     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7943 
7944   // If the Expr being casted is a ParenListExpr, handle it specially.
7945   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7946   // sequence of BinOp comma operators.
7947   if (isa<ParenListExpr>(CastExpr)) {
7948     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7949     if (Result.isInvalid()) return ExprError();
7950     CastExpr = Result.get();
7951   }
7952 
7953   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7954     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7955 
7956   CheckTollFreeBridgeCast(castType, CastExpr);
7957 
7958   CheckObjCBridgeRelatedCast(castType, CastExpr);
7959 
7960   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7961 
7962   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7963 }
7964 
7965 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7966                                     SourceLocation RParenLoc, Expr *E,
7967                                     TypeSourceInfo *TInfo) {
7968   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7969          "Expected paren or paren list expression");
7970 
7971   Expr **exprs;
7972   unsigned numExprs;
7973   Expr *subExpr;
7974   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7975   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7976     LiteralLParenLoc = PE->getLParenLoc();
7977     LiteralRParenLoc = PE->getRParenLoc();
7978     exprs = PE->getExprs();
7979     numExprs = PE->getNumExprs();
7980   } else { // isa<ParenExpr> by assertion at function entrance
7981     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7982     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7983     subExpr = cast<ParenExpr>(E)->getSubExpr();
7984     exprs = &subExpr;
7985     numExprs = 1;
7986   }
7987 
7988   QualType Ty = TInfo->getType();
7989   assert(Ty->isVectorType() && "Expected vector type");
7990 
7991   SmallVector<Expr *, 8> initExprs;
7992   const VectorType *VTy = Ty->castAs<VectorType>();
7993   unsigned numElems = VTy->getNumElements();
7994 
7995   // '(...)' form of vector initialization in AltiVec: the number of
7996   // initializers must be one or must match the size of the vector.
7997   // If a single value is specified in the initializer then it will be
7998   // replicated to all the components of the vector
7999   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8000                                  VTy->getElementType()))
8001     return ExprError();
8002   if (ShouldSplatAltivecScalarInCast(VTy)) {
8003     // The number of initializers must be one or must match the size of the
8004     // vector. If a single value is specified in the initializer then it will
8005     // be replicated to all the components of the vector
8006     if (numExprs == 1) {
8007       QualType ElemTy = VTy->getElementType();
8008       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8009       if (Literal.isInvalid())
8010         return ExprError();
8011       Literal = ImpCastExprToType(Literal.get(), ElemTy,
8012                                   PrepareScalarCast(Literal, ElemTy));
8013       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8014     }
8015     else if (numExprs < numElems) {
8016       Diag(E->getExprLoc(),
8017            diag::err_incorrect_number_of_vector_initializers);
8018       return ExprError();
8019     }
8020     else
8021       initExprs.append(exprs, exprs + numExprs);
8022   }
8023   else {
8024     // For OpenCL, when the number of initializers is a single value,
8025     // it will be replicated to all components of the vector.
8026     if (getLangOpts().OpenCL &&
8027         VTy->getVectorKind() == VectorType::GenericVector &&
8028         numExprs == 1) {
8029         QualType ElemTy = VTy->getElementType();
8030         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8031         if (Literal.isInvalid())
8032           return ExprError();
8033         Literal = ImpCastExprToType(Literal.get(), ElemTy,
8034                                     PrepareScalarCast(Literal, ElemTy));
8035         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8036     }
8037 
8038     initExprs.append(exprs, exprs + numExprs);
8039   }
8040   // FIXME: This means that pretty-printing the final AST will produce curly
8041   // braces instead of the original commas.
8042   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8043                                                    initExprs, LiteralRParenLoc);
8044   initE->setType(Ty);
8045   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8046 }
8047 
8048 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8049 /// the ParenListExpr into a sequence of comma binary operators.
8050 ExprResult
8051 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8052   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8053   if (!E)
8054     return OrigExpr;
8055 
8056   ExprResult Result(E->getExpr(0));
8057 
8058   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8059     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8060                         E->getExpr(i));
8061 
8062   if (Result.isInvalid()) return ExprError();
8063 
8064   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8065 }
8066 
8067 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8068                                     SourceLocation R,
8069                                     MultiExprArg Val) {
8070   return ParenListExpr::Create(Context, L, Val, R);
8071 }
8072 
8073 /// Emit a specialized diagnostic when one expression is a null pointer
8074 /// constant and the other is not a pointer.  Returns true if a diagnostic is
8075 /// emitted.
8076 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8077                                       SourceLocation QuestionLoc) {
8078   Expr *NullExpr = LHSExpr;
8079   Expr *NonPointerExpr = RHSExpr;
8080   Expr::NullPointerConstantKind NullKind =
8081       NullExpr->isNullPointerConstant(Context,
8082                                       Expr::NPC_ValueDependentIsNotNull);
8083 
8084   if (NullKind == Expr::NPCK_NotNull) {
8085     NullExpr = RHSExpr;
8086     NonPointerExpr = LHSExpr;
8087     NullKind =
8088         NullExpr->isNullPointerConstant(Context,
8089                                         Expr::NPC_ValueDependentIsNotNull);
8090   }
8091 
8092   if (NullKind == Expr::NPCK_NotNull)
8093     return false;
8094 
8095   if (NullKind == Expr::NPCK_ZeroExpression)
8096     return false;
8097 
8098   if (NullKind == Expr::NPCK_ZeroLiteral) {
8099     // In this case, check to make sure that we got here from a "NULL"
8100     // string in the source code.
8101     NullExpr = NullExpr->IgnoreParenImpCasts();
8102     SourceLocation loc = NullExpr->getExprLoc();
8103     if (!findMacroSpelling(loc, "NULL"))
8104       return false;
8105   }
8106 
8107   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8108   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8109       << NonPointerExpr->getType() << DiagType
8110       << NonPointerExpr->getSourceRange();
8111   return true;
8112 }
8113 
8114 /// Return false if the condition expression is valid, true otherwise.
8115 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8116   QualType CondTy = Cond->getType();
8117 
8118   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8119   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8120     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8121       << CondTy << Cond->getSourceRange();
8122     return true;
8123   }
8124 
8125   // C99 6.5.15p2
8126   if (CondTy->isScalarType()) return false;
8127 
8128   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8129     << CondTy << Cond->getSourceRange();
8130   return true;
8131 }
8132 
8133 /// Handle when one or both operands are void type.
8134 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8135                                          ExprResult &RHS) {
8136     Expr *LHSExpr = LHS.get();
8137     Expr *RHSExpr = RHS.get();
8138 
8139     if (!LHSExpr->getType()->isVoidType())
8140       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8141           << RHSExpr->getSourceRange();
8142     if (!RHSExpr->getType()->isVoidType())
8143       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8144           << LHSExpr->getSourceRange();
8145     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8146     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8147     return S.Context.VoidTy;
8148 }
8149 
8150 /// Return false if the NullExpr can be promoted to PointerTy,
8151 /// true otherwise.
8152 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8153                                         QualType PointerTy) {
8154   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8155       !NullExpr.get()->isNullPointerConstant(S.Context,
8156                                             Expr::NPC_ValueDependentIsNull))
8157     return true;
8158 
8159   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8160   return false;
8161 }
8162 
8163 /// Checks compatibility between two pointers and return the resulting
8164 /// type.
8165 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8166                                                      ExprResult &RHS,
8167                                                      SourceLocation Loc) {
8168   QualType LHSTy = LHS.get()->getType();
8169   QualType RHSTy = RHS.get()->getType();
8170 
8171   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8172     // Two identical pointers types are always compatible.
8173     return LHSTy;
8174   }
8175 
8176   QualType lhptee, rhptee;
8177 
8178   // Get the pointee types.
8179   bool IsBlockPointer = false;
8180   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8181     lhptee = LHSBTy->getPointeeType();
8182     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8183     IsBlockPointer = true;
8184   } else {
8185     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8186     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8187   }
8188 
8189   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8190   // differently qualified versions of compatible types, the result type is
8191   // a pointer to an appropriately qualified version of the composite
8192   // type.
8193 
8194   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8195   // clause doesn't make sense for our extensions. E.g. address space 2 should
8196   // be incompatible with address space 3: they may live on different devices or
8197   // anything.
8198   Qualifiers lhQual = lhptee.getQualifiers();
8199   Qualifiers rhQual = rhptee.getQualifiers();
8200 
8201   LangAS ResultAddrSpace = LangAS::Default;
8202   LangAS LAddrSpace = lhQual.getAddressSpace();
8203   LangAS RAddrSpace = rhQual.getAddressSpace();
8204 
8205   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8206   // spaces is disallowed.
8207   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8208     ResultAddrSpace = LAddrSpace;
8209   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8210     ResultAddrSpace = RAddrSpace;
8211   else {
8212     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8213         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8214         << RHS.get()->getSourceRange();
8215     return QualType();
8216   }
8217 
8218   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8219   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8220   lhQual.removeCVRQualifiers();
8221   rhQual.removeCVRQualifiers();
8222 
8223   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8224   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8225   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8226   // qual types are compatible iff
8227   //  * corresponded types are compatible
8228   //  * CVR qualifiers are equal
8229   //  * address spaces are equal
8230   // Thus for conditional operator we merge CVR and address space unqualified
8231   // pointees and if there is a composite type we return a pointer to it with
8232   // merged qualifiers.
8233   LHSCastKind =
8234       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8235   RHSCastKind =
8236       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8237   lhQual.removeAddressSpace();
8238   rhQual.removeAddressSpace();
8239 
8240   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8241   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8242 
8243   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8244 
8245   if (CompositeTy.isNull()) {
8246     // In this situation, we assume void* type. No especially good
8247     // reason, but this is what gcc does, and we do have to pick
8248     // to get a consistent AST.
8249     QualType incompatTy;
8250     incompatTy = S.Context.getPointerType(
8251         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8252     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8253     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8254 
8255     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8256     // for casts between types with incompatible address space qualifiers.
8257     // For the following code the compiler produces casts between global and
8258     // local address spaces of the corresponded innermost pointees:
8259     // local int *global *a;
8260     // global int *global *b;
8261     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8262     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8263         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8264         << RHS.get()->getSourceRange();
8265 
8266     return incompatTy;
8267   }
8268 
8269   // The pointer types are compatible.
8270   // In case of OpenCL ResultTy should have the address space qualifier
8271   // which is a superset of address spaces of both the 2nd and the 3rd
8272   // operands of the conditional operator.
8273   QualType ResultTy = [&, ResultAddrSpace]() {
8274     if (S.getLangOpts().OpenCL) {
8275       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8276       CompositeQuals.setAddressSpace(ResultAddrSpace);
8277       return S.Context
8278           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8279           .withCVRQualifiers(MergedCVRQual);
8280     }
8281     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8282   }();
8283   if (IsBlockPointer)
8284     ResultTy = S.Context.getBlockPointerType(ResultTy);
8285   else
8286     ResultTy = S.Context.getPointerType(ResultTy);
8287 
8288   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8289   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8290   return ResultTy;
8291 }
8292 
8293 /// Return the resulting type when the operands are both block pointers.
8294 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8295                                                           ExprResult &LHS,
8296                                                           ExprResult &RHS,
8297                                                           SourceLocation Loc) {
8298   QualType LHSTy = LHS.get()->getType();
8299   QualType RHSTy = RHS.get()->getType();
8300 
8301   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8302     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8303       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8304       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8305       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8306       return destType;
8307     }
8308     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8309       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8310       << RHS.get()->getSourceRange();
8311     return QualType();
8312   }
8313 
8314   // We have 2 block pointer types.
8315   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8316 }
8317 
8318 /// Return the resulting type when the operands are both pointers.
8319 static QualType
8320 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8321                                             ExprResult &RHS,
8322                                             SourceLocation Loc) {
8323   // get the pointer types
8324   QualType LHSTy = LHS.get()->getType();
8325   QualType RHSTy = RHS.get()->getType();
8326 
8327   // get the "pointed to" types
8328   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8329   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8330 
8331   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8332   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8333     // Figure out necessary qualifiers (C99 6.5.15p6)
8334     QualType destPointee
8335       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8336     QualType destType = S.Context.getPointerType(destPointee);
8337     // Add qualifiers if necessary.
8338     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8339     // Promote to void*.
8340     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8341     return destType;
8342   }
8343   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8344     QualType destPointee
8345       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8346     QualType destType = S.Context.getPointerType(destPointee);
8347     // Add qualifiers if necessary.
8348     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8349     // Promote to void*.
8350     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8351     return destType;
8352   }
8353 
8354   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8355 }
8356 
8357 /// Return false if the first expression is not an integer and the second
8358 /// expression is not a pointer, true otherwise.
8359 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8360                                         Expr* PointerExpr, SourceLocation Loc,
8361                                         bool IsIntFirstExpr) {
8362   if (!PointerExpr->getType()->isPointerType() ||
8363       !Int.get()->getType()->isIntegerType())
8364     return false;
8365 
8366   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8367   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8368 
8369   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8370     << Expr1->getType() << Expr2->getType()
8371     << Expr1->getSourceRange() << Expr2->getSourceRange();
8372   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8373                             CK_IntegralToPointer);
8374   return true;
8375 }
8376 
8377 /// Simple conversion between integer and floating point types.
8378 ///
8379 /// Used when handling the OpenCL conditional operator where the
8380 /// condition is a vector while the other operands are scalar.
8381 ///
8382 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8383 /// types are either integer or floating type. Between the two
8384 /// operands, the type with the higher rank is defined as the "result
8385 /// type". The other operand needs to be promoted to the same type. No
8386 /// other type promotion is allowed. We cannot use
8387 /// UsualArithmeticConversions() for this purpose, since it always
8388 /// promotes promotable types.
8389 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8390                                             ExprResult &RHS,
8391                                             SourceLocation QuestionLoc) {
8392   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8393   if (LHS.isInvalid())
8394     return QualType();
8395   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8396   if (RHS.isInvalid())
8397     return QualType();
8398 
8399   // For conversion purposes, we ignore any qualifiers.
8400   // For example, "const float" and "float" are equivalent.
8401   QualType LHSType =
8402     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8403   QualType RHSType =
8404     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8405 
8406   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8407     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8408       << LHSType << LHS.get()->getSourceRange();
8409     return QualType();
8410   }
8411 
8412   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8413     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8414       << RHSType << RHS.get()->getSourceRange();
8415     return QualType();
8416   }
8417 
8418   // If both types are identical, no conversion is needed.
8419   if (LHSType == RHSType)
8420     return LHSType;
8421 
8422   // Now handle "real" floating types (i.e. float, double, long double).
8423   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8424     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8425                                  /*IsCompAssign = */ false);
8426 
8427   // Finally, we have two differing integer types.
8428   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8429   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8430 }
8431 
8432 /// Convert scalar operands to a vector that matches the
8433 ///        condition in length.
8434 ///
8435 /// Used when handling the OpenCL conditional operator where the
8436 /// condition is a vector while the other operands are scalar.
8437 ///
8438 /// We first compute the "result type" for the scalar operands
8439 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8440 /// into a vector of that type where the length matches the condition
8441 /// vector type. s6.11.6 requires that the element types of the result
8442 /// and the condition must have the same number of bits.
8443 static QualType
8444 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8445                               QualType CondTy, SourceLocation QuestionLoc) {
8446   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8447   if (ResTy.isNull()) return QualType();
8448 
8449   const VectorType *CV = CondTy->getAs<VectorType>();
8450   assert(CV);
8451 
8452   // Determine the vector result type
8453   unsigned NumElements = CV->getNumElements();
8454   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8455 
8456   // Ensure that all types have the same number of bits
8457   if (S.Context.getTypeSize(CV->getElementType())
8458       != S.Context.getTypeSize(ResTy)) {
8459     // Since VectorTy is created internally, it does not pretty print
8460     // with an OpenCL name. Instead, we just print a description.
8461     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8462     SmallString<64> Str;
8463     llvm::raw_svector_ostream OS(Str);
8464     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8465     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8466       << CondTy << OS.str();
8467     return QualType();
8468   }
8469 
8470   // Convert operands to the vector result type
8471   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8472   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8473 
8474   return VectorTy;
8475 }
8476 
8477 /// Return false if this is a valid OpenCL condition vector
8478 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8479                                        SourceLocation QuestionLoc) {
8480   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8481   // integral type.
8482   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8483   assert(CondTy);
8484   QualType EleTy = CondTy->getElementType();
8485   if (EleTy->isIntegerType()) return false;
8486 
8487   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8488     << Cond->getType() << Cond->getSourceRange();
8489   return true;
8490 }
8491 
8492 /// Return false if the vector condition type and the vector
8493 ///        result type are compatible.
8494 ///
8495 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8496 /// number of elements, and their element types have the same number
8497 /// of bits.
8498 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8499                               SourceLocation QuestionLoc) {
8500   const VectorType *CV = CondTy->getAs<VectorType>();
8501   const VectorType *RV = VecResTy->getAs<VectorType>();
8502   assert(CV && RV);
8503 
8504   if (CV->getNumElements() != RV->getNumElements()) {
8505     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8506       << CondTy << VecResTy;
8507     return true;
8508   }
8509 
8510   QualType CVE = CV->getElementType();
8511   QualType RVE = RV->getElementType();
8512 
8513   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8514     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8515       << CondTy << VecResTy;
8516     return true;
8517   }
8518 
8519   return false;
8520 }
8521 
8522 /// Return the resulting type for the conditional operator in
8523 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8524 ///        s6.3.i) when the condition is a vector type.
8525 static QualType
8526 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8527                              ExprResult &LHS, ExprResult &RHS,
8528                              SourceLocation QuestionLoc) {
8529   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8530   if (Cond.isInvalid())
8531     return QualType();
8532   QualType CondTy = Cond.get()->getType();
8533 
8534   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8535     return QualType();
8536 
8537   // If either operand is a vector then find the vector type of the
8538   // result as specified in OpenCL v1.1 s6.3.i.
8539   if (LHS.get()->getType()->isVectorType() ||
8540       RHS.get()->getType()->isVectorType()) {
8541     bool IsBoolVecLang =
8542         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8543     QualType VecResTy =
8544         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8545                               /*isCompAssign*/ false,
8546                               /*AllowBothBool*/ true,
8547                               /*AllowBoolConversions*/ false,
8548                               /*AllowBooleanOperation*/ IsBoolVecLang,
8549                               /*ReportInvalid*/ true);
8550     if (VecResTy.isNull())
8551       return QualType();
8552     // The result type must match the condition type as specified in
8553     // OpenCL v1.1 s6.11.6.
8554     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8555       return QualType();
8556     return VecResTy;
8557   }
8558 
8559   // Both operands are scalar.
8560   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8561 }
8562 
8563 /// Return true if the Expr is block type
8564 static bool checkBlockType(Sema &S, const Expr *E) {
8565   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8566     QualType Ty = CE->getCallee()->getType();
8567     if (Ty->isBlockPointerType()) {
8568       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8569       return true;
8570     }
8571   }
8572   return false;
8573 }
8574 
8575 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8576 /// In that case, LHS = cond.
8577 /// C99 6.5.15
8578 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8579                                         ExprResult &RHS, ExprValueKind &VK,
8580                                         ExprObjectKind &OK,
8581                                         SourceLocation QuestionLoc) {
8582 
8583   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8584   if (!LHSResult.isUsable()) return QualType();
8585   LHS = LHSResult;
8586 
8587   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8588   if (!RHSResult.isUsable()) return QualType();
8589   RHS = RHSResult;
8590 
8591   // C++ is sufficiently different to merit its own checker.
8592   if (getLangOpts().CPlusPlus)
8593     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8594 
8595   VK = VK_PRValue;
8596   OK = OK_Ordinary;
8597 
8598   if (Context.isDependenceAllowed() &&
8599       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8600        RHS.get()->isTypeDependent())) {
8601     assert(!getLangOpts().CPlusPlus);
8602     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8603             RHS.get()->containsErrors()) &&
8604            "should only occur in error-recovery path.");
8605     return Context.DependentTy;
8606   }
8607 
8608   // The OpenCL operator with a vector condition is sufficiently
8609   // different to merit its own checker.
8610   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8611       Cond.get()->getType()->isExtVectorType())
8612     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8613 
8614   // First, check the condition.
8615   Cond = UsualUnaryConversions(Cond.get());
8616   if (Cond.isInvalid())
8617     return QualType();
8618   if (checkCondition(*this, Cond.get(), QuestionLoc))
8619     return QualType();
8620 
8621   // Now check the two expressions.
8622   if (LHS.get()->getType()->isVectorType() ||
8623       RHS.get()->getType()->isVectorType())
8624     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8625                                /*AllowBothBool*/ true,
8626                                /*AllowBoolConversions*/ false,
8627                                /*AllowBooleanOperation*/ false,
8628                                /*ReportInvalid*/ true);
8629 
8630   QualType ResTy =
8631       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8632   if (LHS.isInvalid() || RHS.isInvalid())
8633     return QualType();
8634 
8635   QualType LHSTy = LHS.get()->getType();
8636   QualType RHSTy = RHS.get()->getType();
8637 
8638   // Diagnose attempts to convert between __ibm128, __float128 and long double
8639   // where such conversions currently can't be handled.
8640   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8641     Diag(QuestionLoc,
8642          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8643       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8644     return QualType();
8645   }
8646 
8647   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8648   // selection operator (?:).
8649   if (getLangOpts().OpenCL &&
8650       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8651     return QualType();
8652   }
8653 
8654   // If both operands have arithmetic type, do the usual arithmetic conversions
8655   // to find a common type: C99 6.5.15p3,5.
8656   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8657     // Disallow invalid arithmetic conversions, such as those between bit-
8658     // precise integers types of different sizes, or between a bit-precise
8659     // integer and another type.
8660     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8661       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8662           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8663           << RHS.get()->getSourceRange();
8664       return QualType();
8665     }
8666 
8667     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8668     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8669 
8670     return ResTy;
8671   }
8672 
8673   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8674   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8675     return LHSTy;
8676   }
8677 
8678   // If both operands are the same structure or union type, the result is that
8679   // type.
8680   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8681     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8682       if (LHSRT->getDecl() == RHSRT->getDecl())
8683         // "If both the operands have structure or union type, the result has
8684         // that type."  This implies that CV qualifiers are dropped.
8685         return LHSTy.getUnqualifiedType();
8686     // FIXME: Type of conditional expression must be complete in C mode.
8687   }
8688 
8689   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8690   // The following || allows only one side to be void (a GCC-ism).
8691   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8692     return checkConditionalVoidType(*this, LHS, RHS);
8693   }
8694 
8695   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8696   // the type of the other operand."
8697   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8698   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8699 
8700   // All objective-c pointer type analysis is done here.
8701   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8702                                                         QuestionLoc);
8703   if (LHS.isInvalid() || RHS.isInvalid())
8704     return QualType();
8705   if (!compositeType.isNull())
8706     return compositeType;
8707 
8708 
8709   // Handle block pointer types.
8710   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8711     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8712                                                      QuestionLoc);
8713 
8714   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8715   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8716     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8717                                                        QuestionLoc);
8718 
8719   // GCC compatibility: soften pointer/integer mismatch.  Note that
8720   // null pointers have been filtered out by this point.
8721   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8722       /*IsIntFirstExpr=*/true))
8723     return RHSTy;
8724   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8725       /*IsIntFirstExpr=*/false))
8726     return LHSTy;
8727 
8728   // Allow ?: operations in which both operands have the same
8729   // built-in sizeless type.
8730   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8731     return LHSTy;
8732 
8733   // Emit a better diagnostic if one of the expressions is a null pointer
8734   // constant and the other is not a pointer type. In this case, the user most
8735   // likely forgot to take the address of the other expression.
8736   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8737     return QualType();
8738 
8739   // Otherwise, the operands are not compatible.
8740   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8741     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8742     << RHS.get()->getSourceRange();
8743   return QualType();
8744 }
8745 
8746 /// FindCompositeObjCPointerType - Helper method to find composite type of
8747 /// two objective-c pointer types of the two input expressions.
8748 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8749                                             SourceLocation QuestionLoc) {
8750   QualType LHSTy = LHS.get()->getType();
8751   QualType RHSTy = RHS.get()->getType();
8752 
8753   // Handle things like Class and struct objc_class*.  Here we case the result
8754   // to the pseudo-builtin, because that will be implicitly cast back to the
8755   // redefinition type if an attempt is made to access its fields.
8756   if (LHSTy->isObjCClassType() &&
8757       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8758     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8759     return LHSTy;
8760   }
8761   if (RHSTy->isObjCClassType() &&
8762       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8763     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8764     return RHSTy;
8765   }
8766   // And the same for struct objc_object* / id
8767   if (LHSTy->isObjCIdType() &&
8768       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8769     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8770     return LHSTy;
8771   }
8772   if (RHSTy->isObjCIdType() &&
8773       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8774     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8775     return RHSTy;
8776   }
8777   // And the same for struct objc_selector* / SEL
8778   if (Context.isObjCSelType(LHSTy) &&
8779       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8780     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8781     return LHSTy;
8782   }
8783   if (Context.isObjCSelType(RHSTy) &&
8784       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8785     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8786     return RHSTy;
8787   }
8788   // Check constraints for Objective-C object pointers types.
8789   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8790 
8791     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8792       // Two identical object pointer types are always compatible.
8793       return LHSTy;
8794     }
8795     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8796     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8797     QualType compositeType = LHSTy;
8798 
8799     // If both operands are interfaces and either operand can be
8800     // assigned to the other, use that type as the composite
8801     // type. This allows
8802     //   xxx ? (A*) a : (B*) b
8803     // where B is a subclass of A.
8804     //
8805     // Additionally, as for assignment, if either type is 'id'
8806     // allow silent coercion. Finally, if the types are
8807     // incompatible then make sure to use 'id' as the composite
8808     // type so the result is acceptable for sending messages to.
8809 
8810     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8811     // It could return the composite type.
8812     if (!(compositeType =
8813           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8814       // Nothing more to do.
8815     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8816       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8817     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8818       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8819     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8820                 RHSOPT->isObjCQualifiedIdType()) &&
8821                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8822                                                          true)) {
8823       // Need to handle "id<xx>" explicitly.
8824       // GCC allows qualified id and any Objective-C type to devolve to
8825       // id. Currently localizing to here until clear this should be
8826       // part of ObjCQualifiedIdTypesAreCompatible.
8827       compositeType = Context.getObjCIdType();
8828     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8829       compositeType = Context.getObjCIdType();
8830     } else {
8831       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8832       << LHSTy << RHSTy
8833       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8834       QualType incompatTy = Context.getObjCIdType();
8835       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8836       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8837       return incompatTy;
8838     }
8839     // The object pointer types are compatible.
8840     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8841     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8842     return compositeType;
8843   }
8844   // Check Objective-C object pointer types and 'void *'
8845   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8846     if (getLangOpts().ObjCAutoRefCount) {
8847       // ARC forbids the implicit conversion of object pointers to 'void *',
8848       // so these types are not compatible.
8849       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8850           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8851       LHS = RHS = true;
8852       return QualType();
8853     }
8854     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8855     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8856     QualType destPointee
8857     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8858     QualType destType = Context.getPointerType(destPointee);
8859     // Add qualifiers if necessary.
8860     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8861     // Promote to void*.
8862     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8863     return destType;
8864   }
8865   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8866     if (getLangOpts().ObjCAutoRefCount) {
8867       // ARC forbids the implicit conversion of object pointers to 'void *',
8868       // so these types are not compatible.
8869       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8870           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8871       LHS = RHS = true;
8872       return QualType();
8873     }
8874     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8875     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8876     QualType destPointee
8877     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8878     QualType destType = Context.getPointerType(destPointee);
8879     // Add qualifiers if necessary.
8880     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8881     // Promote to void*.
8882     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8883     return destType;
8884   }
8885   return QualType();
8886 }
8887 
8888 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8889 /// ParenRange in parentheses.
8890 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8891                                const PartialDiagnostic &Note,
8892                                SourceRange ParenRange) {
8893   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8894   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8895       EndLoc.isValid()) {
8896     Self.Diag(Loc, Note)
8897       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8898       << FixItHint::CreateInsertion(EndLoc, ")");
8899   } else {
8900     // We can't display the parentheses, so just show the bare note.
8901     Self.Diag(Loc, Note) << ParenRange;
8902   }
8903 }
8904 
8905 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8906   return BinaryOperator::isAdditiveOp(Opc) ||
8907          BinaryOperator::isMultiplicativeOp(Opc) ||
8908          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8909   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8910   // not any of the logical operators.  Bitwise-xor is commonly used as a
8911   // logical-xor because there is no logical-xor operator.  The logical
8912   // operators, including uses of xor, have a high false positive rate for
8913   // precedence warnings.
8914 }
8915 
8916 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8917 /// expression, either using a built-in or overloaded operator,
8918 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8919 /// expression.
8920 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8921                                    Expr **RHSExprs) {
8922   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8923   E = E->IgnoreImpCasts();
8924   E = E->IgnoreConversionOperatorSingleStep();
8925   E = E->IgnoreImpCasts();
8926   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8927     E = MTE->getSubExpr();
8928     E = E->IgnoreImpCasts();
8929   }
8930 
8931   // Built-in binary operator.
8932   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8933     if (IsArithmeticOp(OP->getOpcode())) {
8934       *Opcode = OP->getOpcode();
8935       *RHSExprs = OP->getRHS();
8936       return true;
8937     }
8938   }
8939 
8940   // Overloaded operator.
8941   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8942     if (Call->getNumArgs() != 2)
8943       return false;
8944 
8945     // Make sure this is really a binary operator that is safe to pass into
8946     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8947     OverloadedOperatorKind OO = Call->getOperator();
8948     if (OO < OO_Plus || OO > OO_Arrow ||
8949         OO == OO_PlusPlus || OO == OO_MinusMinus)
8950       return false;
8951 
8952     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8953     if (IsArithmeticOp(OpKind)) {
8954       *Opcode = OpKind;
8955       *RHSExprs = Call->getArg(1);
8956       return true;
8957     }
8958   }
8959 
8960   return false;
8961 }
8962 
8963 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8964 /// or is a logical expression such as (x==y) which has int type, but is
8965 /// commonly interpreted as boolean.
8966 static bool ExprLooksBoolean(Expr *E) {
8967   E = E->IgnoreParenImpCasts();
8968 
8969   if (E->getType()->isBooleanType())
8970     return true;
8971   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8972     return OP->isComparisonOp() || OP->isLogicalOp();
8973   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8974     return OP->getOpcode() == UO_LNot;
8975   if (E->getType()->isPointerType())
8976     return true;
8977   // FIXME: What about overloaded operator calls returning "unspecified boolean
8978   // type"s (commonly pointer-to-members)?
8979 
8980   return false;
8981 }
8982 
8983 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8984 /// and binary operator are mixed in a way that suggests the programmer assumed
8985 /// the conditional operator has higher precedence, for example:
8986 /// "int x = a + someBinaryCondition ? 1 : 2".
8987 static void DiagnoseConditionalPrecedence(Sema &Self,
8988                                           SourceLocation OpLoc,
8989                                           Expr *Condition,
8990                                           Expr *LHSExpr,
8991                                           Expr *RHSExpr) {
8992   BinaryOperatorKind CondOpcode;
8993   Expr *CondRHS;
8994 
8995   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8996     return;
8997   if (!ExprLooksBoolean(CondRHS))
8998     return;
8999 
9000   // The condition is an arithmetic binary expression, with a right-
9001   // hand side that looks boolean, so warn.
9002 
9003   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9004                         ? diag::warn_precedence_bitwise_conditional
9005                         : diag::warn_precedence_conditional;
9006 
9007   Self.Diag(OpLoc, DiagID)
9008       << Condition->getSourceRange()
9009       << BinaryOperator::getOpcodeStr(CondOpcode);
9010 
9011   SuggestParentheses(
9012       Self, OpLoc,
9013       Self.PDiag(diag::note_precedence_silence)
9014           << BinaryOperator::getOpcodeStr(CondOpcode),
9015       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9016 
9017   SuggestParentheses(Self, OpLoc,
9018                      Self.PDiag(diag::note_precedence_conditional_first),
9019                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9020 }
9021 
9022 /// Compute the nullability of a conditional expression.
9023 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9024                                               QualType LHSTy, QualType RHSTy,
9025                                               ASTContext &Ctx) {
9026   if (!ResTy->isAnyPointerType())
9027     return ResTy;
9028 
9029   auto GetNullability = [&Ctx](QualType Ty) {
9030     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9031     if (Kind) {
9032       // For our purposes, treat _Nullable_result as _Nullable.
9033       if (*Kind == NullabilityKind::NullableResult)
9034         return NullabilityKind::Nullable;
9035       return *Kind;
9036     }
9037     return NullabilityKind::Unspecified;
9038   };
9039 
9040   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9041   NullabilityKind MergedKind;
9042 
9043   // Compute nullability of a binary conditional expression.
9044   if (IsBin) {
9045     if (LHSKind == NullabilityKind::NonNull)
9046       MergedKind = NullabilityKind::NonNull;
9047     else
9048       MergedKind = RHSKind;
9049   // Compute nullability of a normal conditional expression.
9050   } else {
9051     if (LHSKind == NullabilityKind::Nullable ||
9052         RHSKind == NullabilityKind::Nullable)
9053       MergedKind = NullabilityKind::Nullable;
9054     else if (LHSKind == NullabilityKind::NonNull)
9055       MergedKind = RHSKind;
9056     else if (RHSKind == NullabilityKind::NonNull)
9057       MergedKind = LHSKind;
9058     else
9059       MergedKind = NullabilityKind::Unspecified;
9060   }
9061 
9062   // Return if ResTy already has the correct nullability.
9063   if (GetNullability(ResTy) == MergedKind)
9064     return ResTy;
9065 
9066   // Strip all nullability from ResTy.
9067   while (ResTy->getNullability(Ctx))
9068     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9069 
9070   // Create a new AttributedType with the new nullability kind.
9071   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9072   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9073 }
9074 
9075 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
9076 /// in the case of a the GNU conditional expr extension.
9077 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9078                                     SourceLocation ColonLoc,
9079                                     Expr *CondExpr, Expr *LHSExpr,
9080                                     Expr *RHSExpr) {
9081   if (!Context.isDependenceAllowed()) {
9082     // C cannot handle TypoExpr nodes in the condition because it
9083     // doesn't handle dependent types properly, so make sure any TypoExprs have
9084     // been dealt with before checking the operands.
9085     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9086     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9087     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9088 
9089     if (!CondResult.isUsable())
9090       return ExprError();
9091 
9092     if (LHSExpr) {
9093       if (!LHSResult.isUsable())
9094         return ExprError();
9095     }
9096 
9097     if (!RHSResult.isUsable())
9098       return ExprError();
9099 
9100     CondExpr = CondResult.get();
9101     LHSExpr = LHSResult.get();
9102     RHSExpr = RHSResult.get();
9103   }
9104 
9105   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9106   // was the condition.
9107   OpaqueValueExpr *opaqueValue = nullptr;
9108   Expr *commonExpr = nullptr;
9109   if (!LHSExpr) {
9110     commonExpr = CondExpr;
9111     // Lower out placeholder types first.  This is important so that we don't
9112     // try to capture a placeholder. This happens in few cases in C++; such
9113     // as Objective-C++'s dictionary subscripting syntax.
9114     if (commonExpr->hasPlaceholderType()) {
9115       ExprResult result = CheckPlaceholderExpr(commonExpr);
9116       if (!result.isUsable()) return ExprError();
9117       commonExpr = result.get();
9118     }
9119     // We usually want to apply unary conversions *before* saving, except
9120     // in the special case of a C++ l-value conditional.
9121     if (!(getLangOpts().CPlusPlus
9122           && !commonExpr->isTypeDependent()
9123           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9124           && commonExpr->isGLValue()
9125           && commonExpr->isOrdinaryOrBitFieldObject()
9126           && RHSExpr->isOrdinaryOrBitFieldObject()
9127           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9128       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9129       if (commonRes.isInvalid())
9130         return ExprError();
9131       commonExpr = commonRes.get();
9132     }
9133 
9134     // If the common expression is a class or array prvalue, materialize it
9135     // so that we can safely refer to it multiple times.
9136     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9137                                     commonExpr->getType()->isArrayType())) {
9138       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9139       if (MatExpr.isInvalid())
9140         return ExprError();
9141       commonExpr = MatExpr.get();
9142     }
9143 
9144     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9145                                                 commonExpr->getType(),
9146                                                 commonExpr->getValueKind(),
9147                                                 commonExpr->getObjectKind(),
9148                                                 commonExpr);
9149     LHSExpr = CondExpr = opaqueValue;
9150   }
9151 
9152   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9153   ExprValueKind VK = VK_PRValue;
9154   ExprObjectKind OK = OK_Ordinary;
9155   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9156   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9157                                              VK, OK, QuestionLoc);
9158   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9159       RHS.isInvalid())
9160     return ExprError();
9161 
9162   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9163                                 RHS.get());
9164 
9165   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9166 
9167   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9168                                          Context);
9169 
9170   if (!commonExpr)
9171     return new (Context)
9172         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9173                             RHS.get(), result, VK, OK);
9174 
9175   return new (Context) BinaryConditionalOperator(
9176       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9177       ColonLoc, result, VK, OK);
9178 }
9179 
9180 // Check if we have a conversion between incompatible cmse function pointer
9181 // types, that is, a conversion between a function pointer with the
9182 // cmse_nonsecure_call attribute and one without.
9183 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9184                                           QualType ToType) {
9185   if (const auto *ToFn =
9186           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9187     if (const auto *FromFn =
9188             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9189       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9190       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9191 
9192       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9193     }
9194   }
9195   return false;
9196 }
9197 
9198 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9199 // being closely modeled after the C99 spec:-). The odd characteristic of this
9200 // routine is it effectively iqnores the qualifiers on the top level pointee.
9201 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9202 // FIXME: add a couple examples in this comment.
9203 static Sema::AssignConvertType
9204 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9205   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9206   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9207 
9208   // get the "pointed to" type (ignoring qualifiers at the top level)
9209   const Type *lhptee, *rhptee;
9210   Qualifiers lhq, rhq;
9211   std::tie(lhptee, lhq) =
9212       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9213   std::tie(rhptee, rhq) =
9214       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9215 
9216   Sema::AssignConvertType ConvTy = Sema::Compatible;
9217 
9218   // C99 6.5.16.1p1: This following citation is common to constraints
9219   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9220   // qualifiers of the type *pointed to* by the right;
9221 
9222   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9223   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9224       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9225     // Ignore lifetime for further calculation.
9226     lhq.removeObjCLifetime();
9227     rhq.removeObjCLifetime();
9228   }
9229 
9230   if (!lhq.compatiblyIncludes(rhq)) {
9231     // Treat address-space mismatches as fatal.
9232     if (!lhq.isAddressSpaceSupersetOf(rhq))
9233       return Sema::IncompatiblePointerDiscardsQualifiers;
9234 
9235     // It's okay to add or remove GC or lifetime qualifiers when converting to
9236     // and from void*.
9237     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9238                         .compatiblyIncludes(
9239                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9240              && (lhptee->isVoidType() || rhptee->isVoidType()))
9241       ; // keep old
9242 
9243     // Treat lifetime mismatches as fatal.
9244     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9245       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9246 
9247     // For GCC/MS compatibility, other qualifier mismatches are treated
9248     // as still compatible in C.
9249     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9250   }
9251 
9252   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9253   // incomplete type and the other is a pointer to a qualified or unqualified
9254   // version of void...
9255   if (lhptee->isVoidType()) {
9256     if (rhptee->isIncompleteOrObjectType())
9257       return ConvTy;
9258 
9259     // As an extension, we allow cast to/from void* to function pointer.
9260     assert(rhptee->isFunctionType());
9261     return Sema::FunctionVoidPointer;
9262   }
9263 
9264   if (rhptee->isVoidType()) {
9265     if (lhptee->isIncompleteOrObjectType())
9266       return ConvTy;
9267 
9268     // As an extension, we allow cast to/from void* to function pointer.
9269     assert(lhptee->isFunctionType());
9270     return Sema::FunctionVoidPointer;
9271   }
9272 
9273   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9274   // unqualified versions of compatible types, ...
9275   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9276   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9277     // Check if the pointee types are compatible ignoring the sign.
9278     // We explicitly check for char so that we catch "char" vs
9279     // "unsigned char" on systems where "char" is unsigned.
9280     if (lhptee->isCharType())
9281       ltrans = S.Context.UnsignedCharTy;
9282     else if (lhptee->hasSignedIntegerRepresentation())
9283       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9284 
9285     if (rhptee->isCharType())
9286       rtrans = S.Context.UnsignedCharTy;
9287     else if (rhptee->hasSignedIntegerRepresentation())
9288       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9289 
9290     if (ltrans == rtrans) {
9291       // Types are compatible ignoring the sign. Qualifier incompatibility
9292       // takes priority over sign incompatibility because the sign
9293       // warning can be disabled.
9294       if (ConvTy != Sema::Compatible)
9295         return ConvTy;
9296 
9297       return Sema::IncompatiblePointerSign;
9298     }
9299 
9300     // If we are a multi-level pointer, it's possible that our issue is simply
9301     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9302     // the eventual target type is the same and the pointers have the same
9303     // level of indirection, this must be the issue.
9304     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9305       do {
9306         std::tie(lhptee, lhq) =
9307           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9308         std::tie(rhptee, rhq) =
9309           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9310 
9311         // Inconsistent address spaces at this point is invalid, even if the
9312         // address spaces would be compatible.
9313         // FIXME: This doesn't catch address space mismatches for pointers of
9314         // different nesting levels, like:
9315         //   __local int *** a;
9316         //   int ** b = a;
9317         // It's not clear how to actually determine when such pointers are
9318         // invalidly incompatible.
9319         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9320           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9321 
9322       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9323 
9324       if (lhptee == rhptee)
9325         return Sema::IncompatibleNestedPointerQualifiers;
9326     }
9327 
9328     // General pointer incompatibility takes priority over qualifiers.
9329     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9330       return Sema::IncompatibleFunctionPointer;
9331     return Sema::IncompatiblePointer;
9332   }
9333   if (!S.getLangOpts().CPlusPlus &&
9334       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9335     return Sema::IncompatibleFunctionPointer;
9336   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9337     return Sema::IncompatibleFunctionPointer;
9338   return ConvTy;
9339 }
9340 
9341 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9342 /// block pointer types are compatible or whether a block and normal pointer
9343 /// are compatible. It is more restrict than comparing two function pointer
9344 // types.
9345 static Sema::AssignConvertType
9346 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9347                                     QualType RHSType) {
9348   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9349   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9350 
9351   QualType lhptee, rhptee;
9352 
9353   // get the "pointed to" type (ignoring qualifiers at the top level)
9354   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9355   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9356 
9357   // In C++, the types have to match exactly.
9358   if (S.getLangOpts().CPlusPlus)
9359     return Sema::IncompatibleBlockPointer;
9360 
9361   Sema::AssignConvertType ConvTy = Sema::Compatible;
9362 
9363   // For blocks we enforce that qualifiers are identical.
9364   Qualifiers LQuals = lhptee.getLocalQualifiers();
9365   Qualifiers RQuals = rhptee.getLocalQualifiers();
9366   if (S.getLangOpts().OpenCL) {
9367     LQuals.removeAddressSpace();
9368     RQuals.removeAddressSpace();
9369   }
9370   if (LQuals != RQuals)
9371     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9372 
9373   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9374   // assignment.
9375   // The current behavior is similar to C++ lambdas. A block might be
9376   // assigned to a variable iff its return type and parameters are compatible
9377   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9378   // an assignment. Presumably it should behave in way that a function pointer
9379   // assignment does in C, so for each parameter and return type:
9380   //  * CVR and address space of LHS should be a superset of CVR and address
9381   //  space of RHS.
9382   //  * unqualified types should be compatible.
9383   if (S.getLangOpts().OpenCL) {
9384     if (!S.Context.typesAreBlockPointerCompatible(
9385             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9386             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9387       return Sema::IncompatibleBlockPointer;
9388   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9389     return Sema::IncompatibleBlockPointer;
9390 
9391   return ConvTy;
9392 }
9393 
9394 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9395 /// for assignment compatibility.
9396 static Sema::AssignConvertType
9397 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9398                                    QualType RHSType) {
9399   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9400   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9401 
9402   if (LHSType->isObjCBuiltinType()) {
9403     // Class is not compatible with ObjC object pointers.
9404     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9405         !RHSType->isObjCQualifiedClassType())
9406       return Sema::IncompatiblePointer;
9407     return Sema::Compatible;
9408   }
9409   if (RHSType->isObjCBuiltinType()) {
9410     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9411         !LHSType->isObjCQualifiedClassType())
9412       return Sema::IncompatiblePointer;
9413     return Sema::Compatible;
9414   }
9415   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9416   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9417 
9418   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9419       // make an exception for id<P>
9420       !LHSType->isObjCQualifiedIdType())
9421     return Sema::CompatiblePointerDiscardsQualifiers;
9422 
9423   if (S.Context.typesAreCompatible(LHSType, RHSType))
9424     return Sema::Compatible;
9425   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9426     return Sema::IncompatibleObjCQualifiedId;
9427   return Sema::IncompatiblePointer;
9428 }
9429 
9430 Sema::AssignConvertType
9431 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9432                                  QualType LHSType, QualType RHSType) {
9433   // Fake up an opaque expression.  We don't actually care about what
9434   // cast operations are required, so if CheckAssignmentConstraints
9435   // adds casts to this they'll be wasted, but fortunately that doesn't
9436   // usually happen on valid code.
9437   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9438   ExprResult RHSPtr = &RHSExpr;
9439   CastKind K;
9440 
9441   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9442 }
9443 
9444 /// This helper function returns true if QT is a vector type that has element
9445 /// type ElementType.
9446 static bool isVector(QualType QT, QualType ElementType) {
9447   if (const VectorType *VT = QT->getAs<VectorType>())
9448     return VT->getElementType().getCanonicalType() == ElementType;
9449   return false;
9450 }
9451 
9452 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9453 /// has code to accommodate several GCC extensions when type checking
9454 /// pointers. Here are some objectionable examples that GCC considers warnings:
9455 ///
9456 ///  int a, *pint;
9457 ///  short *pshort;
9458 ///  struct foo *pfoo;
9459 ///
9460 ///  pint = pshort; // warning: assignment from incompatible pointer type
9461 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9462 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9463 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9464 ///
9465 /// As a result, the code for dealing with pointers is more complex than the
9466 /// C99 spec dictates.
9467 ///
9468 /// Sets 'Kind' for any result kind except Incompatible.
9469 Sema::AssignConvertType
9470 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9471                                  CastKind &Kind, bool ConvertRHS) {
9472   QualType RHSType = RHS.get()->getType();
9473   QualType OrigLHSType = LHSType;
9474 
9475   // Get canonical types.  We're not formatting these types, just comparing
9476   // them.
9477   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9478   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9479 
9480   // Common case: no conversion required.
9481   if (LHSType == RHSType) {
9482     Kind = CK_NoOp;
9483     return Compatible;
9484   }
9485 
9486   // If the LHS has an __auto_type, there are no additional type constraints
9487   // to be worried about.
9488   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9489     if (AT->isGNUAutoType()) {
9490       Kind = CK_NoOp;
9491       return Compatible;
9492     }
9493   }
9494 
9495   // If we have an atomic type, try a non-atomic assignment, then just add an
9496   // atomic qualification step.
9497   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9498     Sema::AssignConvertType result =
9499       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9500     if (result != Compatible)
9501       return result;
9502     if (Kind != CK_NoOp && ConvertRHS)
9503       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9504     Kind = CK_NonAtomicToAtomic;
9505     return Compatible;
9506   }
9507 
9508   // If the left-hand side is a reference type, then we are in a
9509   // (rare!) case where we've allowed the use of references in C,
9510   // e.g., as a parameter type in a built-in function. In this case,
9511   // just make sure that the type referenced is compatible with the
9512   // right-hand side type. The caller is responsible for adjusting
9513   // LHSType so that the resulting expression does not have reference
9514   // type.
9515   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9516     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9517       Kind = CK_LValueBitCast;
9518       return Compatible;
9519     }
9520     return Incompatible;
9521   }
9522 
9523   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9524   // to the same ExtVector type.
9525   if (LHSType->isExtVectorType()) {
9526     if (RHSType->isExtVectorType())
9527       return Incompatible;
9528     if (RHSType->isArithmeticType()) {
9529       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9530       if (ConvertRHS)
9531         RHS = prepareVectorSplat(LHSType, RHS.get());
9532       Kind = CK_VectorSplat;
9533       return Compatible;
9534     }
9535   }
9536 
9537   // Conversions to or from vector type.
9538   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9539     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9540       // Allow assignments of an AltiVec vector type to an equivalent GCC
9541       // vector type and vice versa
9542       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9543         Kind = CK_BitCast;
9544         return Compatible;
9545       }
9546 
9547       // If we are allowing lax vector conversions, and LHS and RHS are both
9548       // vectors, the total size only needs to be the same. This is a bitcast;
9549       // no bits are changed but the result type is different.
9550       if (isLaxVectorConversion(RHSType, LHSType)) {
9551         Kind = CK_BitCast;
9552         return IncompatibleVectors;
9553       }
9554     }
9555 
9556     // When the RHS comes from another lax conversion (e.g. binops between
9557     // scalars and vectors) the result is canonicalized as a vector. When the
9558     // LHS is also a vector, the lax is allowed by the condition above. Handle
9559     // the case where LHS is a scalar.
9560     if (LHSType->isScalarType()) {
9561       const VectorType *VecType = RHSType->getAs<VectorType>();
9562       if (VecType && VecType->getNumElements() == 1 &&
9563           isLaxVectorConversion(RHSType, LHSType)) {
9564         ExprResult *VecExpr = &RHS;
9565         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9566         Kind = CK_BitCast;
9567         return Compatible;
9568       }
9569     }
9570 
9571     // Allow assignments between fixed-length and sizeless SVE vectors.
9572     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9573         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9574       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9575           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9576         Kind = CK_BitCast;
9577         return Compatible;
9578       }
9579 
9580     return Incompatible;
9581   }
9582 
9583   // Diagnose attempts to convert between __ibm128, __float128 and long double
9584   // where such conversions currently can't be handled.
9585   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9586     return Incompatible;
9587 
9588   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9589   // discards the imaginary part.
9590   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9591       !LHSType->getAs<ComplexType>())
9592     return Incompatible;
9593 
9594   // Arithmetic conversions.
9595   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9596       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9597     if (ConvertRHS)
9598       Kind = PrepareScalarCast(RHS, LHSType);
9599     return Compatible;
9600   }
9601 
9602   // Conversions to normal pointers.
9603   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9604     // U* -> T*
9605     if (isa<PointerType>(RHSType)) {
9606       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9607       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9608       if (AddrSpaceL != AddrSpaceR)
9609         Kind = CK_AddressSpaceConversion;
9610       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9611         Kind = CK_NoOp;
9612       else
9613         Kind = CK_BitCast;
9614       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9615     }
9616 
9617     // int -> T*
9618     if (RHSType->isIntegerType()) {
9619       Kind = CK_IntegralToPointer; // FIXME: null?
9620       return IntToPointer;
9621     }
9622 
9623     // C pointers are not compatible with ObjC object pointers,
9624     // with two exceptions:
9625     if (isa<ObjCObjectPointerType>(RHSType)) {
9626       //  - conversions to void*
9627       if (LHSPointer->getPointeeType()->isVoidType()) {
9628         Kind = CK_BitCast;
9629         return Compatible;
9630       }
9631 
9632       //  - conversions from 'Class' to the redefinition type
9633       if (RHSType->isObjCClassType() &&
9634           Context.hasSameType(LHSType,
9635                               Context.getObjCClassRedefinitionType())) {
9636         Kind = CK_BitCast;
9637         return Compatible;
9638       }
9639 
9640       Kind = CK_BitCast;
9641       return IncompatiblePointer;
9642     }
9643 
9644     // U^ -> void*
9645     if (RHSType->getAs<BlockPointerType>()) {
9646       if (LHSPointer->getPointeeType()->isVoidType()) {
9647         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9648         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9649                                 ->getPointeeType()
9650                                 .getAddressSpace();
9651         Kind =
9652             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9653         return Compatible;
9654       }
9655     }
9656 
9657     return Incompatible;
9658   }
9659 
9660   // Conversions to block pointers.
9661   if (isa<BlockPointerType>(LHSType)) {
9662     // U^ -> T^
9663     if (RHSType->isBlockPointerType()) {
9664       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9665                               ->getPointeeType()
9666                               .getAddressSpace();
9667       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9668                               ->getPointeeType()
9669                               .getAddressSpace();
9670       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9671       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9672     }
9673 
9674     // int or null -> T^
9675     if (RHSType->isIntegerType()) {
9676       Kind = CK_IntegralToPointer; // FIXME: null
9677       return IntToBlockPointer;
9678     }
9679 
9680     // id -> T^
9681     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9682       Kind = CK_AnyPointerToBlockPointerCast;
9683       return Compatible;
9684     }
9685 
9686     // void* -> T^
9687     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9688       if (RHSPT->getPointeeType()->isVoidType()) {
9689         Kind = CK_AnyPointerToBlockPointerCast;
9690         return Compatible;
9691       }
9692 
9693     return Incompatible;
9694   }
9695 
9696   // Conversions to Objective-C pointers.
9697   if (isa<ObjCObjectPointerType>(LHSType)) {
9698     // A* -> B*
9699     if (RHSType->isObjCObjectPointerType()) {
9700       Kind = CK_BitCast;
9701       Sema::AssignConvertType result =
9702         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9703       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9704           result == Compatible &&
9705           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9706         result = IncompatibleObjCWeakRef;
9707       return result;
9708     }
9709 
9710     // int or null -> A*
9711     if (RHSType->isIntegerType()) {
9712       Kind = CK_IntegralToPointer; // FIXME: null
9713       return IntToPointer;
9714     }
9715 
9716     // In general, C pointers are not compatible with ObjC object pointers,
9717     // with two exceptions:
9718     if (isa<PointerType>(RHSType)) {
9719       Kind = CK_CPointerToObjCPointerCast;
9720 
9721       //  - conversions from 'void*'
9722       if (RHSType->isVoidPointerType()) {
9723         return Compatible;
9724       }
9725 
9726       //  - conversions to 'Class' from its redefinition type
9727       if (LHSType->isObjCClassType() &&
9728           Context.hasSameType(RHSType,
9729                               Context.getObjCClassRedefinitionType())) {
9730         return Compatible;
9731       }
9732 
9733       return IncompatiblePointer;
9734     }
9735 
9736     // Only under strict condition T^ is compatible with an Objective-C pointer.
9737     if (RHSType->isBlockPointerType() &&
9738         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9739       if (ConvertRHS)
9740         maybeExtendBlockObject(RHS);
9741       Kind = CK_BlockPointerToObjCPointerCast;
9742       return Compatible;
9743     }
9744 
9745     return Incompatible;
9746   }
9747 
9748   // Conversions from pointers that are not covered by the above.
9749   if (isa<PointerType>(RHSType)) {
9750     // T* -> _Bool
9751     if (LHSType == Context.BoolTy) {
9752       Kind = CK_PointerToBoolean;
9753       return Compatible;
9754     }
9755 
9756     // T* -> int
9757     if (LHSType->isIntegerType()) {
9758       Kind = CK_PointerToIntegral;
9759       return PointerToInt;
9760     }
9761 
9762     return Incompatible;
9763   }
9764 
9765   // Conversions from Objective-C pointers that are not covered by the above.
9766   if (isa<ObjCObjectPointerType>(RHSType)) {
9767     // T* -> _Bool
9768     if (LHSType == Context.BoolTy) {
9769       Kind = CK_PointerToBoolean;
9770       return Compatible;
9771     }
9772 
9773     // T* -> int
9774     if (LHSType->isIntegerType()) {
9775       Kind = CK_PointerToIntegral;
9776       return PointerToInt;
9777     }
9778 
9779     return Incompatible;
9780   }
9781 
9782   // struct A -> struct B
9783   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9784     if (Context.typesAreCompatible(LHSType, RHSType)) {
9785       Kind = CK_NoOp;
9786       return Compatible;
9787     }
9788   }
9789 
9790   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9791     Kind = CK_IntToOCLSampler;
9792     return Compatible;
9793   }
9794 
9795   return Incompatible;
9796 }
9797 
9798 /// Constructs a transparent union from an expression that is
9799 /// used to initialize the transparent union.
9800 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9801                                       ExprResult &EResult, QualType UnionType,
9802                                       FieldDecl *Field) {
9803   // Build an initializer list that designates the appropriate member
9804   // of the transparent union.
9805   Expr *E = EResult.get();
9806   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9807                                                    E, SourceLocation());
9808   Initializer->setType(UnionType);
9809   Initializer->setInitializedFieldInUnion(Field);
9810 
9811   // Build a compound literal constructing a value of the transparent
9812   // union type from this initializer list.
9813   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9814   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9815                                         VK_PRValue, Initializer, false);
9816 }
9817 
9818 Sema::AssignConvertType
9819 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9820                                                ExprResult &RHS) {
9821   QualType RHSType = RHS.get()->getType();
9822 
9823   // If the ArgType is a Union type, we want to handle a potential
9824   // transparent_union GCC extension.
9825   const RecordType *UT = ArgType->getAsUnionType();
9826   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9827     return Incompatible;
9828 
9829   // The field to initialize within the transparent union.
9830   RecordDecl *UD = UT->getDecl();
9831   FieldDecl *InitField = nullptr;
9832   // It's compatible if the expression matches any of the fields.
9833   for (auto *it : UD->fields()) {
9834     if (it->getType()->isPointerType()) {
9835       // If the transparent union contains a pointer type, we allow:
9836       // 1) void pointer
9837       // 2) null pointer constant
9838       if (RHSType->isPointerType())
9839         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9840           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9841           InitField = it;
9842           break;
9843         }
9844 
9845       if (RHS.get()->isNullPointerConstant(Context,
9846                                            Expr::NPC_ValueDependentIsNull)) {
9847         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9848                                 CK_NullToPointer);
9849         InitField = it;
9850         break;
9851       }
9852     }
9853 
9854     CastKind Kind;
9855     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9856           == Compatible) {
9857       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9858       InitField = it;
9859       break;
9860     }
9861   }
9862 
9863   if (!InitField)
9864     return Incompatible;
9865 
9866   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9867   return Compatible;
9868 }
9869 
9870 Sema::AssignConvertType
9871 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9872                                        bool Diagnose,
9873                                        bool DiagnoseCFAudited,
9874                                        bool ConvertRHS) {
9875   // We need to be able to tell the caller whether we diagnosed a problem, if
9876   // they ask us to issue diagnostics.
9877   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9878 
9879   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9880   // we can't avoid *all* modifications at the moment, so we need some somewhere
9881   // to put the updated value.
9882   ExprResult LocalRHS = CallerRHS;
9883   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9884 
9885   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9886     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9887       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9888           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9889         Diag(RHS.get()->getExprLoc(),
9890              diag::warn_noderef_to_dereferenceable_pointer)
9891             << RHS.get()->getSourceRange();
9892       }
9893     }
9894   }
9895 
9896   if (getLangOpts().CPlusPlus) {
9897     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9898       // C++ 5.17p3: If the left operand is not of class type, the
9899       // expression is implicitly converted (C++ 4) to the
9900       // cv-unqualified type of the left operand.
9901       QualType RHSType = RHS.get()->getType();
9902       if (Diagnose) {
9903         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9904                                         AA_Assigning);
9905       } else {
9906         ImplicitConversionSequence ICS =
9907             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9908                                   /*SuppressUserConversions=*/false,
9909                                   AllowedExplicit::None,
9910                                   /*InOverloadResolution=*/false,
9911                                   /*CStyle=*/false,
9912                                   /*AllowObjCWritebackConversion=*/false);
9913         if (ICS.isFailure())
9914           return Incompatible;
9915         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9916                                         ICS, AA_Assigning);
9917       }
9918       if (RHS.isInvalid())
9919         return Incompatible;
9920       Sema::AssignConvertType result = Compatible;
9921       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9922           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9923         result = IncompatibleObjCWeakRef;
9924       return result;
9925     }
9926 
9927     // FIXME: Currently, we fall through and treat C++ classes like C
9928     // structures.
9929     // FIXME: We also fall through for atomics; not sure what should
9930     // happen there, though.
9931   } else if (RHS.get()->getType() == Context.OverloadTy) {
9932     // As a set of extensions to C, we support overloading on functions. These
9933     // functions need to be resolved here.
9934     DeclAccessPair DAP;
9935     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9936             RHS.get(), LHSType, /*Complain=*/false, DAP))
9937       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9938     else
9939       return Incompatible;
9940   }
9941 
9942   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9943   // a null pointer constant.
9944   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9945        LHSType->isBlockPointerType()) &&
9946       RHS.get()->isNullPointerConstant(Context,
9947                                        Expr::NPC_ValueDependentIsNull)) {
9948     if (Diagnose || ConvertRHS) {
9949       CastKind Kind;
9950       CXXCastPath Path;
9951       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9952                              /*IgnoreBaseAccess=*/false, Diagnose);
9953       if (ConvertRHS)
9954         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9955     }
9956     return Compatible;
9957   }
9958 
9959   // OpenCL queue_t type assignment.
9960   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9961                                  Context, Expr::NPC_ValueDependentIsNull)) {
9962     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9963     return Compatible;
9964   }
9965 
9966   // This check seems unnatural, however it is necessary to ensure the proper
9967   // conversion of functions/arrays. If the conversion were done for all
9968   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9969   // expressions that suppress this implicit conversion (&, sizeof).
9970   //
9971   // Suppress this for references: C++ 8.5.3p5.
9972   if (!LHSType->isReferenceType()) {
9973     // FIXME: We potentially allocate here even if ConvertRHS is false.
9974     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9975     if (RHS.isInvalid())
9976       return Incompatible;
9977   }
9978   CastKind Kind;
9979   Sema::AssignConvertType result =
9980     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9981 
9982   // C99 6.5.16.1p2: The value of the right operand is converted to the
9983   // type of the assignment expression.
9984   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9985   // so that we can use references in built-in functions even in C.
9986   // The getNonReferenceType() call makes sure that the resulting expression
9987   // does not have reference type.
9988   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9989     QualType Ty = LHSType.getNonLValueExprType(Context);
9990     Expr *E = RHS.get();
9991 
9992     // Check for various Objective-C errors. If we are not reporting
9993     // diagnostics and just checking for errors, e.g., during overload
9994     // resolution, return Incompatible to indicate the failure.
9995     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9996         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9997                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9998       if (!Diagnose)
9999         return Incompatible;
10000     }
10001     if (getLangOpts().ObjC &&
10002         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10003                                            E->getType(), E, Diagnose) ||
10004          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10005       if (!Diagnose)
10006         return Incompatible;
10007       // Replace the expression with a corrected version and continue so we
10008       // can find further errors.
10009       RHS = E;
10010       return Compatible;
10011     }
10012 
10013     if (ConvertRHS)
10014       RHS = ImpCastExprToType(E, Ty, Kind);
10015   }
10016 
10017   return result;
10018 }
10019 
10020 namespace {
10021 /// The original operand to an operator, prior to the application of the usual
10022 /// arithmetic conversions and converting the arguments of a builtin operator
10023 /// candidate.
10024 struct OriginalOperand {
10025   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10026     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10027       Op = MTE->getSubExpr();
10028     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10029       Op = BTE->getSubExpr();
10030     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10031       Orig = ICE->getSubExprAsWritten();
10032       Conversion = ICE->getConversionFunction();
10033     }
10034   }
10035 
10036   QualType getType() const { return Orig->getType(); }
10037 
10038   Expr *Orig;
10039   NamedDecl *Conversion;
10040 };
10041 }
10042 
10043 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10044                                ExprResult &RHS) {
10045   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10046 
10047   Diag(Loc, diag::err_typecheck_invalid_operands)
10048     << OrigLHS.getType() << OrigRHS.getType()
10049     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10050 
10051   // If a user-defined conversion was applied to either of the operands prior
10052   // to applying the built-in operator rules, tell the user about it.
10053   if (OrigLHS.Conversion) {
10054     Diag(OrigLHS.Conversion->getLocation(),
10055          diag::note_typecheck_invalid_operands_converted)
10056       << 0 << LHS.get()->getType();
10057   }
10058   if (OrigRHS.Conversion) {
10059     Diag(OrigRHS.Conversion->getLocation(),
10060          diag::note_typecheck_invalid_operands_converted)
10061       << 1 << RHS.get()->getType();
10062   }
10063 
10064   return QualType();
10065 }
10066 
10067 // Diagnose cases where a scalar was implicitly converted to a vector and
10068 // diagnose the underlying types. Otherwise, diagnose the error
10069 // as invalid vector logical operands for non-C++ cases.
10070 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10071                                             ExprResult &RHS) {
10072   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10073   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10074 
10075   bool LHSNatVec = LHSType->isVectorType();
10076   bool RHSNatVec = RHSType->isVectorType();
10077 
10078   if (!(LHSNatVec && RHSNatVec)) {
10079     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10080     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10081     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10082         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10083         << Vector->getSourceRange();
10084     return QualType();
10085   }
10086 
10087   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10088       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10089       << RHS.get()->getSourceRange();
10090 
10091   return QualType();
10092 }
10093 
10094 /// Try to convert a value of non-vector type to a vector type by converting
10095 /// the type to the element type of the vector and then performing a splat.
10096 /// If the language is OpenCL, we only use conversions that promote scalar
10097 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10098 /// for float->int.
10099 ///
10100 /// OpenCL V2.0 6.2.6.p2:
10101 /// An error shall occur if any scalar operand type has greater rank
10102 /// than the type of the vector element.
10103 ///
10104 /// \param scalar - if non-null, actually perform the conversions
10105 /// \return true if the operation fails (but without diagnosing the failure)
10106 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10107                                      QualType scalarTy,
10108                                      QualType vectorEltTy,
10109                                      QualType vectorTy,
10110                                      unsigned &DiagID) {
10111   // The conversion to apply to the scalar before splatting it,
10112   // if necessary.
10113   CastKind scalarCast = CK_NoOp;
10114 
10115   if (vectorEltTy->isIntegralType(S.Context)) {
10116     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10117         (scalarTy->isIntegerType() &&
10118          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10119       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10120       return true;
10121     }
10122     if (!scalarTy->isIntegralType(S.Context))
10123       return true;
10124     scalarCast = CK_IntegralCast;
10125   } else if (vectorEltTy->isRealFloatingType()) {
10126     if (scalarTy->isRealFloatingType()) {
10127       if (S.getLangOpts().OpenCL &&
10128           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10129         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10130         return true;
10131       }
10132       scalarCast = CK_FloatingCast;
10133     }
10134     else if (scalarTy->isIntegralType(S.Context))
10135       scalarCast = CK_IntegralToFloating;
10136     else
10137       return true;
10138   } else {
10139     return true;
10140   }
10141 
10142   // Adjust scalar if desired.
10143   if (scalar) {
10144     if (scalarCast != CK_NoOp)
10145       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10146     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10147   }
10148   return false;
10149 }
10150 
10151 /// Convert vector E to a vector with the same number of elements but different
10152 /// element type.
10153 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10154   const auto *VecTy = E->getType()->getAs<VectorType>();
10155   assert(VecTy && "Expression E must be a vector");
10156   QualType NewVecTy =
10157       VecTy->isExtVectorType()
10158           ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10159           : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10160                                     VecTy->getVectorKind());
10161 
10162   // Look through the implicit cast. Return the subexpression if its type is
10163   // NewVecTy.
10164   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10165     if (ICE->getSubExpr()->getType() == NewVecTy)
10166       return ICE->getSubExpr();
10167 
10168   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10169   return S.ImpCastExprToType(E, NewVecTy, Cast);
10170 }
10171 
10172 /// Test if a (constant) integer Int can be casted to another integer type
10173 /// IntTy without losing precision.
10174 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10175                                       QualType OtherIntTy) {
10176   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10177 
10178   // Reject cases where the value of the Int is unknown as that would
10179   // possibly cause truncation, but accept cases where the scalar can be
10180   // demoted without loss of precision.
10181   Expr::EvalResult EVResult;
10182   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10183   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10184   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10185   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10186 
10187   if (CstInt) {
10188     // If the scalar is constant and is of a higher order and has more active
10189     // bits that the vector element type, reject it.
10190     llvm::APSInt Result = EVResult.Val.getInt();
10191     unsigned NumBits = IntSigned
10192                            ? (Result.isNegative() ? Result.getMinSignedBits()
10193                                                   : Result.getActiveBits())
10194                            : Result.getActiveBits();
10195     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10196       return true;
10197 
10198     // If the signedness of the scalar type and the vector element type
10199     // differs and the number of bits is greater than that of the vector
10200     // element reject it.
10201     return (IntSigned != OtherIntSigned &&
10202             NumBits > S.Context.getIntWidth(OtherIntTy));
10203   }
10204 
10205   // Reject cases where the value of the scalar is not constant and it's
10206   // order is greater than that of the vector element type.
10207   return (Order < 0);
10208 }
10209 
10210 /// Test if a (constant) integer Int can be casted to floating point type
10211 /// FloatTy without losing precision.
10212 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10213                                      QualType FloatTy) {
10214   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10215 
10216   // Determine if the integer constant can be expressed as a floating point
10217   // number of the appropriate type.
10218   Expr::EvalResult EVResult;
10219   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10220 
10221   uint64_t Bits = 0;
10222   if (CstInt) {
10223     // Reject constants that would be truncated if they were converted to
10224     // the floating point type. Test by simple to/from conversion.
10225     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10226     //        could be avoided if there was a convertFromAPInt method
10227     //        which could signal back if implicit truncation occurred.
10228     llvm::APSInt Result = EVResult.Val.getInt();
10229     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10230     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10231                            llvm::APFloat::rmTowardZero);
10232     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10233                              !IntTy->hasSignedIntegerRepresentation());
10234     bool Ignored = false;
10235     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10236                            &Ignored);
10237     if (Result != ConvertBack)
10238       return true;
10239   } else {
10240     // Reject types that cannot be fully encoded into the mantissa of
10241     // the float.
10242     Bits = S.Context.getTypeSize(IntTy);
10243     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10244         S.Context.getFloatTypeSemantics(FloatTy));
10245     if (Bits > FloatPrec)
10246       return true;
10247   }
10248 
10249   return false;
10250 }
10251 
10252 /// Attempt to convert and splat Scalar into a vector whose types matches
10253 /// Vector following GCC conversion rules. The rule is that implicit
10254 /// conversion can occur when Scalar can be casted to match Vector's element
10255 /// type without causing truncation of Scalar.
10256 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10257                                         ExprResult *Vector) {
10258   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10259   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10260   const auto *VT = VectorTy->castAs<VectorType>();
10261 
10262   assert(!isa<ExtVectorType>(VT) &&
10263          "ExtVectorTypes should not be handled here!");
10264 
10265   QualType VectorEltTy = VT->getElementType();
10266 
10267   // Reject cases where the vector element type or the scalar element type are
10268   // not integral or floating point types.
10269   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10270     return true;
10271 
10272   // The conversion to apply to the scalar before splatting it,
10273   // if necessary.
10274   CastKind ScalarCast = CK_NoOp;
10275 
10276   // Accept cases where the vector elements are integers and the scalar is
10277   // an integer.
10278   // FIXME: Notionally if the scalar was a floating point value with a precise
10279   //        integral representation, we could cast it to an appropriate integer
10280   //        type and then perform the rest of the checks here. GCC will perform
10281   //        this conversion in some cases as determined by the input language.
10282   //        We should accept it on a language independent basis.
10283   if (VectorEltTy->isIntegralType(S.Context) &&
10284       ScalarTy->isIntegralType(S.Context) &&
10285       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10286 
10287     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10288       return true;
10289 
10290     ScalarCast = CK_IntegralCast;
10291   } else if (VectorEltTy->isIntegralType(S.Context) &&
10292              ScalarTy->isRealFloatingType()) {
10293     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10294       ScalarCast = CK_FloatingToIntegral;
10295     else
10296       return true;
10297   } else if (VectorEltTy->isRealFloatingType()) {
10298     if (ScalarTy->isRealFloatingType()) {
10299 
10300       // Reject cases where the scalar type is not a constant and has a higher
10301       // Order than the vector element type.
10302       llvm::APFloat Result(0.0);
10303 
10304       // Determine whether this is a constant scalar. In the event that the
10305       // value is dependent (and thus cannot be evaluated by the constant
10306       // evaluator), skip the evaluation. This will then diagnose once the
10307       // expression is instantiated.
10308       bool CstScalar = Scalar->get()->isValueDependent() ||
10309                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10310       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10311       if (!CstScalar && Order < 0)
10312         return true;
10313 
10314       // If the scalar cannot be safely casted to the vector element type,
10315       // reject it.
10316       if (CstScalar) {
10317         bool Truncated = false;
10318         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10319                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10320         if (Truncated)
10321           return true;
10322       }
10323 
10324       ScalarCast = CK_FloatingCast;
10325     } else if (ScalarTy->isIntegralType(S.Context)) {
10326       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10327         return true;
10328 
10329       ScalarCast = CK_IntegralToFloating;
10330     } else
10331       return true;
10332   } else if (ScalarTy->isEnumeralType())
10333     return true;
10334 
10335   // Adjust scalar if desired.
10336   if (Scalar) {
10337     if (ScalarCast != CK_NoOp)
10338       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10339     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10340   }
10341   return false;
10342 }
10343 
10344 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10345                                    SourceLocation Loc, bool IsCompAssign,
10346                                    bool AllowBothBool,
10347                                    bool AllowBoolConversions,
10348                                    bool AllowBoolOperation,
10349                                    bool ReportInvalid) {
10350   if (!IsCompAssign) {
10351     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10352     if (LHS.isInvalid())
10353       return QualType();
10354   }
10355   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10356   if (RHS.isInvalid())
10357     return QualType();
10358 
10359   // For conversion purposes, we ignore any qualifiers.
10360   // For example, "const float" and "float" are equivalent.
10361   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10362   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10363 
10364   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10365   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10366   assert(LHSVecType || RHSVecType);
10367 
10368   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10369       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10370     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10371 
10372   // AltiVec-style "vector bool op vector bool" combinations are allowed
10373   // for some operators but not others.
10374   if (!AllowBothBool &&
10375       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10376       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10377     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10378 
10379   // This operation may not be performed on boolean vectors.
10380   if (!AllowBoolOperation &&
10381       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10382     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10383 
10384   // If the vector types are identical, return.
10385   if (Context.hasSameType(LHSType, RHSType))
10386     return LHSType;
10387 
10388   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10389   if (LHSVecType && RHSVecType &&
10390       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10391     if (isa<ExtVectorType>(LHSVecType)) {
10392       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10393       return LHSType;
10394     }
10395 
10396     if (!IsCompAssign)
10397       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10398     return RHSType;
10399   }
10400 
10401   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10402   // can be mixed, with the result being the non-bool type.  The non-bool
10403   // operand must have integer element type.
10404   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10405       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10406       (Context.getTypeSize(LHSVecType->getElementType()) ==
10407        Context.getTypeSize(RHSVecType->getElementType()))) {
10408     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10409         LHSVecType->getElementType()->isIntegerType() &&
10410         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10411       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10412       return LHSType;
10413     }
10414     if (!IsCompAssign &&
10415         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10416         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10417         RHSVecType->getElementType()->isIntegerType()) {
10418       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10419       return RHSType;
10420     }
10421   }
10422 
10423   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10424   // since the ambiguity can affect the ABI.
10425   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10426     const VectorType *VecType = SecondType->getAs<VectorType>();
10427     return FirstType->isSizelessBuiltinType() && VecType &&
10428            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10429             VecType->getVectorKind() ==
10430                 VectorType::SveFixedLengthPredicateVector);
10431   };
10432 
10433   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10434     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10435     return QualType();
10436   }
10437 
10438   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10439   // since the ambiguity can affect the ABI.
10440   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10441     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10442     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10443 
10444     if (FirstVecType && SecondVecType)
10445       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10446              (SecondVecType->getVectorKind() ==
10447                   VectorType::SveFixedLengthDataVector ||
10448               SecondVecType->getVectorKind() ==
10449                   VectorType::SveFixedLengthPredicateVector);
10450 
10451     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10452            SecondVecType->getVectorKind() == VectorType::GenericVector;
10453   };
10454 
10455   if (IsSveGnuConversion(LHSType, RHSType) ||
10456       IsSveGnuConversion(RHSType, LHSType)) {
10457     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10458     return QualType();
10459   }
10460 
10461   // If there's a vector type and a scalar, try to convert the scalar to
10462   // the vector element type and splat.
10463   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10464   if (!RHSVecType) {
10465     if (isa<ExtVectorType>(LHSVecType)) {
10466       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10467                                     LHSVecType->getElementType(), LHSType,
10468                                     DiagID))
10469         return LHSType;
10470     } else {
10471       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10472         return LHSType;
10473     }
10474   }
10475   if (!LHSVecType) {
10476     if (isa<ExtVectorType>(RHSVecType)) {
10477       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10478                                     LHSType, RHSVecType->getElementType(),
10479                                     RHSType, DiagID))
10480         return RHSType;
10481     } else {
10482       if (LHS.get()->isLValue() ||
10483           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10484         return RHSType;
10485     }
10486   }
10487 
10488   // FIXME: The code below also handles conversion between vectors and
10489   // non-scalars, we should break this down into fine grained specific checks
10490   // and emit proper diagnostics.
10491   QualType VecType = LHSVecType ? LHSType : RHSType;
10492   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10493   QualType OtherType = LHSVecType ? RHSType : LHSType;
10494   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10495   if (isLaxVectorConversion(OtherType, VecType)) {
10496     // If we're allowing lax vector conversions, only the total (data) size
10497     // needs to be the same. For non compound assignment, if one of the types is
10498     // scalar, the result is always the vector type.
10499     if (!IsCompAssign) {
10500       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10501       return VecType;
10502     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10503     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10504     // type. Note that this is already done by non-compound assignments in
10505     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10506     // <1 x T> -> T. The result is also a vector type.
10507     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10508                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10509       ExprResult *RHSExpr = &RHS;
10510       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10511       return VecType;
10512     }
10513   }
10514 
10515   // Okay, the expression is invalid.
10516 
10517   // If there's a non-vector, non-real operand, diagnose that.
10518   if ((!RHSVecType && !RHSType->isRealType()) ||
10519       (!LHSVecType && !LHSType->isRealType())) {
10520     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10521       << LHSType << RHSType
10522       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10523     return QualType();
10524   }
10525 
10526   // OpenCL V1.1 6.2.6.p1:
10527   // If the operands are of more than one vector type, then an error shall
10528   // occur. Implicit conversions between vector types are not permitted, per
10529   // section 6.2.1.
10530   if (getLangOpts().OpenCL &&
10531       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10532       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10533     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10534                                                            << RHSType;
10535     return QualType();
10536   }
10537 
10538 
10539   // If there is a vector type that is not a ExtVector and a scalar, we reach
10540   // this point if scalar could not be converted to the vector's element type
10541   // without truncation.
10542   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10543       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10544     QualType Scalar = LHSVecType ? RHSType : LHSType;
10545     QualType Vector = LHSVecType ? LHSType : RHSType;
10546     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10547     Diag(Loc,
10548          diag::err_typecheck_vector_not_convertable_implict_truncation)
10549         << ScalarOrVector << Scalar << Vector;
10550 
10551     return QualType();
10552   }
10553 
10554   // Otherwise, use the generic diagnostic.
10555   Diag(Loc, DiagID)
10556     << LHSType << RHSType
10557     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10558   return QualType();
10559 }
10560 
10561 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10562                                            SourceLocation Loc,
10563                                            bool IsCompAssign,
10564                                            ArithConvKind OperationKind) {
10565   if (!IsCompAssign) {
10566     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10567     if (LHS.isInvalid())
10568       return QualType();
10569   }
10570   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10571   if (RHS.isInvalid())
10572     return QualType();
10573 
10574   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10575   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10576 
10577   unsigned DiagID = diag::err_typecheck_invalid_operands;
10578   if ((OperationKind == ACK_Arithmetic) &&
10579       (LHSType->castAs<BuiltinType>()->isSVEBool() ||
10580        RHSType->castAs<BuiltinType>()->isSVEBool())) {
10581     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10582                       << RHS.get()->getSourceRange();
10583     return QualType();
10584   }
10585 
10586   if (Context.hasSameType(LHSType, RHSType))
10587     return LHSType;
10588 
10589   auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10590                                          QualType DestType) {
10591     const QualType DestBaseType = DestType->getSveEltType(Context);
10592     if (DestBaseType->getUnqualifiedDesugaredType() ==
10593         SrcType->getUnqualifiedDesugaredType()) {
10594       unsigned DiagID = diag::err_typecheck_invalid_operands;
10595       if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10596                                     DiagID))
10597         return DestType;
10598     }
10599     return QualType();
10600   };
10601 
10602   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10603     auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10604     if (DestType == QualType())
10605       return InvalidOperands(Loc, LHS, RHS);
10606     return DestType;
10607   }
10608 
10609   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10610     auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10611                                              LHSType, RHSType);
10612     if (DestType == QualType())
10613       return InvalidOperands(Loc, LHS, RHS);
10614     return DestType;
10615   }
10616 
10617   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10618                     << RHS.get()->getSourceRange();
10619   return QualType();
10620 }
10621 
10622 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10623 // expression.  These are mainly cases where the null pointer is used as an
10624 // integer instead of a pointer.
10625 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10626                                 SourceLocation Loc, bool IsCompare) {
10627   // The canonical way to check for a GNU null is with isNullPointerConstant,
10628   // but we use a bit of a hack here for speed; this is a relatively
10629   // hot path, and isNullPointerConstant is slow.
10630   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10631   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10632 
10633   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10634 
10635   // Avoid analyzing cases where the result will either be invalid (and
10636   // diagnosed as such) or entirely valid and not something to warn about.
10637   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10638       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10639     return;
10640 
10641   // Comparison operations would not make sense with a null pointer no matter
10642   // what the other expression is.
10643   if (!IsCompare) {
10644     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10645         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10646         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10647     return;
10648   }
10649 
10650   // The rest of the operations only make sense with a null pointer
10651   // if the other expression is a pointer.
10652   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10653       NonNullType->canDecayToPointerType())
10654     return;
10655 
10656   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10657       << LHSNull /* LHS is NULL */ << NonNullType
10658       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10659 }
10660 
10661 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10662                                           SourceLocation Loc) {
10663   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10664   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10665   if (!LUE || !RUE)
10666     return;
10667   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10668       RUE->getKind() != UETT_SizeOf)
10669     return;
10670 
10671   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10672   QualType LHSTy = LHSArg->getType();
10673   QualType RHSTy;
10674 
10675   if (RUE->isArgumentType())
10676     RHSTy = RUE->getArgumentType().getNonReferenceType();
10677   else
10678     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10679 
10680   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10681     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10682       return;
10683 
10684     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10685     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10686       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10687         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10688             << LHSArgDecl;
10689     }
10690   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10691     QualType ArrayElemTy = ArrayTy->getElementType();
10692     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10693         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10694         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10695         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10696       return;
10697     S.Diag(Loc, diag::warn_division_sizeof_array)
10698         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10699     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10700       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10701         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10702             << LHSArgDecl;
10703     }
10704 
10705     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10706   }
10707 }
10708 
10709 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10710                                                ExprResult &RHS,
10711                                                SourceLocation Loc, bool IsDiv) {
10712   // Check for division/remainder by zero.
10713   Expr::EvalResult RHSValue;
10714   if (!RHS.get()->isValueDependent() &&
10715       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10716       RHSValue.Val.getInt() == 0)
10717     S.DiagRuntimeBehavior(Loc, RHS.get(),
10718                           S.PDiag(diag::warn_remainder_division_by_zero)
10719                             << IsDiv << RHS.get()->getSourceRange());
10720 }
10721 
10722 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10723                                            SourceLocation Loc,
10724                                            bool IsCompAssign, bool IsDiv) {
10725   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10726 
10727   QualType LHSTy = LHS.get()->getType();
10728   QualType RHSTy = RHS.get()->getType();
10729   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10730     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10731                                /*AllowBothBool*/ getLangOpts().AltiVec,
10732                                /*AllowBoolConversions*/ false,
10733                                /*AllowBooleanOperation*/ false,
10734                                /*ReportInvalid*/ true);
10735   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10736     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10737                                        ACK_Arithmetic);
10738   if (!IsDiv &&
10739       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10740     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10741   // For division, only matrix-by-scalar is supported. Other combinations with
10742   // matrix types are invalid.
10743   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10744     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10745 
10746   QualType compType = UsualArithmeticConversions(
10747       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10748   if (LHS.isInvalid() || RHS.isInvalid())
10749     return QualType();
10750 
10751 
10752   if (compType.isNull() || !compType->isArithmeticType())
10753     return InvalidOperands(Loc, LHS, RHS);
10754   if (IsDiv) {
10755     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10756     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10757   }
10758   return compType;
10759 }
10760 
10761 QualType Sema::CheckRemainderOperands(
10762   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10763   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10764 
10765   if (LHS.get()->getType()->isVectorType() ||
10766       RHS.get()->getType()->isVectorType()) {
10767     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10768         RHS.get()->getType()->hasIntegerRepresentation())
10769       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10770                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10771                                  /*AllowBoolConversions*/ false,
10772                                  /*AllowBooleanOperation*/ false,
10773                                  /*ReportInvalid*/ true);
10774     return InvalidOperands(Loc, LHS, RHS);
10775   }
10776 
10777   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10778       RHS.get()->getType()->isVLSTBuiltinType()) {
10779     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10780         RHS.get()->getType()->hasIntegerRepresentation())
10781       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10782                                          ACK_Arithmetic);
10783 
10784     return InvalidOperands(Loc, LHS, RHS);
10785   }
10786 
10787   QualType compType = UsualArithmeticConversions(
10788       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10789   if (LHS.isInvalid() || RHS.isInvalid())
10790     return QualType();
10791 
10792   if (compType.isNull() || !compType->isIntegerType())
10793     return InvalidOperands(Loc, LHS, RHS);
10794   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10795   return compType;
10796 }
10797 
10798 /// Diagnose invalid arithmetic on two void pointers.
10799 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10800                                                 Expr *LHSExpr, Expr *RHSExpr) {
10801   S.Diag(Loc, S.getLangOpts().CPlusPlus
10802                 ? diag::err_typecheck_pointer_arith_void_type
10803                 : diag::ext_gnu_void_ptr)
10804     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10805                             << RHSExpr->getSourceRange();
10806 }
10807 
10808 /// Diagnose invalid arithmetic on a void pointer.
10809 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10810                                             Expr *Pointer) {
10811   S.Diag(Loc, S.getLangOpts().CPlusPlus
10812                 ? diag::err_typecheck_pointer_arith_void_type
10813                 : diag::ext_gnu_void_ptr)
10814     << 0 /* one pointer */ << Pointer->getSourceRange();
10815 }
10816 
10817 /// Diagnose invalid arithmetic on a null pointer.
10818 ///
10819 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10820 /// idiom, which we recognize as a GNU extension.
10821 ///
10822 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10823                                             Expr *Pointer, bool IsGNUIdiom) {
10824   if (IsGNUIdiom)
10825     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10826       << Pointer->getSourceRange();
10827   else
10828     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10829       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10830 }
10831 
10832 /// Diagnose invalid subraction on a null pointer.
10833 ///
10834 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10835                                              Expr *Pointer, bool BothNull) {
10836   // Null - null is valid in C++ [expr.add]p7
10837   if (BothNull && S.getLangOpts().CPlusPlus)
10838     return;
10839 
10840   // Is this s a macro from a system header?
10841   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10842     return;
10843 
10844   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10845       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10846 }
10847 
10848 /// Diagnose invalid arithmetic on two function pointers.
10849 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10850                                                     Expr *LHS, Expr *RHS) {
10851   assert(LHS->getType()->isAnyPointerType());
10852   assert(RHS->getType()->isAnyPointerType());
10853   S.Diag(Loc, S.getLangOpts().CPlusPlus
10854                 ? diag::err_typecheck_pointer_arith_function_type
10855                 : diag::ext_gnu_ptr_func_arith)
10856     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10857     // We only show the second type if it differs from the first.
10858     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10859                                                    RHS->getType())
10860     << RHS->getType()->getPointeeType()
10861     << LHS->getSourceRange() << RHS->getSourceRange();
10862 }
10863 
10864 /// Diagnose invalid arithmetic on a function pointer.
10865 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10866                                                 Expr *Pointer) {
10867   assert(Pointer->getType()->isAnyPointerType());
10868   S.Diag(Loc, S.getLangOpts().CPlusPlus
10869                 ? diag::err_typecheck_pointer_arith_function_type
10870                 : diag::ext_gnu_ptr_func_arith)
10871     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10872     << 0 /* one pointer, so only one type */
10873     << Pointer->getSourceRange();
10874 }
10875 
10876 /// Emit error if Operand is incomplete pointer type
10877 ///
10878 /// \returns True if pointer has incomplete type
10879 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10880                                                  Expr *Operand) {
10881   QualType ResType = Operand->getType();
10882   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10883     ResType = ResAtomicType->getValueType();
10884 
10885   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10886   QualType PointeeTy = ResType->getPointeeType();
10887   return S.RequireCompleteSizedType(
10888       Loc, PointeeTy,
10889       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10890       Operand->getSourceRange());
10891 }
10892 
10893 /// Check the validity of an arithmetic pointer operand.
10894 ///
10895 /// If the operand has pointer type, this code will check for pointer types
10896 /// which are invalid in arithmetic operations. These will be diagnosed
10897 /// appropriately, including whether or not the use is supported as an
10898 /// extension.
10899 ///
10900 /// \returns True when the operand is valid to use (even if as an extension).
10901 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10902                                             Expr *Operand) {
10903   QualType ResType = Operand->getType();
10904   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10905     ResType = ResAtomicType->getValueType();
10906 
10907   if (!ResType->isAnyPointerType()) return true;
10908 
10909   QualType PointeeTy = ResType->getPointeeType();
10910   if (PointeeTy->isVoidType()) {
10911     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10912     return !S.getLangOpts().CPlusPlus;
10913   }
10914   if (PointeeTy->isFunctionType()) {
10915     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10916     return !S.getLangOpts().CPlusPlus;
10917   }
10918 
10919   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10920 
10921   return true;
10922 }
10923 
10924 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10925 /// operands.
10926 ///
10927 /// This routine will diagnose any invalid arithmetic on pointer operands much
10928 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10929 /// for emitting a single diagnostic even for operations where both LHS and RHS
10930 /// are (potentially problematic) pointers.
10931 ///
10932 /// \returns True when the operand is valid to use (even if as an extension).
10933 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10934                                                 Expr *LHSExpr, Expr *RHSExpr) {
10935   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10936   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10937   if (!isLHSPointer && !isRHSPointer) return true;
10938 
10939   QualType LHSPointeeTy, RHSPointeeTy;
10940   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10941   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10942 
10943   // if both are pointers check if operation is valid wrt address spaces
10944   if (isLHSPointer && isRHSPointer) {
10945     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10946       S.Diag(Loc,
10947              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10948           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10949           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10950       return false;
10951     }
10952   }
10953 
10954   // Check for arithmetic on pointers to incomplete types.
10955   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10956   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10957   if (isLHSVoidPtr || isRHSVoidPtr) {
10958     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10959     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10960     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10961 
10962     return !S.getLangOpts().CPlusPlus;
10963   }
10964 
10965   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10966   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10967   if (isLHSFuncPtr || isRHSFuncPtr) {
10968     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10969     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10970                                                                 RHSExpr);
10971     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10972 
10973     return !S.getLangOpts().CPlusPlus;
10974   }
10975 
10976   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10977     return false;
10978   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10979     return false;
10980 
10981   return true;
10982 }
10983 
10984 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10985 /// literal.
10986 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10987                                   Expr *LHSExpr, Expr *RHSExpr) {
10988   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10989   Expr* IndexExpr = RHSExpr;
10990   if (!StrExpr) {
10991     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10992     IndexExpr = LHSExpr;
10993   }
10994 
10995   bool IsStringPlusInt = StrExpr &&
10996       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10997   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10998     return;
10999 
11000   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11001   Self.Diag(OpLoc, diag::warn_string_plus_int)
11002       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11003 
11004   // Only print a fixit for "str" + int, not for int + "str".
11005   if (IndexExpr == RHSExpr) {
11006     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11007     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11008         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11009         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11010         << FixItHint::CreateInsertion(EndLoc, "]");
11011   } else
11012     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11013 }
11014 
11015 /// Emit a warning when adding a char literal to a string.
11016 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11017                                    Expr *LHSExpr, Expr *RHSExpr) {
11018   const Expr *StringRefExpr = LHSExpr;
11019   const CharacterLiteral *CharExpr =
11020       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11021 
11022   if (!CharExpr) {
11023     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11024     StringRefExpr = RHSExpr;
11025   }
11026 
11027   if (!CharExpr || !StringRefExpr)
11028     return;
11029 
11030   const QualType StringType = StringRefExpr->getType();
11031 
11032   // Return if not a PointerType.
11033   if (!StringType->isAnyPointerType())
11034     return;
11035 
11036   // Return if not a CharacterType.
11037   if (!StringType->getPointeeType()->isAnyCharacterType())
11038     return;
11039 
11040   ASTContext &Ctx = Self.getASTContext();
11041   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11042 
11043   const QualType CharType = CharExpr->getType();
11044   if (!CharType->isAnyCharacterType() &&
11045       CharType->isIntegerType() &&
11046       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11047     Self.Diag(OpLoc, diag::warn_string_plus_char)
11048         << DiagRange << Ctx.CharTy;
11049   } else {
11050     Self.Diag(OpLoc, diag::warn_string_plus_char)
11051         << DiagRange << CharExpr->getType();
11052   }
11053 
11054   // Only print a fixit for str + char, not for char + str.
11055   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11056     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11057     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11058         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11059         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11060         << FixItHint::CreateInsertion(EndLoc, "]");
11061   } else {
11062     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11063   }
11064 }
11065 
11066 /// Emit error when two pointers are incompatible.
11067 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11068                                            Expr *LHSExpr, Expr *RHSExpr) {
11069   assert(LHSExpr->getType()->isAnyPointerType());
11070   assert(RHSExpr->getType()->isAnyPointerType());
11071   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11072     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11073     << RHSExpr->getSourceRange();
11074 }
11075 
11076 // C99 6.5.6
11077 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11078                                      SourceLocation Loc, BinaryOperatorKind Opc,
11079                                      QualType* CompLHSTy) {
11080   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11081 
11082   if (LHS.get()->getType()->isVectorType() ||
11083       RHS.get()->getType()->isVectorType()) {
11084     QualType compType =
11085         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11086                             /*AllowBothBool*/ getLangOpts().AltiVec,
11087                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11088                             /*AllowBooleanOperation*/ false,
11089                             /*ReportInvalid*/ true);
11090     if (CompLHSTy) *CompLHSTy = compType;
11091     return compType;
11092   }
11093 
11094   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11095       RHS.get()->getType()->isVLSTBuiltinType()) {
11096     QualType compType =
11097         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11098     if (CompLHSTy)
11099       *CompLHSTy = compType;
11100     return compType;
11101   }
11102 
11103   if (LHS.get()->getType()->isConstantMatrixType() ||
11104       RHS.get()->getType()->isConstantMatrixType()) {
11105     QualType compType =
11106         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11107     if (CompLHSTy)
11108       *CompLHSTy = compType;
11109     return compType;
11110   }
11111 
11112   QualType compType = UsualArithmeticConversions(
11113       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11114   if (LHS.isInvalid() || RHS.isInvalid())
11115     return QualType();
11116 
11117   // Diagnose "string literal" '+' int and string '+' "char literal".
11118   if (Opc == BO_Add) {
11119     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11120     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11121   }
11122 
11123   // handle the common case first (both operands are arithmetic).
11124   if (!compType.isNull() && compType->isArithmeticType()) {
11125     if (CompLHSTy) *CompLHSTy = compType;
11126     return compType;
11127   }
11128 
11129   // Type-checking.  Ultimately the pointer's going to be in PExp;
11130   // note that we bias towards the LHS being the pointer.
11131   Expr *PExp = LHS.get(), *IExp = RHS.get();
11132 
11133   bool isObjCPointer;
11134   if (PExp->getType()->isPointerType()) {
11135     isObjCPointer = false;
11136   } else if (PExp->getType()->isObjCObjectPointerType()) {
11137     isObjCPointer = true;
11138   } else {
11139     std::swap(PExp, IExp);
11140     if (PExp->getType()->isPointerType()) {
11141       isObjCPointer = false;
11142     } else if (PExp->getType()->isObjCObjectPointerType()) {
11143       isObjCPointer = true;
11144     } else {
11145       return InvalidOperands(Loc, LHS, RHS);
11146     }
11147   }
11148   assert(PExp->getType()->isAnyPointerType());
11149 
11150   if (!IExp->getType()->isIntegerType())
11151     return InvalidOperands(Loc, LHS, RHS);
11152 
11153   // Adding to a null pointer results in undefined behavior.
11154   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11155           Context, Expr::NPC_ValueDependentIsNotNull)) {
11156     // In C++ adding zero to a null pointer is defined.
11157     Expr::EvalResult KnownVal;
11158     if (!getLangOpts().CPlusPlus ||
11159         (!IExp->isValueDependent() &&
11160          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11161           KnownVal.Val.getInt() != 0))) {
11162       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11163       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11164           Context, BO_Add, PExp, IExp);
11165       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11166     }
11167   }
11168 
11169   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11170     return QualType();
11171 
11172   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11173     return QualType();
11174 
11175   // Check array bounds for pointer arithemtic
11176   CheckArrayAccess(PExp, IExp);
11177 
11178   if (CompLHSTy) {
11179     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11180     if (LHSTy.isNull()) {
11181       LHSTy = LHS.get()->getType();
11182       if (LHSTy->isPromotableIntegerType())
11183         LHSTy = Context.getPromotedIntegerType(LHSTy);
11184     }
11185     *CompLHSTy = LHSTy;
11186   }
11187 
11188   return PExp->getType();
11189 }
11190 
11191 // C99 6.5.6
11192 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11193                                         SourceLocation Loc,
11194                                         QualType* CompLHSTy) {
11195   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11196 
11197   if (LHS.get()->getType()->isVectorType() ||
11198       RHS.get()->getType()->isVectorType()) {
11199     QualType compType =
11200         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11201                             /*AllowBothBool*/ getLangOpts().AltiVec,
11202                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11203                             /*AllowBooleanOperation*/ false,
11204                             /*ReportInvalid*/ true);
11205     if (CompLHSTy) *CompLHSTy = compType;
11206     return compType;
11207   }
11208 
11209   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11210       RHS.get()->getType()->isVLSTBuiltinType()) {
11211     QualType compType =
11212         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11213     if (CompLHSTy)
11214       *CompLHSTy = compType;
11215     return compType;
11216   }
11217 
11218   if (LHS.get()->getType()->isConstantMatrixType() ||
11219       RHS.get()->getType()->isConstantMatrixType()) {
11220     QualType compType =
11221         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11222     if (CompLHSTy)
11223       *CompLHSTy = compType;
11224     return compType;
11225   }
11226 
11227   QualType compType = UsualArithmeticConversions(
11228       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11229   if (LHS.isInvalid() || RHS.isInvalid())
11230     return QualType();
11231 
11232   // Enforce type constraints: C99 6.5.6p3.
11233 
11234   // Handle the common case first (both operands are arithmetic).
11235   if (!compType.isNull() && compType->isArithmeticType()) {
11236     if (CompLHSTy) *CompLHSTy = compType;
11237     return compType;
11238   }
11239 
11240   // Either ptr - int   or   ptr - ptr.
11241   if (LHS.get()->getType()->isAnyPointerType()) {
11242     QualType lpointee = LHS.get()->getType()->getPointeeType();
11243 
11244     // Diagnose bad cases where we step over interface counts.
11245     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11246         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11247       return QualType();
11248 
11249     // The result type of a pointer-int computation is the pointer type.
11250     if (RHS.get()->getType()->isIntegerType()) {
11251       // Subtracting from a null pointer should produce a warning.
11252       // The last argument to the diagnose call says this doesn't match the
11253       // GNU int-to-pointer idiom.
11254       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11255                                            Expr::NPC_ValueDependentIsNotNull)) {
11256         // In C++ adding zero to a null pointer is defined.
11257         Expr::EvalResult KnownVal;
11258         if (!getLangOpts().CPlusPlus ||
11259             (!RHS.get()->isValueDependent() &&
11260              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11261               KnownVal.Val.getInt() != 0))) {
11262           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11263         }
11264       }
11265 
11266       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11267         return QualType();
11268 
11269       // Check array bounds for pointer arithemtic
11270       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11271                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11272 
11273       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11274       return LHS.get()->getType();
11275     }
11276 
11277     // Handle pointer-pointer subtractions.
11278     if (const PointerType *RHSPTy
11279           = RHS.get()->getType()->getAs<PointerType>()) {
11280       QualType rpointee = RHSPTy->getPointeeType();
11281 
11282       if (getLangOpts().CPlusPlus) {
11283         // Pointee types must be the same: C++ [expr.add]
11284         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11285           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11286         }
11287       } else {
11288         // Pointee types must be compatible C99 6.5.6p3
11289         if (!Context.typesAreCompatible(
11290                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11291                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11292           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11293           return QualType();
11294         }
11295       }
11296 
11297       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11298                                                LHS.get(), RHS.get()))
11299         return QualType();
11300 
11301       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11302           Context, Expr::NPC_ValueDependentIsNotNull);
11303       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11304           Context, Expr::NPC_ValueDependentIsNotNull);
11305 
11306       // Subtracting nullptr or from nullptr is suspect
11307       if (LHSIsNullPtr)
11308         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11309       if (RHSIsNullPtr)
11310         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11311 
11312       // The pointee type may have zero size.  As an extension, a structure or
11313       // union may have zero size or an array may have zero length.  In this
11314       // case subtraction does not make sense.
11315       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11316         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11317         if (ElementSize.isZero()) {
11318           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11319             << rpointee.getUnqualifiedType()
11320             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11321         }
11322       }
11323 
11324       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11325       return Context.getPointerDiffType();
11326     }
11327   }
11328 
11329   return InvalidOperands(Loc, LHS, RHS);
11330 }
11331 
11332 static bool isScopedEnumerationType(QualType T) {
11333   if (const EnumType *ET = T->getAs<EnumType>())
11334     return ET->getDecl()->isScoped();
11335   return false;
11336 }
11337 
11338 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11339                                    SourceLocation Loc, BinaryOperatorKind Opc,
11340                                    QualType LHSType) {
11341   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11342   // so skip remaining warnings as we don't want to modify values within Sema.
11343   if (S.getLangOpts().OpenCL)
11344     return;
11345 
11346   // Check right/shifter operand
11347   Expr::EvalResult RHSResult;
11348   if (RHS.get()->isValueDependent() ||
11349       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11350     return;
11351   llvm::APSInt Right = RHSResult.Val.getInt();
11352 
11353   if (Right.isNegative()) {
11354     S.DiagRuntimeBehavior(Loc, RHS.get(),
11355                           S.PDiag(diag::warn_shift_negative)
11356                             << RHS.get()->getSourceRange());
11357     return;
11358   }
11359 
11360   QualType LHSExprType = LHS.get()->getType();
11361   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11362   if (LHSExprType->isBitIntType())
11363     LeftSize = S.Context.getIntWidth(LHSExprType);
11364   else if (LHSExprType->isFixedPointType()) {
11365     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11366     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11367   }
11368   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11369   if (Right.uge(LeftBits)) {
11370     S.DiagRuntimeBehavior(Loc, RHS.get(),
11371                           S.PDiag(diag::warn_shift_gt_typewidth)
11372                             << RHS.get()->getSourceRange());
11373     return;
11374   }
11375 
11376   // FIXME: We probably need to handle fixed point types specially here.
11377   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11378     return;
11379 
11380   // When left shifting an ICE which is signed, we can check for overflow which
11381   // according to C++ standards prior to C++2a has undefined behavior
11382   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11383   // more than the maximum value representable in the result type, so never
11384   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11385   // expression is still probably a bug.)
11386   Expr::EvalResult LHSResult;
11387   if (LHS.get()->isValueDependent() ||
11388       LHSType->hasUnsignedIntegerRepresentation() ||
11389       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11390     return;
11391   llvm::APSInt Left = LHSResult.Val.getInt();
11392 
11393   // If LHS does not have a signed type and non-negative value
11394   // then, the behavior is undefined before C++2a. Warn about it.
11395   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11396       !S.getLangOpts().CPlusPlus20) {
11397     S.DiagRuntimeBehavior(Loc, LHS.get(),
11398                           S.PDiag(diag::warn_shift_lhs_negative)
11399                             << LHS.get()->getSourceRange());
11400     return;
11401   }
11402 
11403   llvm::APInt ResultBits =
11404       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11405   if (LeftBits.uge(ResultBits))
11406     return;
11407   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11408   Result = Result.shl(Right);
11409 
11410   // Print the bit representation of the signed integer as an unsigned
11411   // hexadecimal number.
11412   SmallString<40> HexResult;
11413   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11414 
11415   // If we are only missing a sign bit, this is less likely to result in actual
11416   // bugs -- if the result is cast back to an unsigned type, it will have the
11417   // expected value. Thus we place this behind a different warning that can be
11418   // turned off separately if needed.
11419   if (LeftBits == ResultBits - 1) {
11420     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11421         << HexResult << LHSType
11422         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11423     return;
11424   }
11425 
11426   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11427     << HexResult.str() << Result.getMinSignedBits() << LHSType
11428     << Left.getBitWidth() << LHS.get()->getSourceRange()
11429     << RHS.get()->getSourceRange();
11430 }
11431 
11432 /// Return the resulting type when a vector is shifted
11433 ///        by a scalar or vector shift amount.
11434 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11435                                  SourceLocation Loc, bool IsCompAssign) {
11436   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11437   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11438       !LHS.get()->getType()->isVectorType()) {
11439     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11440       << RHS.get()->getType() << LHS.get()->getType()
11441       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11442     return QualType();
11443   }
11444 
11445   if (!IsCompAssign) {
11446     LHS = S.UsualUnaryConversions(LHS.get());
11447     if (LHS.isInvalid()) return QualType();
11448   }
11449 
11450   RHS = S.UsualUnaryConversions(RHS.get());
11451   if (RHS.isInvalid()) return QualType();
11452 
11453   QualType LHSType = LHS.get()->getType();
11454   // Note that LHS might be a scalar because the routine calls not only in
11455   // OpenCL case.
11456   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11457   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11458 
11459   // Note that RHS might not be a vector.
11460   QualType RHSType = RHS.get()->getType();
11461   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11462   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11463 
11464   // Do not allow shifts for boolean vectors.
11465   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11466       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11467     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11468         << LHS.get()->getType() << RHS.get()->getType()
11469         << LHS.get()->getSourceRange();
11470     return QualType();
11471   }
11472 
11473   // The operands need to be integers.
11474   if (!LHSEleType->isIntegerType()) {
11475     S.Diag(Loc, diag::err_typecheck_expect_int)
11476       << LHS.get()->getType() << LHS.get()->getSourceRange();
11477     return QualType();
11478   }
11479 
11480   if (!RHSEleType->isIntegerType()) {
11481     S.Diag(Loc, diag::err_typecheck_expect_int)
11482       << RHS.get()->getType() << RHS.get()->getSourceRange();
11483     return QualType();
11484   }
11485 
11486   if (!LHSVecTy) {
11487     assert(RHSVecTy);
11488     if (IsCompAssign)
11489       return RHSType;
11490     if (LHSEleType != RHSEleType) {
11491       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11492       LHSEleType = RHSEleType;
11493     }
11494     QualType VecTy =
11495         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11496     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11497     LHSType = VecTy;
11498   } else if (RHSVecTy) {
11499     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11500     // are applied component-wise. So if RHS is a vector, then ensure
11501     // that the number of elements is the same as LHS...
11502     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11503       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11504         << LHS.get()->getType() << RHS.get()->getType()
11505         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11506       return QualType();
11507     }
11508     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11509       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11510       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11511       if (LHSBT != RHSBT &&
11512           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11513         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11514             << LHS.get()->getType() << RHS.get()->getType()
11515             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11516       }
11517     }
11518   } else {
11519     // ...else expand RHS to match the number of elements in LHS.
11520     QualType VecTy =
11521       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11522     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11523   }
11524 
11525   return LHSType;
11526 }
11527 
11528 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11529                                          ExprResult &RHS, SourceLocation Loc,
11530                                          bool IsCompAssign) {
11531   if (!IsCompAssign) {
11532     LHS = S.UsualUnaryConversions(LHS.get());
11533     if (LHS.isInvalid())
11534       return QualType();
11535   }
11536 
11537   RHS = S.UsualUnaryConversions(RHS.get());
11538   if (RHS.isInvalid())
11539     return QualType();
11540 
11541   QualType LHSType = LHS.get()->getType();
11542   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11543   QualType LHSEleType = LHSType->isVLSTBuiltinType()
11544                             ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11545                             : LHSType;
11546 
11547   // Note that RHS might not be a vector
11548   QualType RHSType = RHS.get()->getType();
11549   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11550   QualType RHSEleType = RHSType->isVLSTBuiltinType()
11551                             ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11552                             : RHSType;
11553 
11554   if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11555       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11556     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11557         << LHSType << RHSType << LHS.get()->getSourceRange();
11558     return QualType();
11559   }
11560 
11561   if (!LHSEleType->isIntegerType()) {
11562     S.Diag(Loc, diag::err_typecheck_expect_int)
11563         << LHS.get()->getType() << LHS.get()->getSourceRange();
11564     return QualType();
11565   }
11566 
11567   if (!RHSEleType->isIntegerType()) {
11568     S.Diag(Loc, diag::err_typecheck_expect_int)
11569         << RHS.get()->getType() << RHS.get()->getSourceRange();
11570     return QualType();
11571   }
11572 
11573   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11574       (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11575        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11576     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11577         << LHSType << RHSType << LHS.get()->getSourceRange()
11578         << RHS.get()->getSourceRange();
11579     return QualType();
11580   }
11581 
11582   if (!LHSType->isVLSTBuiltinType()) {
11583     assert(RHSType->isVLSTBuiltinType());
11584     if (IsCompAssign)
11585       return RHSType;
11586     if (LHSEleType != RHSEleType) {
11587       LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11588       LHSEleType = RHSEleType;
11589     }
11590     const llvm::ElementCount VecSize =
11591         S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11592     QualType VecTy =
11593         S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11594     LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11595     LHSType = VecTy;
11596   } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11597     if (S.Context.getTypeSize(RHSBuiltinTy) !=
11598         S.Context.getTypeSize(LHSBuiltinTy)) {
11599       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11600           << LHSType << RHSType << LHS.get()->getSourceRange()
11601           << RHS.get()->getSourceRange();
11602       return QualType();
11603     }
11604   } else {
11605     const llvm::ElementCount VecSize =
11606         S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11607     if (LHSEleType != RHSEleType) {
11608       RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11609       RHSEleType = LHSEleType;
11610     }
11611     QualType VecTy =
11612         S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11613     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11614   }
11615 
11616   return LHSType;
11617 }
11618 
11619 // C99 6.5.7
11620 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11621                                   SourceLocation Loc, BinaryOperatorKind Opc,
11622                                   bool IsCompAssign) {
11623   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11624 
11625   // Vector shifts promote their scalar inputs to vector type.
11626   if (LHS.get()->getType()->isVectorType() ||
11627       RHS.get()->getType()->isVectorType()) {
11628     if (LangOpts.ZVector) {
11629       // The shift operators for the z vector extensions work basically
11630       // like general shifts, except that neither the LHS nor the RHS is
11631       // allowed to be a "vector bool".
11632       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11633         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11634           return InvalidOperands(Loc, LHS, RHS);
11635       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11636         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11637           return InvalidOperands(Loc, LHS, RHS);
11638     }
11639     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11640   }
11641 
11642   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11643       RHS.get()->getType()->isVLSTBuiltinType())
11644     return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11645 
11646   // Shifts don't perform usual arithmetic conversions, they just do integer
11647   // promotions on each operand. C99 6.5.7p3
11648 
11649   // For the LHS, do usual unary conversions, but then reset them away
11650   // if this is a compound assignment.
11651   ExprResult OldLHS = LHS;
11652   LHS = UsualUnaryConversions(LHS.get());
11653   if (LHS.isInvalid())
11654     return QualType();
11655   QualType LHSType = LHS.get()->getType();
11656   if (IsCompAssign) LHS = OldLHS;
11657 
11658   // The RHS is simpler.
11659   RHS = UsualUnaryConversions(RHS.get());
11660   if (RHS.isInvalid())
11661     return QualType();
11662   QualType RHSType = RHS.get()->getType();
11663 
11664   // C99 6.5.7p2: Each of the operands shall have integer type.
11665   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11666   if ((!LHSType->isFixedPointOrIntegerType() &&
11667        !LHSType->hasIntegerRepresentation()) ||
11668       !RHSType->hasIntegerRepresentation())
11669     return InvalidOperands(Loc, LHS, RHS);
11670 
11671   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11672   // hasIntegerRepresentation() above instead of this.
11673   if (isScopedEnumerationType(LHSType) ||
11674       isScopedEnumerationType(RHSType)) {
11675     return InvalidOperands(Loc, LHS, RHS);
11676   }
11677   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11678 
11679   // "The type of the result is that of the promoted left operand."
11680   return LHSType;
11681 }
11682 
11683 /// Diagnose bad pointer comparisons.
11684 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11685                                               ExprResult &LHS, ExprResult &RHS,
11686                                               bool IsError) {
11687   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11688                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11689     << LHS.get()->getType() << RHS.get()->getType()
11690     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11691 }
11692 
11693 /// Returns false if the pointers are converted to a composite type,
11694 /// true otherwise.
11695 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11696                                            ExprResult &LHS, ExprResult &RHS) {
11697   // C++ [expr.rel]p2:
11698   //   [...] Pointer conversions (4.10) and qualification
11699   //   conversions (4.4) are performed on pointer operands (or on
11700   //   a pointer operand and a null pointer constant) to bring
11701   //   them to their composite pointer type. [...]
11702   //
11703   // C++ [expr.eq]p1 uses the same notion for (in)equality
11704   // comparisons of pointers.
11705 
11706   QualType LHSType = LHS.get()->getType();
11707   QualType RHSType = RHS.get()->getType();
11708   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11709          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11710 
11711   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11712   if (T.isNull()) {
11713     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11714         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11715       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11716     else
11717       S.InvalidOperands(Loc, LHS, RHS);
11718     return true;
11719   }
11720 
11721   return false;
11722 }
11723 
11724 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11725                                                     ExprResult &LHS,
11726                                                     ExprResult &RHS,
11727                                                     bool IsError) {
11728   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11729                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11730     << LHS.get()->getType() << RHS.get()->getType()
11731     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11732 }
11733 
11734 static bool isObjCObjectLiteral(ExprResult &E) {
11735   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11736   case Stmt::ObjCArrayLiteralClass:
11737   case Stmt::ObjCDictionaryLiteralClass:
11738   case Stmt::ObjCStringLiteralClass:
11739   case Stmt::ObjCBoxedExprClass:
11740     return true;
11741   default:
11742     // Note that ObjCBoolLiteral is NOT an object literal!
11743     return false;
11744   }
11745 }
11746 
11747 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11748   const ObjCObjectPointerType *Type =
11749     LHS->getType()->getAs<ObjCObjectPointerType>();
11750 
11751   // If this is not actually an Objective-C object, bail out.
11752   if (!Type)
11753     return false;
11754 
11755   // Get the LHS object's interface type.
11756   QualType InterfaceType = Type->getPointeeType();
11757 
11758   // If the RHS isn't an Objective-C object, bail out.
11759   if (!RHS->getType()->isObjCObjectPointerType())
11760     return false;
11761 
11762   // Try to find the -isEqual: method.
11763   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11764   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11765                                                       InterfaceType,
11766                                                       /*IsInstance=*/true);
11767   if (!Method) {
11768     if (Type->isObjCIdType()) {
11769       // For 'id', just check the global pool.
11770       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11771                                                   /*receiverId=*/true);
11772     } else {
11773       // Check protocols.
11774       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11775                                              /*IsInstance=*/true);
11776     }
11777   }
11778 
11779   if (!Method)
11780     return false;
11781 
11782   QualType T = Method->parameters()[0]->getType();
11783   if (!T->isObjCObjectPointerType())
11784     return false;
11785 
11786   QualType R = Method->getReturnType();
11787   if (!R->isScalarType())
11788     return false;
11789 
11790   return true;
11791 }
11792 
11793 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11794   FromE = FromE->IgnoreParenImpCasts();
11795   switch (FromE->getStmtClass()) {
11796     default:
11797       break;
11798     case Stmt::ObjCStringLiteralClass:
11799       // "string literal"
11800       return LK_String;
11801     case Stmt::ObjCArrayLiteralClass:
11802       // "array literal"
11803       return LK_Array;
11804     case Stmt::ObjCDictionaryLiteralClass:
11805       // "dictionary literal"
11806       return LK_Dictionary;
11807     case Stmt::BlockExprClass:
11808       return LK_Block;
11809     case Stmt::ObjCBoxedExprClass: {
11810       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11811       switch (Inner->getStmtClass()) {
11812         case Stmt::IntegerLiteralClass:
11813         case Stmt::FloatingLiteralClass:
11814         case Stmt::CharacterLiteralClass:
11815         case Stmt::ObjCBoolLiteralExprClass:
11816         case Stmt::CXXBoolLiteralExprClass:
11817           // "numeric literal"
11818           return LK_Numeric;
11819         case Stmt::ImplicitCastExprClass: {
11820           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11821           // Boolean literals can be represented by implicit casts.
11822           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11823             return LK_Numeric;
11824           break;
11825         }
11826         default:
11827           break;
11828       }
11829       return LK_Boxed;
11830     }
11831   }
11832   return LK_None;
11833 }
11834 
11835 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11836                                           ExprResult &LHS, ExprResult &RHS,
11837                                           BinaryOperator::Opcode Opc){
11838   Expr *Literal;
11839   Expr *Other;
11840   if (isObjCObjectLiteral(LHS)) {
11841     Literal = LHS.get();
11842     Other = RHS.get();
11843   } else {
11844     Literal = RHS.get();
11845     Other = LHS.get();
11846   }
11847 
11848   // Don't warn on comparisons against nil.
11849   Other = Other->IgnoreParenCasts();
11850   if (Other->isNullPointerConstant(S.getASTContext(),
11851                                    Expr::NPC_ValueDependentIsNotNull))
11852     return;
11853 
11854   // This should be kept in sync with warn_objc_literal_comparison.
11855   // LK_String should always be after the other literals, since it has its own
11856   // warning flag.
11857   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11858   assert(LiteralKind != Sema::LK_Block);
11859   if (LiteralKind == Sema::LK_None) {
11860     llvm_unreachable("Unknown Objective-C object literal kind");
11861   }
11862 
11863   if (LiteralKind == Sema::LK_String)
11864     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11865       << Literal->getSourceRange();
11866   else
11867     S.Diag(Loc, diag::warn_objc_literal_comparison)
11868       << LiteralKind << Literal->getSourceRange();
11869 
11870   if (BinaryOperator::isEqualityOp(Opc) &&
11871       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11872     SourceLocation Start = LHS.get()->getBeginLoc();
11873     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11874     CharSourceRange OpRange =
11875       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11876 
11877     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11878       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11879       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11880       << FixItHint::CreateInsertion(End, "]");
11881   }
11882 }
11883 
11884 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11885 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11886                                            ExprResult &RHS, SourceLocation Loc,
11887                                            BinaryOperatorKind Opc) {
11888   // Check that left hand side is !something.
11889   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11890   if (!UO || UO->getOpcode() != UO_LNot) return;
11891 
11892   // Only check if the right hand side is non-bool arithmetic type.
11893   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11894 
11895   // Make sure that the something in !something is not bool.
11896   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11897   if (SubExpr->isKnownToHaveBooleanValue()) return;
11898 
11899   // Emit warning.
11900   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11901   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11902       << Loc << IsBitwiseOp;
11903 
11904   // First note suggest !(x < y)
11905   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11906   SourceLocation FirstClose = RHS.get()->getEndLoc();
11907   FirstClose = S.getLocForEndOfToken(FirstClose);
11908   if (FirstClose.isInvalid())
11909     FirstOpen = SourceLocation();
11910   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11911       << IsBitwiseOp
11912       << FixItHint::CreateInsertion(FirstOpen, "(")
11913       << FixItHint::CreateInsertion(FirstClose, ")");
11914 
11915   // Second note suggests (!x) < y
11916   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11917   SourceLocation SecondClose = LHS.get()->getEndLoc();
11918   SecondClose = S.getLocForEndOfToken(SecondClose);
11919   if (SecondClose.isInvalid())
11920     SecondOpen = SourceLocation();
11921   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11922       << FixItHint::CreateInsertion(SecondOpen, "(")
11923       << FixItHint::CreateInsertion(SecondClose, ")");
11924 }
11925 
11926 // Returns true if E refers to a non-weak array.
11927 static bool checkForArray(const Expr *E) {
11928   const ValueDecl *D = nullptr;
11929   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11930     D = DR->getDecl();
11931   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11932     if (Mem->isImplicitAccess())
11933       D = Mem->getMemberDecl();
11934   }
11935   if (!D)
11936     return false;
11937   return D->getType()->isArrayType() && !D->isWeak();
11938 }
11939 
11940 /// Diagnose some forms of syntactically-obvious tautological comparison.
11941 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11942                                            Expr *LHS, Expr *RHS,
11943                                            BinaryOperatorKind Opc) {
11944   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11945   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11946 
11947   QualType LHSType = LHS->getType();
11948   QualType RHSType = RHS->getType();
11949   if (LHSType->hasFloatingRepresentation() ||
11950       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11951       S.inTemplateInstantiation())
11952     return;
11953 
11954   // Comparisons between two array types are ill-formed for operator<=>, so
11955   // we shouldn't emit any additional warnings about it.
11956   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11957     return;
11958 
11959   // For non-floating point types, check for self-comparisons of the form
11960   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11961   // often indicate logic errors in the program.
11962   //
11963   // NOTE: Don't warn about comparison expressions resulting from macro
11964   // expansion. Also don't warn about comparisons which are only self
11965   // comparisons within a template instantiation. The warnings should catch
11966   // obvious cases in the definition of the template anyways. The idea is to
11967   // warn when the typed comparison operator will always evaluate to the same
11968   // result.
11969 
11970   // Used for indexing into %select in warn_comparison_always
11971   enum {
11972     AlwaysConstant,
11973     AlwaysTrue,
11974     AlwaysFalse,
11975     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11976   };
11977 
11978   // C++2a [depr.array.comp]:
11979   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11980   //   operands of array type are deprecated.
11981   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11982       RHSStripped->getType()->isArrayType()) {
11983     S.Diag(Loc, diag::warn_depr_array_comparison)
11984         << LHS->getSourceRange() << RHS->getSourceRange()
11985         << LHSStripped->getType() << RHSStripped->getType();
11986     // Carry on to produce the tautological comparison warning, if this
11987     // expression is potentially-evaluated, we can resolve the array to a
11988     // non-weak declaration, and so on.
11989   }
11990 
11991   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11992     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11993       unsigned Result;
11994       switch (Opc) {
11995       case BO_EQ:
11996       case BO_LE:
11997       case BO_GE:
11998         Result = AlwaysTrue;
11999         break;
12000       case BO_NE:
12001       case BO_LT:
12002       case BO_GT:
12003         Result = AlwaysFalse;
12004         break;
12005       case BO_Cmp:
12006         Result = AlwaysEqual;
12007         break;
12008       default:
12009         Result = AlwaysConstant;
12010         break;
12011       }
12012       S.DiagRuntimeBehavior(Loc, nullptr,
12013                             S.PDiag(diag::warn_comparison_always)
12014                                 << 0 /*self-comparison*/
12015                                 << Result);
12016     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12017       // What is it always going to evaluate to?
12018       unsigned Result;
12019       switch (Opc) {
12020       case BO_EQ: // e.g. array1 == array2
12021         Result = AlwaysFalse;
12022         break;
12023       case BO_NE: // e.g. array1 != array2
12024         Result = AlwaysTrue;
12025         break;
12026       default: // e.g. array1 <= array2
12027         // The best we can say is 'a constant'
12028         Result = AlwaysConstant;
12029         break;
12030       }
12031       S.DiagRuntimeBehavior(Loc, nullptr,
12032                             S.PDiag(diag::warn_comparison_always)
12033                                 << 1 /*array comparison*/
12034                                 << Result);
12035     }
12036   }
12037 
12038   if (isa<CastExpr>(LHSStripped))
12039     LHSStripped = LHSStripped->IgnoreParenCasts();
12040   if (isa<CastExpr>(RHSStripped))
12041     RHSStripped = RHSStripped->IgnoreParenCasts();
12042 
12043   // Warn about comparisons against a string constant (unless the other
12044   // operand is null); the user probably wants string comparison function.
12045   Expr *LiteralString = nullptr;
12046   Expr *LiteralStringStripped = nullptr;
12047   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12048       !RHSStripped->isNullPointerConstant(S.Context,
12049                                           Expr::NPC_ValueDependentIsNull)) {
12050     LiteralString = LHS;
12051     LiteralStringStripped = LHSStripped;
12052   } else if ((isa<StringLiteral>(RHSStripped) ||
12053               isa<ObjCEncodeExpr>(RHSStripped)) &&
12054              !LHSStripped->isNullPointerConstant(S.Context,
12055                                           Expr::NPC_ValueDependentIsNull)) {
12056     LiteralString = RHS;
12057     LiteralStringStripped = RHSStripped;
12058   }
12059 
12060   if (LiteralString) {
12061     S.DiagRuntimeBehavior(Loc, nullptr,
12062                           S.PDiag(diag::warn_stringcompare)
12063                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
12064                               << LiteralString->getSourceRange());
12065   }
12066 }
12067 
12068 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12069   switch (CK) {
12070   default: {
12071 #ifndef NDEBUG
12072     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12073                  << "\n";
12074 #endif
12075     llvm_unreachable("unhandled cast kind");
12076   }
12077   case CK_UserDefinedConversion:
12078     return ICK_Identity;
12079   case CK_LValueToRValue:
12080     return ICK_Lvalue_To_Rvalue;
12081   case CK_ArrayToPointerDecay:
12082     return ICK_Array_To_Pointer;
12083   case CK_FunctionToPointerDecay:
12084     return ICK_Function_To_Pointer;
12085   case CK_IntegralCast:
12086     return ICK_Integral_Conversion;
12087   case CK_FloatingCast:
12088     return ICK_Floating_Conversion;
12089   case CK_IntegralToFloating:
12090   case CK_FloatingToIntegral:
12091     return ICK_Floating_Integral;
12092   case CK_IntegralComplexCast:
12093   case CK_FloatingComplexCast:
12094   case CK_FloatingComplexToIntegralComplex:
12095   case CK_IntegralComplexToFloatingComplex:
12096     return ICK_Complex_Conversion;
12097   case CK_FloatingComplexToReal:
12098   case CK_FloatingRealToComplex:
12099   case CK_IntegralComplexToReal:
12100   case CK_IntegralRealToComplex:
12101     return ICK_Complex_Real;
12102   }
12103 }
12104 
12105 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12106                                              QualType FromType,
12107                                              SourceLocation Loc) {
12108   // Check for a narrowing implicit conversion.
12109   StandardConversionSequence SCS;
12110   SCS.setAsIdentityConversion();
12111   SCS.setToType(0, FromType);
12112   SCS.setToType(1, ToType);
12113   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12114     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12115 
12116   APValue PreNarrowingValue;
12117   QualType PreNarrowingType;
12118   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12119                                PreNarrowingType,
12120                                /*IgnoreFloatToIntegralConversion*/ true)) {
12121   case NK_Dependent_Narrowing:
12122     // Implicit conversion to a narrower type, but the expression is
12123     // value-dependent so we can't tell whether it's actually narrowing.
12124   case NK_Not_Narrowing:
12125     return false;
12126 
12127   case NK_Constant_Narrowing:
12128     // Implicit conversion to a narrower type, and the value is not a constant
12129     // expression.
12130     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12131         << /*Constant*/ 1
12132         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12133     return true;
12134 
12135   case NK_Variable_Narrowing:
12136     // Implicit conversion to a narrower type, and the value is not a constant
12137     // expression.
12138   case NK_Type_Narrowing:
12139     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12140         << /*Constant*/ 0 << FromType << ToType;
12141     // TODO: It's not a constant expression, but what if the user intended it
12142     // to be? Can we produce notes to help them figure out why it isn't?
12143     return true;
12144   }
12145   llvm_unreachable("unhandled case in switch");
12146 }
12147 
12148 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12149                                                          ExprResult &LHS,
12150                                                          ExprResult &RHS,
12151                                                          SourceLocation Loc) {
12152   QualType LHSType = LHS.get()->getType();
12153   QualType RHSType = RHS.get()->getType();
12154   // Dig out the original argument type and expression before implicit casts
12155   // were applied. These are the types/expressions we need to check the
12156   // [expr.spaceship] requirements against.
12157   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12158   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12159   QualType LHSStrippedType = LHSStripped.get()->getType();
12160   QualType RHSStrippedType = RHSStripped.get()->getType();
12161 
12162   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12163   // other is not, the program is ill-formed.
12164   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12165     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12166     return QualType();
12167   }
12168 
12169   // FIXME: Consider combining this with checkEnumArithmeticConversions.
12170   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12171                     RHSStrippedType->isEnumeralType();
12172   if (NumEnumArgs == 1) {
12173     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12174     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12175     if (OtherTy->hasFloatingRepresentation()) {
12176       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12177       return QualType();
12178     }
12179   }
12180   if (NumEnumArgs == 2) {
12181     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12182     // type E, the operator yields the result of converting the operands
12183     // to the underlying type of E and applying <=> to the converted operands.
12184     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12185       S.InvalidOperands(Loc, LHS, RHS);
12186       return QualType();
12187     }
12188     QualType IntType =
12189         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12190     assert(IntType->isArithmeticType());
12191 
12192     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12193     // promote the boolean type, and all other promotable integer types, to
12194     // avoid this.
12195     if (IntType->isPromotableIntegerType())
12196       IntType = S.Context.getPromotedIntegerType(IntType);
12197 
12198     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12199     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12200     LHSType = RHSType = IntType;
12201   }
12202 
12203   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12204   // usual arithmetic conversions are applied to the operands.
12205   QualType Type =
12206       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12207   if (LHS.isInvalid() || RHS.isInvalid())
12208     return QualType();
12209   if (Type.isNull())
12210     return S.InvalidOperands(Loc, LHS, RHS);
12211 
12212   Optional<ComparisonCategoryType> CCT =
12213       getComparisonCategoryForBuiltinCmp(Type);
12214   if (!CCT)
12215     return S.InvalidOperands(Loc, LHS, RHS);
12216 
12217   bool HasNarrowing = checkThreeWayNarrowingConversion(
12218       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12219   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12220                                                    RHS.get()->getBeginLoc());
12221   if (HasNarrowing)
12222     return QualType();
12223 
12224   assert(!Type.isNull() && "composite type for <=> has not been set");
12225 
12226   return S.CheckComparisonCategoryType(
12227       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12228 }
12229 
12230 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12231                                                  ExprResult &RHS,
12232                                                  SourceLocation Loc,
12233                                                  BinaryOperatorKind Opc) {
12234   if (Opc == BO_Cmp)
12235     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12236 
12237   // C99 6.5.8p3 / C99 6.5.9p4
12238   QualType Type =
12239       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12240   if (LHS.isInvalid() || RHS.isInvalid())
12241     return QualType();
12242   if (Type.isNull())
12243     return S.InvalidOperands(Loc, LHS, RHS);
12244   assert(Type->isArithmeticType() || Type->isEnumeralType());
12245 
12246   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12247     return S.InvalidOperands(Loc, LHS, RHS);
12248 
12249   // Check for comparisons of floating point operands using != and ==.
12250   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12251     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12252 
12253   // The result of comparisons is 'bool' in C++, 'int' in C.
12254   return S.Context.getLogicalOperationType();
12255 }
12256 
12257 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12258   if (!NullE.get()->getType()->isAnyPointerType())
12259     return;
12260   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12261   if (!E.get()->getType()->isAnyPointerType() &&
12262       E.get()->isNullPointerConstant(Context,
12263                                      Expr::NPC_ValueDependentIsNotNull) ==
12264         Expr::NPCK_ZeroExpression) {
12265     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12266       if (CL->getValue() == 0)
12267         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12268             << NullValue
12269             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12270                                             NullValue ? "NULL" : "(void *)0");
12271     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12272         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12273         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12274         if (T == Context.CharTy)
12275           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12276               << NullValue
12277               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12278                                               NullValue ? "NULL" : "(void *)0");
12279       }
12280   }
12281 }
12282 
12283 // C99 6.5.8, C++ [expr.rel]
12284 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12285                                     SourceLocation Loc,
12286                                     BinaryOperatorKind Opc) {
12287   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12288   bool IsThreeWay = Opc == BO_Cmp;
12289   bool IsOrdered = IsRelational || IsThreeWay;
12290   auto IsAnyPointerType = [](ExprResult E) {
12291     QualType Ty = E.get()->getType();
12292     return Ty->isPointerType() || Ty->isMemberPointerType();
12293   };
12294 
12295   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12296   // type, array-to-pointer, ..., conversions are performed on both operands to
12297   // bring them to their composite type.
12298   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12299   // any type-related checks.
12300   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12301     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12302     if (LHS.isInvalid())
12303       return QualType();
12304     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12305     if (RHS.isInvalid())
12306       return QualType();
12307   } else {
12308     LHS = DefaultLvalueConversion(LHS.get());
12309     if (LHS.isInvalid())
12310       return QualType();
12311     RHS = DefaultLvalueConversion(RHS.get());
12312     if (RHS.isInvalid())
12313       return QualType();
12314   }
12315 
12316   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12317   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12318     CheckPtrComparisonWithNullChar(LHS, RHS);
12319     CheckPtrComparisonWithNullChar(RHS, LHS);
12320   }
12321 
12322   // Handle vector comparisons separately.
12323   if (LHS.get()->getType()->isVectorType() ||
12324       RHS.get()->getType()->isVectorType())
12325     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12326 
12327   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12328       RHS.get()->getType()->isVLSTBuiltinType())
12329     return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12330 
12331   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12332   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12333 
12334   QualType LHSType = LHS.get()->getType();
12335   QualType RHSType = RHS.get()->getType();
12336   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12337       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12338     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12339 
12340   const Expr::NullPointerConstantKind LHSNullKind =
12341       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12342   const Expr::NullPointerConstantKind RHSNullKind =
12343       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12344   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12345   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12346 
12347   auto computeResultTy = [&]() {
12348     if (Opc != BO_Cmp)
12349       return Context.getLogicalOperationType();
12350     assert(getLangOpts().CPlusPlus);
12351     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12352 
12353     QualType CompositeTy = LHS.get()->getType();
12354     assert(!CompositeTy->isReferenceType());
12355 
12356     Optional<ComparisonCategoryType> CCT =
12357         getComparisonCategoryForBuiltinCmp(CompositeTy);
12358     if (!CCT)
12359       return InvalidOperands(Loc, LHS, RHS);
12360 
12361     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12362       // P0946R0: Comparisons between a null pointer constant and an object
12363       // pointer result in std::strong_equality, which is ill-formed under
12364       // P1959R0.
12365       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12366           << (LHSIsNull ? LHS.get()->getSourceRange()
12367                         : RHS.get()->getSourceRange());
12368       return QualType();
12369     }
12370 
12371     return CheckComparisonCategoryType(
12372         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12373   };
12374 
12375   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12376     bool IsEquality = Opc == BO_EQ;
12377     if (RHSIsNull)
12378       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12379                                    RHS.get()->getSourceRange());
12380     else
12381       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12382                                    LHS.get()->getSourceRange());
12383   }
12384 
12385   if (IsOrdered && LHSType->isFunctionPointerType() &&
12386       RHSType->isFunctionPointerType()) {
12387     // Valid unless a relational comparison of function pointers
12388     bool IsError = Opc == BO_Cmp;
12389     auto DiagID =
12390         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12391         : getLangOpts().CPlusPlus
12392             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12393             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12394     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12395                       << RHS.get()->getSourceRange();
12396     if (IsError)
12397       return QualType();
12398   }
12399 
12400   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12401       (RHSType->isIntegerType() && !RHSIsNull)) {
12402     // Skip normal pointer conversion checks in this case; we have better
12403     // diagnostics for this below.
12404   } else if (getLangOpts().CPlusPlus) {
12405     // Equality comparison of a function pointer to a void pointer is invalid,
12406     // but we allow it as an extension.
12407     // FIXME: If we really want to allow this, should it be part of composite
12408     // pointer type computation so it works in conditionals too?
12409     if (!IsOrdered &&
12410         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12411          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12412       // This is a gcc extension compatibility comparison.
12413       // In a SFINAE context, we treat this as a hard error to maintain
12414       // conformance with the C++ standard.
12415       diagnoseFunctionPointerToVoidComparison(
12416           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12417 
12418       if (isSFINAEContext())
12419         return QualType();
12420 
12421       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12422       return computeResultTy();
12423     }
12424 
12425     // C++ [expr.eq]p2:
12426     //   If at least one operand is a pointer [...] bring them to their
12427     //   composite pointer type.
12428     // C++ [expr.spaceship]p6
12429     //  If at least one of the operands is of pointer type, [...] bring them
12430     //  to their composite pointer type.
12431     // C++ [expr.rel]p2:
12432     //   If both operands are pointers, [...] bring them to their composite
12433     //   pointer type.
12434     // For <=>, the only valid non-pointer types are arrays and functions, and
12435     // we already decayed those, so this is really the same as the relational
12436     // comparison rule.
12437     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12438             (IsOrdered ? 2 : 1) &&
12439         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12440                                          RHSType->isObjCObjectPointerType()))) {
12441       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12442         return QualType();
12443       return computeResultTy();
12444     }
12445   } else if (LHSType->isPointerType() &&
12446              RHSType->isPointerType()) { // C99 6.5.8p2
12447     // All of the following pointer-related warnings are GCC extensions, except
12448     // when handling null pointer constants.
12449     QualType LCanPointeeTy =
12450       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12451     QualType RCanPointeeTy =
12452       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12453 
12454     // C99 6.5.9p2 and C99 6.5.8p2
12455     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12456                                    RCanPointeeTy.getUnqualifiedType())) {
12457       if (IsRelational) {
12458         // Pointers both need to point to complete or incomplete types
12459         if ((LCanPointeeTy->isIncompleteType() !=
12460              RCanPointeeTy->isIncompleteType()) &&
12461             !getLangOpts().C11) {
12462           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12463               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12464               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12465               << RCanPointeeTy->isIncompleteType();
12466         }
12467       }
12468     } else if (!IsRelational &&
12469                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12470       // Valid unless comparison between non-null pointer and function pointer
12471       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12472           && !LHSIsNull && !RHSIsNull)
12473         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12474                                                 /*isError*/false);
12475     } else {
12476       // Invalid
12477       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12478     }
12479     if (LCanPointeeTy != RCanPointeeTy) {
12480       // Treat NULL constant as a special case in OpenCL.
12481       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12482         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12483           Diag(Loc,
12484                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12485               << LHSType << RHSType << 0 /* comparison */
12486               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12487         }
12488       }
12489       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12490       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12491       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12492                                                : CK_BitCast;
12493       if (LHSIsNull && !RHSIsNull)
12494         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12495       else
12496         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12497     }
12498     return computeResultTy();
12499   }
12500 
12501   if (getLangOpts().CPlusPlus) {
12502     // C++ [expr.eq]p4:
12503     //   Two operands of type std::nullptr_t or one operand of type
12504     //   std::nullptr_t and the other a null pointer constant compare equal.
12505     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12506       if (LHSType->isNullPtrType()) {
12507         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12508         return computeResultTy();
12509       }
12510       if (RHSType->isNullPtrType()) {
12511         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12512         return computeResultTy();
12513       }
12514     }
12515 
12516     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12517     // These aren't covered by the composite pointer type rules.
12518     if (!IsOrdered && RHSType->isNullPtrType() &&
12519         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12520       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12521       return computeResultTy();
12522     }
12523     if (!IsOrdered && LHSType->isNullPtrType() &&
12524         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12525       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12526       return computeResultTy();
12527     }
12528 
12529     if (IsRelational &&
12530         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12531          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12532       // HACK: Relational comparison of nullptr_t against a pointer type is
12533       // invalid per DR583, but we allow it within std::less<> and friends,
12534       // since otherwise common uses of it break.
12535       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12536       // friends to have std::nullptr_t overload candidates.
12537       DeclContext *DC = CurContext;
12538       if (isa<FunctionDecl>(DC))
12539         DC = DC->getParent();
12540       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12541         if (CTSD->isInStdNamespace() &&
12542             llvm::StringSwitch<bool>(CTSD->getName())
12543                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12544                 .Default(false)) {
12545           if (RHSType->isNullPtrType())
12546             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12547           else
12548             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12549           return computeResultTy();
12550         }
12551       }
12552     }
12553 
12554     // C++ [expr.eq]p2:
12555     //   If at least one operand is a pointer to member, [...] bring them to
12556     //   their composite pointer type.
12557     if (!IsOrdered &&
12558         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12559       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12560         return QualType();
12561       else
12562         return computeResultTy();
12563     }
12564   }
12565 
12566   // Handle block pointer types.
12567   if (!IsOrdered && LHSType->isBlockPointerType() &&
12568       RHSType->isBlockPointerType()) {
12569     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12570     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12571 
12572     if (!LHSIsNull && !RHSIsNull &&
12573         !Context.typesAreCompatible(lpointee, rpointee)) {
12574       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12575         << LHSType << RHSType << LHS.get()->getSourceRange()
12576         << RHS.get()->getSourceRange();
12577     }
12578     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12579     return computeResultTy();
12580   }
12581 
12582   // Allow block pointers to be compared with null pointer constants.
12583   if (!IsOrdered
12584       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12585           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12586     if (!LHSIsNull && !RHSIsNull) {
12587       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12588              ->getPointeeType()->isVoidType())
12589             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12590                 ->getPointeeType()->isVoidType())))
12591         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12592           << LHSType << RHSType << LHS.get()->getSourceRange()
12593           << RHS.get()->getSourceRange();
12594     }
12595     if (LHSIsNull && !RHSIsNull)
12596       LHS = ImpCastExprToType(LHS.get(), RHSType,
12597                               RHSType->isPointerType() ? CK_BitCast
12598                                 : CK_AnyPointerToBlockPointerCast);
12599     else
12600       RHS = ImpCastExprToType(RHS.get(), LHSType,
12601                               LHSType->isPointerType() ? CK_BitCast
12602                                 : CK_AnyPointerToBlockPointerCast);
12603     return computeResultTy();
12604   }
12605 
12606   if (LHSType->isObjCObjectPointerType() ||
12607       RHSType->isObjCObjectPointerType()) {
12608     const PointerType *LPT = LHSType->getAs<PointerType>();
12609     const PointerType *RPT = RHSType->getAs<PointerType>();
12610     if (LPT || RPT) {
12611       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12612       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12613 
12614       if (!LPtrToVoid && !RPtrToVoid &&
12615           !Context.typesAreCompatible(LHSType, RHSType)) {
12616         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12617                                           /*isError*/false);
12618       }
12619       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12620       // the RHS, but we have test coverage for this behavior.
12621       // FIXME: Consider using convertPointersToCompositeType in C++.
12622       if (LHSIsNull && !RHSIsNull) {
12623         Expr *E = LHS.get();
12624         if (getLangOpts().ObjCAutoRefCount)
12625           CheckObjCConversion(SourceRange(), RHSType, E,
12626                               CCK_ImplicitConversion);
12627         LHS = ImpCastExprToType(E, RHSType,
12628                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12629       }
12630       else {
12631         Expr *E = RHS.get();
12632         if (getLangOpts().ObjCAutoRefCount)
12633           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12634                               /*Diagnose=*/true,
12635                               /*DiagnoseCFAudited=*/false, Opc);
12636         RHS = ImpCastExprToType(E, LHSType,
12637                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12638       }
12639       return computeResultTy();
12640     }
12641     if (LHSType->isObjCObjectPointerType() &&
12642         RHSType->isObjCObjectPointerType()) {
12643       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12644         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12645                                           /*isError*/false);
12646       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12647         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12648 
12649       if (LHSIsNull && !RHSIsNull)
12650         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12651       else
12652         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12653       return computeResultTy();
12654     }
12655 
12656     if (!IsOrdered && LHSType->isBlockPointerType() &&
12657         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12658       LHS = ImpCastExprToType(LHS.get(), RHSType,
12659                               CK_BlockPointerToObjCPointerCast);
12660       return computeResultTy();
12661     } else if (!IsOrdered &&
12662                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12663                RHSType->isBlockPointerType()) {
12664       RHS = ImpCastExprToType(RHS.get(), LHSType,
12665                               CK_BlockPointerToObjCPointerCast);
12666       return computeResultTy();
12667     }
12668   }
12669   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12670       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12671     unsigned DiagID = 0;
12672     bool isError = false;
12673     if (LangOpts.DebuggerSupport) {
12674       // Under a debugger, allow the comparison of pointers to integers,
12675       // since users tend to want to compare addresses.
12676     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12677                (RHSIsNull && RHSType->isIntegerType())) {
12678       if (IsOrdered) {
12679         isError = getLangOpts().CPlusPlus;
12680         DiagID =
12681           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12682                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12683       }
12684     } else if (getLangOpts().CPlusPlus) {
12685       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12686       isError = true;
12687     } else if (IsOrdered)
12688       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12689     else
12690       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12691 
12692     if (DiagID) {
12693       Diag(Loc, DiagID)
12694         << LHSType << RHSType << LHS.get()->getSourceRange()
12695         << RHS.get()->getSourceRange();
12696       if (isError)
12697         return QualType();
12698     }
12699 
12700     if (LHSType->isIntegerType())
12701       LHS = ImpCastExprToType(LHS.get(), RHSType,
12702                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12703     else
12704       RHS = ImpCastExprToType(RHS.get(), LHSType,
12705                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12706     return computeResultTy();
12707   }
12708 
12709   // Handle block pointers.
12710   if (!IsOrdered && RHSIsNull
12711       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12712     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12713     return computeResultTy();
12714   }
12715   if (!IsOrdered && LHSIsNull
12716       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12717     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12718     return computeResultTy();
12719   }
12720 
12721   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12722     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12723       return computeResultTy();
12724     }
12725 
12726     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12727       return computeResultTy();
12728     }
12729 
12730     if (LHSIsNull && RHSType->isQueueT()) {
12731       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12732       return computeResultTy();
12733     }
12734 
12735     if (LHSType->isQueueT() && RHSIsNull) {
12736       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12737       return computeResultTy();
12738     }
12739   }
12740 
12741   return InvalidOperands(Loc, LHS, RHS);
12742 }
12743 
12744 // Return a signed ext_vector_type that is of identical size and number of
12745 // elements. For floating point vectors, return an integer type of identical
12746 // size and number of elements. In the non ext_vector_type case, search from
12747 // the largest type to the smallest type to avoid cases where long long == long,
12748 // where long gets picked over long long.
12749 QualType Sema::GetSignedVectorType(QualType V) {
12750   const VectorType *VTy = V->castAs<VectorType>();
12751   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12752 
12753   if (isa<ExtVectorType>(VTy)) {
12754     if (VTy->isExtVectorBoolType())
12755       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12756     if (TypeSize == Context.getTypeSize(Context.CharTy))
12757       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12758     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12759       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12760     if (TypeSize == Context.getTypeSize(Context.IntTy))
12761       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12762     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12763       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12764     if (TypeSize == Context.getTypeSize(Context.LongTy))
12765       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12766     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12767            "Unhandled vector element size in vector compare");
12768     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12769   }
12770 
12771   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12772     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12773                                  VectorType::GenericVector);
12774   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12775     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12776                                  VectorType::GenericVector);
12777   if (TypeSize == Context.getTypeSize(Context.LongTy))
12778     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12779                                  VectorType::GenericVector);
12780   if (TypeSize == Context.getTypeSize(Context.IntTy))
12781     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12782                                  VectorType::GenericVector);
12783   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12784     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12785                                  VectorType::GenericVector);
12786   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12787          "Unhandled vector element size in vector compare");
12788   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12789                                VectorType::GenericVector);
12790 }
12791 
12792 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12793   const BuiltinType *VTy = V->castAs<BuiltinType>();
12794   assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12795 
12796   const QualType ETy = V->getSveEltType(Context);
12797   const auto TypeSize = Context.getTypeSize(ETy);
12798 
12799   const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12800   const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12801   return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12802 }
12803 
12804 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12805 /// operates on extended vector types.  Instead of producing an IntTy result,
12806 /// like a scalar comparison, a vector comparison produces a vector of integer
12807 /// types.
12808 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12809                                           SourceLocation Loc,
12810                                           BinaryOperatorKind Opc) {
12811   if (Opc == BO_Cmp) {
12812     Diag(Loc, diag::err_three_way_vector_comparison);
12813     return QualType();
12814   }
12815 
12816   // Check to make sure we're operating on vectors of the same type and width,
12817   // Allowing one side to be a scalar of element type.
12818   QualType vType =
12819       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12820                           /*AllowBothBool*/ true,
12821                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12822                           /*AllowBooleanOperation*/ true,
12823                           /*ReportInvalid*/ true);
12824   if (vType.isNull())
12825     return vType;
12826 
12827   QualType LHSType = LHS.get()->getType();
12828 
12829   // Determine the return type of a vector compare. By default clang will return
12830   // a scalar for all vector compares except vector bool and vector pixel.
12831   // With the gcc compiler we will always return a vector type and with the xl
12832   // compiler we will always return a scalar type. This switch allows choosing
12833   // which behavior is prefered.
12834   if (getLangOpts().AltiVec) {
12835     switch (getLangOpts().getAltivecSrcCompat()) {
12836     case LangOptions::AltivecSrcCompatKind::Mixed:
12837       // If AltiVec, the comparison results in a numeric type, i.e.
12838       // bool for C++, int for C
12839       if (vType->castAs<VectorType>()->getVectorKind() ==
12840           VectorType::AltiVecVector)
12841         return Context.getLogicalOperationType();
12842       else
12843         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12844       break;
12845     case LangOptions::AltivecSrcCompatKind::GCC:
12846       // For GCC we always return the vector type.
12847       break;
12848     case LangOptions::AltivecSrcCompatKind::XL:
12849       return Context.getLogicalOperationType();
12850       break;
12851     }
12852   }
12853 
12854   // For non-floating point types, check for self-comparisons of the form
12855   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12856   // often indicate logic errors in the program.
12857   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12858 
12859   // Check for comparisons of floating point operands using != and ==.
12860   if (BinaryOperator::isEqualityOp(Opc) &&
12861       LHSType->hasFloatingRepresentation()) {
12862     assert(RHS.get()->getType()->hasFloatingRepresentation());
12863     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12864   }
12865 
12866   // Return a signed type for the vector.
12867   return GetSignedVectorType(vType);
12868 }
12869 
12870 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12871                                                   ExprResult &RHS,
12872                                                   SourceLocation Loc,
12873                                                   BinaryOperatorKind Opc) {
12874   if (Opc == BO_Cmp) {
12875     Diag(Loc, diag::err_three_way_vector_comparison);
12876     return QualType();
12877   }
12878 
12879   // Check to make sure we're operating on vectors of the same type and width,
12880   // Allowing one side to be a scalar of element type.
12881   QualType vType = CheckSizelessVectorOperands(
12882       LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12883 
12884   if (vType.isNull())
12885     return vType;
12886 
12887   QualType LHSType = LHS.get()->getType();
12888 
12889   // For non-floating point types, check for self-comparisons of the form
12890   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12891   // often indicate logic errors in the program.
12892   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12893 
12894   // Check for comparisons of floating point operands using != and ==.
12895   if (BinaryOperator::isEqualityOp(Opc) &&
12896       LHSType->hasFloatingRepresentation()) {
12897     assert(RHS.get()->getType()->hasFloatingRepresentation());
12898     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12899   }
12900 
12901   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12902   const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12903 
12904   if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12905       RHSBuiltinTy->isSVEBool())
12906     return LHSType;
12907 
12908   // Return a signed type for the vector.
12909   return GetSignedSizelessVectorType(vType);
12910 }
12911 
12912 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12913                                     const ExprResult &XorRHS,
12914                                     const SourceLocation Loc) {
12915   // Do not diagnose macros.
12916   if (Loc.isMacroID())
12917     return;
12918 
12919   // Do not diagnose if both LHS and RHS are macros.
12920   if (XorLHS.get()->getExprLoc().isMacroID() &&
12921       XorRHS.get()->getExprLoc().isMacroID())
12922     return;
12923 
12924   bool Negative = false;
12925   bool ExplicitPlus = false;
12926   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12927   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12928 
12929   if (!LHSInt)
12930     return;
12931   if (!RHSInt) {
12932     // Check negative literals.
12933     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12934       UnaryOperatorKind Opc = UO->getOpcode();
12935       if (Opc != UO_Minus && Opc != UO_Plus)
12936         return;
12937       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12938       if (!RHSInt)
12939         return;
12940       Negative = (Opc == UO_Minus);
12941       ExplicitPlus = !Negative;
12942     } else {
12943       return;
12944     }
12945   }
12946 
12947   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12948   llvm::APInt RightSideValue = RHSInt->getValue();
12949   if (LeftSideValue != 2 && LeftSideValue != 10)
12950     return;
12951 
12952   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12953     return;
12954 
12955   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12956       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12957   llvm::StringRef ExprStr =
12958       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12959 
12960   CharSourceRange XorRange =
12961       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12962   llvm::StringRef XorStr =
12963       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12964   // Do not diagnose if xor keyword/macro is used.
12965   if (XorStr == "xor")
12966     return;
12967 
12968   std::string LHSStr = std::string(Lexer::getSourceText(
12969       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12970       S.getSourceManager(), S.getLangOpts()));
12971   std::string RHSStr = std::string(Lexer::getSourceText(
12972       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12973       S.getSourceManager(), S.getLangOpts()));
12974 
12975   if (Negative) {
12976     RightSideValue = -RightSideValue;
12977     RHSStr = "-" + RHSStr;
12978   } else if (ExplicitPlus) {
12979     RHSStr = "+" + RHSStr;
12980   }
12981 
12982   StringRef LHSStrRef = LHSStr;
12983   StringRef RHSStrRef = RHSStr;
12984   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12985   // literals.
12986   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12987       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12988       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12989       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12990       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12991       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12992       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12993     return;
12994 
12995   bool SuggestXor =
12996       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12997   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12998   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12999   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13000     std::string SuggestedExpr = "1 << " + RHSStr;
13001     bool Overflow = false;
13002     llvm::APInt One = (LeftSideValue - 1);
13003     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13004     if (Overflow) {
13005       if (RightSideIntValue < 64)
13006         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13007             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13008             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13009       else if (RightSideIntValue == 64)
13010         S.Diag(Loc, diag::warn_xor_used_as_pow)
13011             << ExprStr << toString(XorValue, 10, true);
13012       else
13013         return;
13014     } else {
13015       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13016           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13017           << toString(PowValue, 10, true)
13018           << FixItHint::CreateReplacement(
13019                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13020     }
13021 
13022     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13023         << ("0x2 ^ " + RHSStr) << SuggestXor;
13024   } else if (LeftSideValue == 10) {
13025     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13026     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13027         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13028         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13029     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13030         << ("0xA ^ " + RHSStr) << SuggestXor;
13031   }
13032 }
13033 
13034 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13035                                           SourceLocation Loc) {
13036   // Ensure that either both operands are of the same vector type, or
13037   // one operand is of a vector type and the other is of its element type.
13038   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13039                                        /*AllowBothBool*/ true,
13040                                        /*AllowBoolConversions*/ false,
13041                                        /*AllowBooleanOperation*/ false,
13042                                        /*ReportInvalid*/ false);
13043   if (vType.isNull())
13044     return InvalidOperands(Loc, LHS, RHS);
13045   if (getLangOpts().OpenCL &&
13046       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13047       vType->hasFloatingRepresentation())
13048     return InvalidOperands(Loc, LHS, RHS);
13049   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13050   //        usage of the logical operators && and || with vectors in C. This
13051   //        check could be notionally dropped.
13052   if (!getLangOpts().CPlusPlus &&
13053       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13054     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13055 
13056   return GetSignedVectorType(LHS.get()->getType());
13057 }
13058 
13059 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13060                                               SourceLocation Loc,
13061                                               bool IsCompAssign) {
13062   if (!IsCompAssign) {
13063     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13064     if (LHS.isInvalid())
13065       return QualType();
13066   }
13067   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13068   if (RHS.isInvalid())
13069     return QualType();
13070 
13071   // For conversion purposes, we ignore any qualifiers.
13072   // For example, "const float" and "float" are equivalent.
13073   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13074   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13075 
13076   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13077   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13078   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13079 
13080   if (Context.hasSameType(LHSType, RHSType))
13081     return LHSType;
13082 
13083   // Type conversion may change LHS/RHS. Keep copies to the original results, in
13084   // case we have to return InvalidOperands.
13085   ExprResult OriginalLHS = LHS;
13086   ExprResult OriginalRHS = RHS;
13087   if (LHSMatType && !RHSMatType) {
13088     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13089     if (!RHS.isInvalid())
13090       return LHSType;
13091 
13092     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13093   }
13094 
13095   if (!LHSMatType && RHSMatType) {
13096     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13097     if (!LHS.isInvalid())
13098       return RHSType;
13099     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13100   }
13101 
13102   return InvalidOperands(Loc, LHS, RHS);
13103 }
13104 
13105 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13106                                            SourceLocation Loc,
13107                                            bool IsCompAssign) {
13108   if (!IsCompAssign) {
13109     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13110     if (LHS.isInvalid())
13111       return QualType();
13112   }
13113   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13114   if (RHS.isInvalid())
13115     return QualType();
13116 
13117   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13118   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13119   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13120 
13121   if (LHSMatType && RHSMatType) {
13122     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13123       return InvalidOperands(Loc, LHS, RHS);
13124 
13125     if (!Context.hasSameType(LHSMatType->getElementType(),
13126                              RHSMatType->getElementType()))
13127       return InvalidOperands(Loc, LHS, RHS);
13128 
13129     return Context.getConstantMatrixType(LHSMatType->getElementType(),
13130                                          LHSMatType->getNumRows(),
13131                                          RHSMatType->getNumColumns());
13132   }
13133   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13134 }
13135 
13136 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13137   switch (Opc) {
13138   default:
13139     return false;
13140   case BO_And:
13141   case BO_AndAssign:
13142   case BO_Or:
13143   case BO_OrAssign:
13144   case BO_Xor:
13145   case BO_XorAssign:
13146     return true;
13147   }
13148 }
13149 
13150 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13151                                            SourceLocation Loc,
13152                                            BinaryOperatorKind Opc) {
13153   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13154 
13155   bool IsCompAssign =
13156       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13157 
13158   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13159 
13160   if (LHS.get()->getType()->isVectorType() ||
13161       RHS.get()->getType()->isVectorType()) {
13162     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13163         RHS.get()->getType()->hasIntegerRepresentation())
13164       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13165                                  /*AllowBothBool*/ true,
13166                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
13167                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13168                                  /*ReportInvalid*/ true);
13169     return InvalidOperands(Loc, LHS, RHS);
13170   }
13171 
13172   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13173       RHS.get()->getType()->isVLSTBuiltinType()) {
13174     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13175         RHS.get()->getType()->hasIntegerRepresentation())
13176       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13177                                          ACK_BitwiseOp);
13178     return InvalidOperands(Loc, LHS, RHS);
13179   }
13180 
13181   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13182       RHS.get()->getType()->isVLSTBuiltinType()) {
13183     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13184         RHS.get()->getType()->hasIntegerRepresentation())
13185       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13186                                          ACK_BitwiseOp);
13187     return InvalidOperands(Loc, LHS, RHS);
13188   }
13189 
13190   if (Opc == BO_And)
13191     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13192 
13193   if (LHS.get()->getType()->hasFloatingRepresentation() ||
13194       RHS.get()->getType()->hasFloatingRepresentation())
13195     return InvalidOperands(Loc, LHS, RHS);
13196 
13197   ExprResult LHSResult = LHS, RHSResult = RHS;
13198   QualType compType = UsualArithmeticConversions(
13199       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13200   if (LHSResult.isInvalid() || RHSResult.isInvalid())
13201     return QualType();
13202   LHS = LHSResult.get();
13203   RHS = RHSResult.get();
13204 
13205   if (Opc == BO_Xor)
13206     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13207 
13208   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13209     return compType;
13210   return InvalidOperands(Loc, LHS, RHS);
13211 }
13212 
13213 // C99 6.5.[13,14]
13214 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13215                                            SourceLocation Loc,
13216                                            BinaryOperatorKind Opc) {
13217   // Check vector operands differently.
13218   if (LHS.get()->getType()->isVectorType() ||
13219       RHS.get()->getType()->isVectorType())
13220     return CheckVectorLogicalOperands(LHS, RHS, Loc);
13221 
13222   bool EnumConstantInBoolContext = false;
13223   for (const ExprResult &HS : {LHS, RHS}) {
13224     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13225       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13226       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13227         EnumConstantInBoolContext = true;
13228     }
13229   }
13230 
13231   if (EnumConstantInBoolContext)
13232     Diag(Loc, diag::warn_enum_constant_in_bool_context);
13233 
13234   // Diagnose cases where the user write a logical and/or but probably meant a
13235   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13236   // is a constant.
13237   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13238       !LHS.get()->getType()->isBooleanType() &&
13239       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13240       // Don't warn in macros or template instantiations.
13241       !Loc.isMacroID() && !inTemplateInstantiation()) {
13242     // If the RHS can be constant folded, and if it constant folds to something
13243     // that isn't 0 or 1 (which indicate a potential logical operation that
13244     // happened to fold to true/false) then warn.
13245     // Parens on the RHS are ignored.
13246     Expr::EvalResult EVResult;
13247     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13248       llvm::APSInt Result = EVResult.Val.getInt();
13249       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13250            !RHS.get()->getExprLoc().isMacroID()) ||
13251           (Result != 0 && Result != 1)) {
13252         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13253             << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13254         // Suggest replacing the logical operator with the bitwise version
13255         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13256             << (Opc == BO_LAnd ? "&" : "|")
13257             << FixItHint::CreateReplacement(
13258                    SourceRange(Loc, getLocForEndOfToken(Loc)),
13259                    Opc == BO_LAnd ? "&" : "|");
13260         if (Opc == BO_LAnd)
13261           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13262           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13263               << FixItHint::CreateRemoval(
13264                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13265                                  RHS.get()->getEndLoc()));
13266       }
13267     }
13268   }
13269 
13270   if (!Context.getLangOpts().CPlusPlus) {
13271     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13272     // not operate on the built-in scalar and vector float types.
13273     if (Context.getLangOpts().OpenCL &&
13274         Context.getLangOpts().OpenCLVersion < 120) {
13275       if (LHS.get()->getType()->isFloatingType() ||
13276           RHS.get()->getType()->isFloatingType())
13277         return InvalidOperands(Loc, LHS, RHS);
13278     }
13279 
13280     LHS = UsualUnaryConversions(LHS.get());
13281     if (LHS.isInvalid())
13282       return QualType();
13283 
13284     RHS = UsualUnaryConversions(RHS.get());
13285     if (RHS.isInvalid())
13286       return QualType();
13287 
13288     if (!LHS.get()->getType()->isScalarType() ||
13289         !RHS.get()->getType()->isScalarType())
13290       return InvalidOperands(Loc, LHS, RHS);
13291 
13292     return Context.IntTy;
13293   }
13294 
13295   // The following is safe because we only use this method for
13296   // non-overloadable operands.
13297 
13298   // C++ [expr.log.and]p1
13299   // C++ [expr.log.or]p1
13300   // The operands are both contextually converted to type bool.
13301   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13302   if (LHSRes.isInvalid())
13303     return InvalidOperands(Loc, LHS, RHS);
13304   LHS = LHSRes;
13305 
13306   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13307   if (RHSRes.isInvalid())
13308     return InvalidOperands(Loc, LHS, RHS);
13309   RHS = RHSRes;
13310 
13311   // C++ [expr.log.and]p2
13312   // C++ [expr.log.or]p2
13313   // The result is a bool.
13314   return Context.BoolTy;
13315 }
13316 
13317 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13318   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13319   if (!ME) return false;
13320   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13321   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13322       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13323   if (!Base) return false;
13324   return Base->getMethodDecl() != nullptr;
13325 }
13326 
13327 /// Is the given expression (which must be 'const') a reference to a
13328 /// variable which was originally non-const, but which has become
13329 /// 'const' due to being captured within a block?
13330 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13331 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13332   assert(E->isLValue() && E->getType().isConstQualified());
13333   E = E->IgnoreParens();
13334 
13335   // Must be a reference to a declaration from an enclosing scope.
13336   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13337   if (!DRE) return NCCK_None;
13338   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13339 
13340   // The declaration must be a variable which is not declared 'const'.
13341   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13342   if (!var) return NCCK_None;
13343   if (var->getType().isConstQualified()) return NCCK_None;
13344   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13345 
13346   // Decide whether the first capture was for a block or a lambda.
13347   DeclContext *DC = S.CurContext, *Prev = nullptr;
13348   // Decide whether the first capture was for a block or a lambda.
13349   while (DC) {
13350     // For init-capture, it is possible that the variable belongs to the
13351     // template pattern of the current context.
13352     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13353       if (var->isInitCapture() &&
13354           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13355         break;
13356     if (DC == var->getDeclContext())
13357       break;
13358     Prev = DC;
13359     DC = DC->getParent();
13360   }
13361   // Unless we have an init-capture, we've gone one step too far.
13362   if (!var->isInitCapture())
13363     DC = Prev;
13364   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13365 }
13366 
13367 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13368   Ty = Ty.getNonReferenceType();
13369   if (IsDereference && Ty->isPointerType())
13370     Ty = Ty->getPointeeType();
13371   return !Ty.isConstQualified();
13372 }
13373 
13374 // Update err_typecheck_assign_const and note_typecheck_assign_const
13375 // when this enum is changed.
13376 enum {
13377   ConstFunction,
13378   ConstVariable,
13379   ConstMember,
13380   ConstMethod,
13381   NestedConstMember,
13382   ConstUnknown,  // Keep as last element
13383 };
13384 
13385 /// Emit the "read-only variable not assignable" error and print notes to give
13386 /// more information about why the variable is not assignable, such as pointing
13387 /// to the declaration of a const variable, showing that a method is const, or
13388 /// that the function is returning a const reference.
13389 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13390                                     SourceLocation Loc) {
13391   SourceRange ExprRange = E->getSourceRange();
13392 
13393   // Only emit one error on the first const found.  All other consts will emit
13394   // a note to the error.
13395   bool DiagnosticEmitted = false;
13396 
13397   // Track if the current expression is the result of a dereference, and if the
13398   // next checked expression is the result of a dereference.
13399   bool IsDereference = false;
13400   bool NextIsDereference = false;
13401 
13402   // Loop to process MemberExpr chains.
13403   while (true) {
13404     IsDereference = NextIsDereference;
13405 
13406     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13407     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13408       NextIsDereference = ME->isArrow();
13409       const ValueDecl *VD = ME->getMemberDecl();
13410       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13411         // Mutable fields can be modified even if the class is const.
13412         if (Field->isMutable()) {
13413           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13414           break;
13415         }
13416 
13417         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13418           if (!DiagnosticEmitted) {
13419             S.Diag(Loc, diag::err_typecheck_assign_const)
13420                 << ExprRange << ConstMember << false /*static*/ << Field
13421                 << Field->getType();
13422             DiagnosticEmitted = true;
13423           }
13424           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13425               << ConstMember << false /*static*/ << Field << Field->getType()
13426               << Field->getSourceRange();
13427         }
13428         E = ME->getBase();
13429         continue;
13430       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13431         if (VDecl->getType().isConstQualified()) {
13432           if (!DiagnosticEmitted) {
13433             S.Diag(Loc, diag::err_typecheck_assign_const)
13434                 << ExprRange << ConstMember << true /*static*/ << VDecl
13435                 << VDecl->getType();
13436             DiagnosticEmitted = true;
13437           }
13438           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13439               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13440               << VDecl->getSourceRange();
13441         }
13442         // Static fields do not inherit constness from parents.
13443         break;
13444       }
13445       break; // End MemberExpr
13446     } else if (const ArraySubscriptExpr *ASE =
13447                    dyn_cast<ArraySubscriptExpr>(E)) {
13448       E = ASE->getBase()->IgnoreParenImpCasts();
13449       continue;
13450     } else if (const ExtVectorElementExpr *EVE =
13451                    dyn_cast<ExtVectorElementExpr>(E)) {
13452       E = EVE->getBase()->IgnoreParenImpCasts();
13453       continue;
13454     }
13455     break;
13456   }
13457 
13458   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13459     // Function calls
13460     const FunctionDecl *FD = CE->getDirectCallee();
13461     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13462       if (!DiagnosticEmitted) {
13463         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13464                                                       << ConstFunction << FD;
13465         DiagnosticEmitted = true;
13466       }
13467       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13468              diag::note_typecheck_assign_const)
13469           << ConstFunction << FD << FD->getReturnType()
13470           << FD->getReturnTypeSourceRange();
13471     }
13472   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13473     // Point to variable declaration.
13474     if (const ValueDecl *VD = DRE->getDecl()) {
13475       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13476         if (!DiagnosticEmitted) {
13477           S.Diag(Loc, diag::err_typecheck_assign_const)
13478               << ExprRange << ConstVariable << VD << VD->getType();
13479           DiagnosticEmitted = true;
13480         }
13481         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13482             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13483       }
13484     }
13485   } else if (isa<CXXThisExpr>(E)) {
13486     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13487       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13488         if (MD->isConst()) {
13489           if (!DiagnosticEmitted) {
13490             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13491                                                           << ConstMethod << MD;
13492             DiagnosticEmitted = true;
13493           }
13494           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13495               << ConstMethod << MD << MD->getSourceRange();
13496         }
13497       }
13498     }
13499   }
13500 
13501   if (DiagnosticEmitted)
13502     return;
13503 
13504   // Can't determine a more specific message, so display the generic error.
13505   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13506 }
13507 
13508 enum OriginalExprKind {
13509   OEK_Variable,
13510   OEK_Member,
13511   OEK_LValue
13512 };
13513 
13514 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13515                                          const RecordType *Ty,
13516                                          SourceLocation Loc, SourceRange Range,
13517                                          OriginalExprKind OEK,
13518                                          bool &DiagnosticEmitted) {
13519   std::vector<const RecordType *> RecordTypeList;
13520   RecordTypeList.push_back(Ty);
13521   unsigned NextToCheckIndex = 0;
13522   // We walk the record hierarchy breadth-first to ensure that we print
13523   // diagnostics in field nesting order.
13524   while (RecordTypeList.size() > NextToCheckIndex) {
13525     bool IsNested = NextToCheckIndex > 0;
13526     for (const FieldDecl *Field :
13527          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13528       // First, check every field for constness.
13529       QualType FieldTy = Field->getType();
13530       if (FieldTy.isConstQualified()) {
13531         if (!DiagnosticEmitted) {
13532           S.Diag(Loc, diag::err_typecheck_assign_const)
13533               << Range << NestedConstMember << OEK << VD
13534               << IsNested << Field;
13535           DiagnosticEmitted = true;
13536         }
13537         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13538             << NestedConstMember << IsNested << Field
13539             << FieldTy << Field->getSourceRange();
13540       }
13541 
13542       // Then we append it to the list to check next in order.
13543       FieldTy = FieldTy.getCanonicalType();
13544       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13545         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13546           RecordTypeList.push_back(FieldRecTy);
13547       }
13548     }
13549     ++NextToCheckIndex;
13550   }
13551 }
13552 
13553 /// Emit an error for the case where a record we are trying to assign to has a
13554 /// const-qualified field somewhere in its hierarchy.
13555 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13556                                          SourceLocation Loc) {
13557   QualType Ty = E->getType();
13558   assert(Ty->isRecordType() && "lvalue was not record?");
13559   SourceRange Range = E->getSourceRange();
13560   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13561   bool DiagEmitted = false;
13562 
13563   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13564     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13565             Range, OEK_Member, DiagEmitted);
13566   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13567     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13568             Range, OEK_Variable, DiagEmitted);
13569   else
13570     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13571             Range, OEK_LValue, DiagEmitted);
13572   if (!DiagEmitted)
13573     DiagnoseConstAssignment(S, E, Loc);
13574 }
13575 
13576 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13577 /// emit an error and return true.  If so, return false.
13578 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13579   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13580 
13581   S.CheckShadowingDeclModification(E, Loc);
13582 
13583   SourceLocation OrigLoc = Loc;
13584   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13585                                                               &Loc);
13586   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13587     IsLV = Expr::MLV_InvalidMessageExpression;
13588   if (IsLV == Expr::MLV_Valid)
13589     return false;
13590 
13591   unsigned DiagID = 0;
13592   bool NeedType = false;
13593   switch (IsLV) { // C99 6.5.16p2
13594   case Expr::MLV_ConstQualified:
13595     // Use a specialized diagnostic when we're assigning to an object
13596     // from an enclosing function or block.
13597     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13598       if (NCCK == NCCK_Block)
13599         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13600       else
13601         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13602       break;
13603     }
13604 
13605     // In ARC, use some specialized diagnostics for occasions where we
13606     // infer 'const'.  These are always pseudo-strong variables.
13607     if (S.getLangOpts().ObjCAutoRefCount) {
13608       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13609       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13610         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13611 
13612         // Use the normal diagnostic if it's pseudo-__strong but the
13613         // user actually wrote 'const'.
13614         if (var->isARCPseudoStrong() &&
13615             (!var->getTypeSourceInfo() ||
13616              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13617           // There are three pseudo-strong cases:
13618           //  - self
13619           ObjCMethodDecl *method = S.getCurMethodDecl();
13620           if (method && var == method->getSelfDecl()) {
13621             DiagID = method->isClassMethod()
13622               ? diag::err_typecheck_arc_assign_self_class_method
13623               : diag::err_typecheck_arc_assign_self;
13624 
13625           //  - Objective-C externally_retained attribute.
13626           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13627                      isa<ParmVarDecl>(var)) {
13628             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13629 
13630           //  - fast enumeration variables
13631           } else {
13632             DiagID = diag::err_typecheck_arr_assign_enumeration;
13633           }
13634 
13635           SourceRange Assign;
13636           if (Loc != OrigLoc)
13637             Assign = SourceRange(OrigLoc, OrigLoc);
13638           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13639           // We need to preserve the AST regardless, so migration tool
13640           // can do its job.
13641           return false;
13642         }
13643       }
13644     }
13645 
13646     // If none of the special cases above are triggered, then this is a
13647     // simple const assignment.
13648     if (DiagID == 0) {
13649       DiagnoseConstAssignment(S, E, Loc);
13650       return true;
13651     }
13652 
13653     break;
13654   case Expr::MLV_ConstAddrSpace:
13655     DiagnoseConstAssignment(S, E, Loc);
13656     return true;
13657   case Expr::MLV_ConstQualifiedField:
13658     DiagnoseRecursiveConstFields(S, E, Loc);
13659     return true;
13660   case Expr::MLV_ArrayType:
13661   case Expr::MLV_ArrayTemporary:
13662     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13663     NeedType = true;
13664     break;
13665   case Expr::MLV_NotObjectType:
13666     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13667     NeedType = true;
13668     break;
13669   case Expr::MLV_LValueCast:
13670     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13671     break;
13672   case Expr::MLV_Valid:
13673     llvm_unreachable("did not take early return for MLV_Valid");
13674   case Expr::MLV_InvalidExpression:
13675   case Expr::MLV_MemberFunction:
13676   case Expr::MLV_ClassTemporary:
13677     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13678     break;
13679   case Expr::MLV_IncompleteType:
13680   case Expr::MLV_IncompleteVoidType:
13681     return S.RequireCompleteType(Loc, E->getType(),
13682              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13683   case Expr::MLV_DuplicateVectorComponents:
13684     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13685     break;
13686   case Expr::MLV_NoSetterProperty:
13687     llvm_unreachable("readonly properties should be processed differently");
13688   case Expr::MLV_InvalidMessageExpression:
13689     DiagID = diag::err_readonly_message_assignment;
13690     break;
13691   case Expr::MLV_SubObjCPropertySetting:
13692     DiagID = diag::err_no_subobject_property_setting;
13693     break;
13694   }
13695 
13696   SourceRange Assign;
13697   if (Loc != OrigLoc)
13698     Assign = SourceRange(OrigLoc, OrigLoc);
13699   if (NeedType)
13700     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13701   else
13702     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13703   return true;
13704 }
13705 
13706 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13707                                          SourceLocation Loc,
13708                                          Sema &Sema) {
13709   if (Sema.inTemplateInstantiation())
13710     return;
13711   if (Sema.isUnevaluatedContext())
13712     return;
13713   if (Loc.isInvalid() || Loc.isMacroID())
13714     return;
13715   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13716     return;
13717 
13718   // C / C++ fields
13719   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13720   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13721   if (ML && MR) {
13722     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13723       return;
13724     const ValueDecl *LHSDecl =
13725         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13726     const ValueDecl *RHSDecl =
13727         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13728     if (LHSDecl != RHSDecl)
13729       return;
13730     if (LHSDecl->getType().isVolatileQualified())
13731       return;
13732     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13733       if (RefTy->getPointeeType().isVolatileQualified())
13734         return;
13735 
13736     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13737   }
13738 
13739   // Objective-C instance variables
13740   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13741   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13742   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13743     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13744     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13745     if (RL && RR && RL->getDecl() == RR->getDecl())
13746       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13747   }
13748 }
13749 
13750 // C99 6.5.16.1
13751 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13752                                        SourceLocation Loc,
13753                                        QualType CompoundType) {
13754   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13755 
13756   // Verify that LHS is a modifiable lvalue, and emit error if not.
13757   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13758     return QualType();
13759 
13760   QualType LHSType = LHSExpr->getType();
13761   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13762                                              CompoundType;
13763   // OpenCL v1.2 s6.1.1.1 p2:
13764   // The half data type can only be used to declare a pointer to a buffer that
13765   // contains half values
13766   if (getLangOpts().OpenCL &&
13767       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13768       LHSType->isHalfType()) {
13769     Diag(Loc, diag::err_opencl_half_load_store) << 1
13770         << LHSType.getUnqualifiedType();
13771     return QualType();
13772   }
13773 
13774   AssignConvertType ConvTy;
13775   if (CompoundType.isNull()) {
13776     Expr *RHSCheck = RHS.get();
13777 
13778     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13779 
13780     QualType LHSTy(LHSType);
13781     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13782     if (RHS.isInvalid())
13783       return QualType();
13784     // Special case of NSObject attributes on c-style pointer types.
13785     if (ConvTy == IncompatiblePointer &&
13786         ((Context.isObjCNSObjectType(LHSType) &&
13787           RHSType->isObjCObjectPointerType()) ||
13788          (Context.isObjCNSObjectType(RHSType) &&
13789           LHSType->isObjCObjectPointerType())))
13790       ConvTy = Compatible;
13791 
13792     if (ConvTy == Compatible &&
13793         LHSType->isObjCObjectType())
13794         Diag(Loc, diag::err_objc_object_assignment)
13795           << LHSType;
13796 
13797     // If the RHS is a unary plus or minus, check to see if they = and + are
13798     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13799     // instead of "x += 4".
13800     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13801       RHSCheck = ICE->getSubExpr();
13802     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13803       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13804           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13805           // Only if the two operators are exactly adjacent.
13806           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13807           // And there is a space or other character before the subexpr of the
13808           // unary +/-.  We don't want to warn on "x=-1".
13809           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13810           UO->getSubExpr()->getBeginLoc().isFileID()) {
13811         Diag(Loc, diag::warn_not_compound_assign)
13812           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13813           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13814       }
13815     }
13816 
13817     if (ConvTy == Compatible) {
13818       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13819         // Warn about retain cycles where a block captures the LHS, but
13820         // not if the LHS is a simple variable into which the block is
13821         // being stored...unless that variable can be captured by reference!
13822         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13823         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13824         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13825           checkRetainCycles(LHSExpr, RHS.get());
13826       }
13827 
13828       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13829           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13830         // It is safe to assign a weak reference into a strong variable.
13831         // Although this code can still have problems:
13832         //   id x = self.weakProp;
13833         //   id y = self.weakProp;
13834         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13835         // paths through the function. This should be revisited if
13836         // -Wrepeated-use-of-weak is made flow-sensitive.
13837         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13838         // variable, which will be valid for the current autorelease scope.
13839         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13840                              RHS.get()->getBeginLoc()))
13841           getCurFunction()->markSafeWeakUse(RHS.get());
13842 
13843       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13844         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13845       }
13846     }
13847   } else {
13848     // Compound assignment "x += y"
13849     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13850   }
13851 
13852   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13853                                RHS.get(), AA_Assigning))
13854     return QualType();
13855 
13856   CheckForNullPointerDereference(*this, LHSExpr);
13857 
13858   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13859     if (CompoundType.isNull()) {
13860       // C++2a [expr.ass]p5:
13861       //   A simple-assignment whose left operand is of a volatile-qualified
13862       //   type is deprecated unless the assignment is either a discarded-value
13863       //   expression or an unevaluated operand
13864       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13865     } else {
13866       // C++2a [expr.ass]p6:
13867       //   [Compound-assignment] expressions are deprecated if E1 has
13868       //   volatile-qualified type
13869       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13870     }
13871   }
13872 
13873   // C11 6.5.16p3: The type of an assignment expression is the type of the
13874   // left operand would have after lvalue conversion.
13875   // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13876   // qualified type, the value has the unqualified version of the type of the
13877   // lvalue; additionally, if the lvalue has atomic type, the value has the
13878   // non-atomic version of the type of the lvalue.
13879   // C++ 5.17p1: the type of the assignment expression is that of its left
13880   // operand.
13881   return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13882 }
13883 
13884 // Only ignore explicit casts to void.
13885 static bool IgnoreCommaOperand(const Expr *E) {
13886   E = E->IgnoreParens();
13887 
13888   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13889     if (CE->getCastKind() == CK_ToVoid) {
13890       return true;
13891     }
13892 
13893     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13894     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13895         CE->getSubExpr()->getType()->isDependentType()) {
13896       return true;
13897     }
13898   }
13899 
13900   return false;
13901 }
13902 
13903 // Look for instances where it is likely the comma operator is confused with
13904 // another operator.  There is an explicit list of acceptable expressions for
13905 // the left hand side of the comma operator, otherwise emit a warning.
13906 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13907   // No warnings in macros
13908   if (Loc.isMacroID())
13909     return;
13910 
13911   // Don't warn in template instantiations.
13912   if (inTemplateInstantiation())
13913     return;
13914 
13915   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13916   // instead, skip more than needed, then call back into here with the
13917   // CommaVisitor in SemaStmt.cpp.
13918   // The listed locations are the initialization and increment portions
13919   // of a for loop.  The additional checks are on the condition of
13920   // if statements, do/while loops, and for loops.
13921   // Differences in scope flags for C89 mode requires the extra logic.
13922   const unsigned ForIncrementFlags =
13923       getLangOpts().C99 || getLangOpts().CPlusPlus
13924           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13925           : Scope::ContinueScope | Scope::BreakScope;
13926   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13927   const unsigned ScopeFlags = getCurScope()->getFlags();
13928   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13929       (ScopeFlags & ForInitFlags) == ForInitFlags)
13930     return;
13931 
13932   // If there are multiple comma operators used together, get the RHS of the
13933   // of the comma operator as the LHS.
13934   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13935     if (BO->getOpcode() != BO_Comma)
13936       break;
13937     LHS = BO->getRHS();
13938   }
13939 
13940   // Only allow some expressions on LHS to not warn.
13941   if (IgnoreCommaOperand(LHS))
13942     return;
13943 
13944   Diag(Loc, diag::warn_comma_operator);
13945   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13946       << LHS->getSourceRange()
13947       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13948                                     LangOpts.CPlusPlus ? "static_cast<void>("
13949                                                        : "(void)(")
13950       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13951                                     ")");
13952 }
13953 
13954 // C99 6.5.17
13955 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13956                                    SourceLocation Loc) {
13957   LHS = S.CheckPlaceholderExpr(LHS.get());
13958   RHS = S.CheckPlaceholderExpr(RHS.get());
13959   if (LHS.isInvalid() || RHS.isInvalid())
13960     return QualType();
13961 
13962   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13963   // operands, but not unary promotions.
13964   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13965 
13966   // So we treat the LHS as a ignored value, and in C++ we allow the
13967   // containing site to determine what should be done with the RHS.
13968   LHS = S.IgnoredValueConversions(LHS.get());
13969   if (LHS.isInvalid())
13970     return QualType();
13971 
13972   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13973 
13974   if (!S.getLangOpts().CPlusPlus) {
13975     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13976     if (RHS.isInvalid())
13977       return QualType();
13978     if (!RHS.get()->getType()->isVoidType())
13979       S.RequireCompleteType(Loc, RHS.get()->getType(),
13980                             diag::err_incomplete_type);
13981   }
13982 
13983   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13984     S.DiagnoseCommaOperator(LHS.get(), Loc);
13985 
13986   return RHS.get()->getType();
13987 }
13988 
13989 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13990 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13991 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13992                                                ExprValueKind &VK,
13993                                                ExprObjectKind &OK,
13994                                                SourceLocation OpLoc,
13995                                                bool IsInc, bool IsPrefix) {
13996   if (Op->isTypeDependent())
13997     return S.Context.DependentTy;
13998 
13999   QualType ResType = Op->getType();
14000   // Atomic types can be used for increment / decrement where the non-atomic
14001   // versions can, so ignore the _Atomic() specifier for the purpose of
14002   // checking.
14003   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14004     ResType = ResAtomicType->getValueType();
14005 
14006   assert(!ResType.isNull() && "no type for increment/decrement expression");
14007 
14008   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14009     // Decrement of bool is not allowed.
14010     if (!IsInc) {
14011       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14012       return QualType();
14013     }
14014     // Increment of bool sets it to true, but is deprecated.
14015     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14016                                               : diag::warn_increment_bool)
14017       << Op->getSourceRange();
14018   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14019     // Error on enum increments and decrements in C++ mode
14020     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14021     return QualType();
14022   } else if (ResType->isRealType()) {
14023     // OK!
14024   } else if (ResType->isPointerType()) {
14025     // C99 6.5.2.4p2, 6.5.6p2
14026     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14027       return QualType();
14028   } else if (ResType->isObjCObjectPointerType()) {
14029     // On modern runtimes, ObjC pointer arithmetic is forbidden.
14030     // Otherwise, we just need a complete type.
14031     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14032         checkArithmeticOnObjCPointer(S, OpLoc, Op))
14033       return QualType();
14034   } else if (ResType->isAnyComplexType()) {
14035     // C99 does not support ++/-- on complex types, we allow as an extension.
14036     S.Diag(OpLoc, diag::ext_integer_increment_complex)
14037       << ResType << Op->getSourceRange();
14038   } else if (ResType->isPlaceholderType()) {
14039     ExprResult PR = S.CheckPlaceholderExpr(Op);
14040     if (PR.isInvalid()) return QualType();
14041     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14042                                           IsInc, IsPrefix);
14043   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14044     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14045   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14046              (ResType->castAs<VectorType>()->getVectorKind() !=
14047               VectorType::AltiVecBool)) {
14048     // The z vector extensions allow ++ and -- for non-bool vectors.
14049   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14050             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14051     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14052   } else {
14053     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14054       << ResType << int(IsInc) << Op->getSourceRange();
14055     return QualType();
14056   }
14057   // At this point, we know we have a real, complex or pointer type.
14058   // Now make sure the operand is a modifiable lvalue.
14059   if (CheckForModifiableLvalue(Op, OpLoc, S))
14060     return QualType();
14061   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14062     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14063     //   An operand with volatile-qualified type is deprecated
14064     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14065         << IsInc << ResType;
14066   }
14067   // In C++, a prefix increment is the same type as the operand. Otherwise
14068   // (in C or with postfix), the increment is the unqualified type of the
14069   // operand.
14070   if (IsPrefix && S.getLangOpts().CPlusPlus) {
14071     VK = VK_LValue;
14072     OK = Op->getObjectKind();
14073     return ResType;
14074   } else {
14075     VK = VK_PRValue;
14076     return ResType.getUnqualifiedType();
14077   }
14078 }
14079 
14080 
14081 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14082 /// This routine allows us to typecheck complex/recursive expressions
14083 /// where the declaration is needed for type checking. We only need to
14084 /// handle cases when the expression references a function designator
14085 /// or is an lvalue. Here are some examples:
14086 ///  - &(x) => x
14087 ///  - &*****f => f for f a function designator.
14088 ///  - &s.xx => s
14089 ///  - &s.zz[1].yy -> s, if zz is an array
14090 ///  - *(x + 1) -> x, if x is an array
14091 ///  - &"123"[2] -> 0
14092 ///  - & __real__ x -> x
14093 ///
14094 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14095 /// members.
14096 static ValueDecl *getPrimaryDecl(Expr *E) {
14097   switch (E->getStmtClass()) {
14098   case Stmt::DeclRefExprClass:
14099     return cast<DeclRefExpr>(E)->getDecl();
14100   case Stmt::MemberExprClass:
14101     // If this is an arrow operator, the address is an offset from
14102     // the base's value, so the object the base refers to is
14103     // irrelevant.
14104     if (cast<MemberExpr>(E)->isArrow())
14105       return nullptr;
14106     // Otherwise, the expression refers to a part of the base
14107     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14108   case Stmt::ArraySubscriptExprClass: {
14109     // FIXME: This code shouldn't be necessary!  We should catch the implicit
14110     // promotion of register arrays earlier.
14111     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14112     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14113       if (ICE->getSubExpr()->getType()->isArrayType())
14114         return getPrimaryDecl(ICE->getSubExpr());
14115     }
14116     return nullptr;
14117   }
14118   case Stmt::UnaryOperatorClass: {
14119     UnaryOperator *UO = cast<UnaryOperator>(E);
14120 
14121     switch(UO->getOpcode()) {
14122     case UO_Real:
14123     case UO_Imag:
14124     case UO_Extension:
14125       return getPrimaryDecl(UO->getSubExpr());
14126     default:
14127       return nullptr;
14128     }
14129   }
14130   case Stmt::ParenExprClass:
14131     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14132   case Stmt::ImplicitCastExprClass:
14133     // If the result of an implicit cast is an l-value, we care about
14134     // the sub-expression; otherwise, the result here doesn't matter.
14135     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14136   case Stmt::CXXUuidofExprClass:
14137     return cast<CXXUuidofExpr>(E)->getGuidDecl();
14138   default:
14139     return nullptr;
14140   }
14141 }
14142 
14143 namespace {
14144 enum {
14145   AO_Bit_Field = 0,
14146   AO_Vector_Element = 1,
14147   AO_Property_Expansion = 2,
14148   AO_Register_Variable = 3,
14149   AO_Matrix_Element = 4,
14150   AO_No_Error = 5
14151 };
14152 }
14153 /// Diagnose invalid operand for address of operations.
14154 ///
14155 /// \param Type The type of operand which cannot have its address taken.
14156 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14157                                          Expr *E, unsigned Type) {
14158   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14159 }
14160 
14161 /// CheckAddressOfOperand - The operand of & must be either a function
14162 /// designator or an lvalue designating an object. If it is an lvalue, the
14163 /// object cannot be declared with storage class register or be a bit field.
14164 /// Note: The usual conversions are *not* applied to the operand of the &
14165 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14166 /// In C++, the operand might be an overloaded function name, in which case
14167 /// we allow the '&' but retain the overloaded-function type.
14168 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14169   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14170     if (PTy->getKind() == BuiltinType::Overload) {
14171       Expr *E = OrigOp.get()->IgnoreParens();
14172       if (!isa<OverloadExpr>(E)) {
14173         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14174         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14175           << OrigOp.get()->getSourceRange();
14176         return QualType();
14177       }
14178 
14179       OverloadExpr *Ovl = cast<OverloadExpr>(E);
14180       if (isa<UnresolvedMemberExpr>(Ovl))
14181         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14182           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14183             << OrigOp.get()->getSourceRange();
14184           return QualType();
14185         }
14186 
14187       return Context.OverloadTy;
14188     }
14189 
14190     if (PTy->getKind() == BuiltinType::UnknownAny)
14191       return Context.UnknownAnyTy;
14192 
14193     if (PTy->getKind() == BuiltinType::BoundMember) {
14194       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14195         << OrigOp.get()->getSourceRange();
14196       return QualType();
14197     }
14198 
14199     OrigOp = CheckPlaceholderExpr(OrigOp.get());
14200     if (OrigOp.isInvalid()) return QualType();
14201   }
14202 
14203   if (OrigOp.get()->isTypeDependent())
14204     return Context.DependentTy;
14205 
14206   assert(!OrigOp.get()->hasPlaceholderType());
14207 
14208   // Make sure to ignore parentheses in subsequent checks
14209   Expr *op = OrigOp.get()->IgnoreParens();
14210 
14211   // In OpenCL captures for blocks called as lambda functions
14212   // are located in the private address space. Blocks used in
14213   // enqueue_kernel can be located in a different address space
14214   // depending on a vendor implementation. Thus preventing
14215   // taking an address of the capture to avoid invalid AS casts.
14216   if (LangOpts.OpenCL) {
14217     auto* VarRef = dyn_cast<DeclRefExpr>(op);
14218     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14219       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14220       return QualType();
14221     }
14222   }
14223 
14224   if (getLangOpts().C99) {
14225     // Implement C99-only parts of addressof rules.
14226     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14227       if (uOp->getOpcode() == UO_Deref)
14228         // Per C99 6.5.3.2, the address of a deref always returns a valid result
14229         // (assuming the deref expression is valid).
14230         return uOp->getSubExpr()->getType();
14231     }
14232     // Technically, there should be a check for array subscript
14233     // expressions here, but the result of one is always an lvalue anyway.
14234   }
14235   ValueDecl *dcl = getPrimaryDecl(op);
14236 
14237   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14238     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14239                                            op->getBeginLoc()))
14240       return QualType();
14241 
14242   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14243   unsigned AddressOfError = AO_No_Error;
14244 
14245   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14246     bool sfinae = (bool)isSFINAEContext();
14247     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14248                                   : diag::ext_typecheck_addrof_temporary)
14249       << op->getType() << op->getSourceRange();
14250     if (sfinae)
14251       return QualType();
14252     // Materialize the temporary as an lvalue so that we can take its address.
14253     OrigOp = op =
14254         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14255   } else if (isa<ObjCSelectorExpr>(op)) {
14256     return Context.getPointerType(op->getType());
14257   } else if (lval == Expr::LV_MemberFunction) {
14258     // If it's an instance method, make a member pointer.
14259     // The expression must have exactly the form &A::foo.
14260 
14261     // If the underlying expression isn't a decl ref, give up.
14262     if (!isa<DeclRefExpr>(op)) {
14263       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14264         << OrigOp.get()->getSourceRange();
14265       return QualType();
14266     }
14267     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14268     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14269 
14270     // The id-expression was parenthesized.
14271     if (OrigOp.get() != DRE) {
14272       Diag(OpLoc, diag::err_parens_pointer_member_function)
14273         << OrigOp.get()->getSourceRange();
14274 
14275     // The method was named without a qualifier.
14276     } else if (!DRE->getQualifier()) {
14277       if (MD->getParent()->getName().empty())
14278         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14279           << op->getSourceRange();
14280       else {
14281         SmallString<32> Str;
14282         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14283         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14284           << op->getSourceRange()
14285           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14286       }
14287     }
14288 
14289     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14290     if (isa<CXXDestructorDecl>(MD))
14291       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14292 
14293     QualType MPTy = Context.getMemberPointerType(
14294         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14295     // Under the MS ABI, lock down the inheritance model now.
14296     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14297       (void)isCompleteType(OpLoc, MPTy);
14298     return MPTy;
14299   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14300     // C99 6.5.3.2p1
14301     // The operand must be either an l-value or a function designator
14302     if (!op->getType()->isFunctionType()) {
14303       // Use a special diagnostic for loads from property references.
14304       if (isa<PseudoObjectExpr>(op)) {
14305         AddressOfError = AO_Property_Expansion;
14306       } else {
14307         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14308           << op->getType() << op->getSourceRange();
14309         return QualType();
14310       }
14311     }
14312   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14313     // The operand cannot be a bit-field
14314     AddressOfError = AO_Bit_Field;
14315   } else if (op->getObjectKind() == OK_VectorComponent) {
14316     // The operand cannot be an element of a vector
14317     AddressOfError = AO_Vector_Element;
14318   } else if (op->getObjectKind() == OK_MatrixComponent) {
14319     // The operand cannot be an element of a matrix.
14320     AddressOfError = AO_Matrix_Element;
14321   } else if (dcl) { // C99 6.5.3.2p1
14322     // We have an lvalue with a decl. Make sure the decl is not declared
14323     // with the register storage-class specifier.
14324     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14325       // in C++ it is not error to take address of a register
14326       // variable (c++03 7.1.1P3)
14327       if (vd->getStorageClass() == SC_Register &&
14328           !getLangOpts().CPlusPlus) {
14329         AddressOfError = AO_Register_Variable;
14330       }
14331     } else if (isa<MSPropertyDecl>(dcl)) {
14332       AddressOfError = AO_Property_Expansion;
14333     } else if (isa<FunctionTemplateDecl>(dcl)) {
14334       return Context.OverloadTy;
14335     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14336       // Okay: we can take the address of a field.
14337       // Could be a pointer to member, though, if there is an explicit
14338       // scope qualifier for the class.
14339       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14340         DeclContext *Ctx = dcl->getDeclContext();
14341         if (Ctx && Ctx->isRecord()) {
14342           if (dcl->getType()->isReferenceType()) {
14343             Diag(OpLoc,
14344                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14345               << dcl->getDeclName() << dcl->getType();
14346             return QualType();
14347           }
14348 
14349           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14350             Ctx = Ctx->getParent();
14351 
14352           QualType MPTy = Context.getMemberPointerType(
14353               op->getType(),
14354               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14355           // Under the MS ABI, lock down the inheritance model now.
14356           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14357             (void)isCompleteType(OpLoc, MPTy);
14358           return MPTy;
14359         }
14360       }
14361     } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14362                     MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14363       llvm_unreachable("Unknown/unexpected decl type");
14364   }
14365 
14366   if (AddressOfError != AO_No_Error) {
14367     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14368     return QualType();
14369   }
14370 
14371   if (lval == Expr::LV_IncompleteVoidType) {
14372     // Taking the address of a void variable is technically illegal, but we
14373     // allow it in cases which are otherwise valid.
14374     // Example: "extern void x; void* y = &x;".
14375     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14376   }
14377 
14378   // If the operand has type "type", the result has type "pointer to type".
14379   if (op->getType()->isObjCObjectType())
14380     return Context.getObjCObjectPointerType(op->getType());
14381 
14382   CheckAddressOfPackedMember(op);
14383 
14384   return Context.getPointerType(op->getType());
14385 }
14386 
14387 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14388   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14389   if (!DRE)
14390     return;
14391   const Decl *D = DRE->getDecl();
14392   if (!D)
14393     return;
14394   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14395   if (!Param)
14396     return;
14397   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14398     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14399       return;
14400   if (FunctionScopeInfo *FD = S.getCurFunction())
14401     if (!FD->ModifiedNonNullParams.count(Param))
14402       FD->ModifiedNonNullParams.insert(Param);
14403 }
14404 
14405 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14406 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14407                                         SourceLocation OpLoc) {
14408   if (Op->isTypeDependent())
14409     return S.Context.DependentTy;
14410 
14411   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14412   if (ConvResult.isInvalid())
14413     return QualType();
14414   Op = ConvResult.get();
14415   QualType OpTy = Op->getType();
14416   QualType Result;
14417 
14418   if (isa<CXXReinterpretCastExpr>(Op)) {
14419     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14420     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14421                                      Op->getSourceRange());
14422   }
14423 
14424   if (const PointerType *PT = OpTy->getAs<PointerType>())
14425   {
14426     Result = PT->getPointeeType();
14427   }
14428   else if (const ObjCObjectPointerType *OPT =
14429              OpTy->getAs<ObjCObjectPointerType>())
14430     Result = OPT->getPointeeType();
14431   else {
14432     ExprResult PR = S.CheckPlaceholderExpr(Op);
14433     if (PR.isInvalid()) return QualType();
14434     if (PR.get() != Op)
14435       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14436   }
14437 
14438   if (Result.isNull()) {
14439     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14440       << OpTy << Op->getSourceRange();
14441     return QualType();
14442   }
14443 
14444   // Note that per both C89 and C99, indirection is always legal, even if Result
14445   // is an incomplete type or void.  It would be possible to warn about
14446   // dereferencing a void pointer, but it's completely well-defined, and such a
14447   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14448   // for pointers to 'void' but is fine for any other pointer type:
14449   //
14450   // C++ [expr.unary.op]p1:
14451   //   [...] the expression to which [the unary * operator] is applied shall
14452   //   be a pointer to an object type, or a pointer to a function type
14453   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14454     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14455       << OpTy << Op->getSourceRange();
14456 
14457   // Dereferences are usually l-values...
14458   VK = VK_LValue;
14459 
14460   // ...except that certain expressions are never l-values in C.
14461   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14462     VK = VK_PRValue;
14463 
14464   return Result;
14465 }
14466 
14467 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14468   BinaryOperatorKind Opc;
14469   switch (Kind) {
14470   default: llvm_unreachable("Unknown binop!");
14471   case tok::periodstar:           Opc = BO_PtrMemD; break;
14472   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14473   case tok::star:                 Opc = BO_Mul; break;
14474   case tok::slash:                Opc = BO_Div; break;
14475   case tok::percent:              Opc = BO_Rem; break;
14476   case tok::plus:                 Opc = BO_Add; break;
14477   case tok::minus:                Opc = BO_Sub; break;
14478   case tok::lessless:             Opc = BO_Shl; break;
14479   case tok::greatergreater:       Opc = BO_Shr; break;
14480   case tok::lessequal:            Opc = BO_LE; break;
14481   case tok::less:                 Opc = BO_LT; break;
14482   case tok::greaterequal:         Opc = BO_GE; break;
14483   case tok::greater:              Opc = BO_GT; break;
14484   case tok::exclaimequal:         Opc = BO_NE; break;
14485   case tok::equalequal:           Opc = BO_EQ; break;
14486   case tok::spaceship:            Opc = BO_Cmp; break;
14487   case tok::amp:                  Opc = BO_And; break;
14488   case tok::caret:                Opc = BO_Xor; break;
14489   case tok::pipe:                 Opc = BO_Or; break;
14490   case tok::ampamp:               Opc = BO_LAnd; break;
14491   case tok::pipepipe:             Opc = BO_LOr; break;
14492   case tok::equal:                Opc = BO_Assign; break;
14493   case tok::starequal:            Opc = BO_MulAssign; break;
14494   case tok::slashequal:           Opc = BO_DivAssign; break;
14495   case tok::percentequal:         Opc = BO_RemAssign; break;
14496   case tok::plusequal:            Opc = BO_AddAssign; break;
14497   case tok::minusequal:           Opc = BO_SubAssign; break;
14498   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14499   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14500   case tok::ampequal:             Opc = BO_AndAssign; break;
14501   case tok::caretequal:           Opc = BO_XorAssign; break;
14502   case tok::pipeequal:            Opc = BO_OrAssign; break;
14503   case tok::comma:                Opc = BO_Comma; break;
14504   }
14505   return Opc;
14506 }
14507 
14508 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14509   tok::TokenKind Kind) {
14510   UnaryOperatorKind Opc;
14511   switch (Kind) {
14512   default: llvm_unreachable("Unknown unary op!");
14513   case tok::plusplus:     Opc = UO_PreInc; break;
14514   case tok::minusminus:   Opc = UO_PreDec; break;
14515   case tok::amp:          Opc = UO_AddrOf; break;
14516   case tok::star:         Opc = UO_Deref; break;
14517   case tok::plus:         Opc = UO_Plus; break;
14518   case tok::minus:        Opc = UO_Minus; break;
14519   case tok::tilde:        Opc = UO_Not; break;
14520   case tok::exclaim:      Opc = UO_LNot; break;
14521   case tok::kw___real:    Opc = UO_Real; break;
14522   case tok::kw___imag:    Opc = UO_Imag; break;
14523   case tok::kw___extension__: Opc = UO_Extension; break;
14524   }
14525   return Opc;
14526 }
14527 
14528 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14529 /// This warning suppressed in the event of macro expansions.
14530 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14531                                    SourceLocation OpLoc, bool IsBuiltin) {
14532   if (S.inTemplateInstantiation())
14533     return;
14534   if (S.isUnevaluatedContext())
14535     return;
14536   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14537     return;
14538   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14539   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14540   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14541   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14542   if (!LHSDeclRef || !RHSDeclRef ||
14543       LHSDeclRef->getLocation().isMacroID() ||
14544       RHSDeclRef->getLocation().isMacroID())
14545     return;
14546   const ValueDecl *LHSDecl =
14547     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14548   const ValueDecl *RHSDecl =
14549     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14550   if (LHSDecl != RHSDecl)
14551     return;
14552   if (LHSDecl->getType().isVolatileQualified())
14553     return;
14554   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14555     if (RefTy->getPointeeType().isVolatileQualified())
14556       return;
14557 
14558   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14559                           : diag::warn_self_assignment_overloaded)
14560       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14561       << RHSExpr->getSourceRange();
14562 }
14563 
14564 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14565 /// is usually indicative of introspection within the Objective-C pointer.
14566 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14567                                           SourceLocation OpLoc) {
14568   if (!S.getLangOpts().ObjC)
14569     return;
14570 
14571   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14572   const Expr *LHS = L.get();
14573   const Expr *RHS = R.get();
14574 
14575   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14576     ObjCPointerExpr = LHS;
14577     OtherExpr = RHS;
14578   }
14579   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14580     ObjCPointerExpr = RHS;
14581     OtherExpr = LHS;
14582   }
14583 
14584   // This warning is deliberately made very specific to reduce false
14585   // positives with logic that uses '&' for hashing.  This logic mainly
14586   // looks for code trying to introspect into tagged pointers, which
14587   // code should generally never do.
14588   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14589     unsigned Diag = diag::warn_objc_pointer_masking;
14590     // Determine if we are introspecting the result of performSelectorXXX.
14591     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14592     // Special case messages to -performSelector and friends, which
14593     // can return non-pointer values boxed in a pointer value.
14594     // Some clients may wish to silence warnings in this subcase.
14595     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14596       Selector S = ME->getSelector();
14597       StringRef SelArg0 = S.getNameForSlot(0);
14598       if (SelArg0.startswith("performSelector"))
14599         Diag = diag::warn_objc_pointer_masking_performSelector;
14600     }
14601 
14602     S.Diag(OpLoc, Diag)
14603       << ObjCPointerExpr->getSourceRange();
14604   }
14605 }
14606 
14607 static NamedDecl *getDeclFromExpr(Expr *E) {
14608   if (!E)
14609     return nullptr;
14610   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14611     return DRE->getDecl();
14612   if (auto *ME = dyn_cast<MemberExpr>(E))
14613     return ME->getMemberDecl();
14614   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14615     return IRE->getDecl();
14616   return nullptr;
14617 }
14618 
14619 // This helper function promotes a binary operator's operands (which are of a
14620 // half vector type) to a vector of floats and then truncates the result to
14621 // a vector of either half or short.
14622 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14623                                       BinaryOperatorKind Opc, QualType ResultTy,
14624                                       ExprValueKind VK, ExprObjectKind OK,
14625                                       bool IsCompAssign, SourceLocation OpLoc,
14626                                       FPOptionsOverride FPFeatures) {
14627   auto &Context = S.getASTContext();
14628   assert((isVector(ResultTy, Context.HalfTy) ||
14629           isVector(ResultTy, Context.ShortTy)) &&
14630          "Result must be a vector of half or short");
14631   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14632          isVector(RHS.get()->getType(), Context.HalfTy) &&
14633          "both operands expected to be a half vector");
14634 
14635   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14636   QualType BinOpResTy = RHS.get()->getType();
14637 
14638   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14639   // change BinOpResTy to a vector of ints.
14640   if (isVector(ResultTy, Context.ShortTy))
14641     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14642 
14643   if (IsCompAssign)
14644     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14645                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14646                                           BinOpResTy, BinOpResTy);
14647 
14648   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14649   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14650                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14651   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14652 }
14653 
14654 static std::pair<ExprResult, ExprResult>
14655 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14656                            Expr *RHSExpr) {
14657   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14658   if (!S.Context.isDependenceAllowed()) {
14659     // C cannot handle TypoExpr nodes on either side of a binop because it
14660     // doesn't handle dependent types properly, so make sure any TypoExprs have
14661     // been dealt with before checking the operands.
14662     LHS = S.CorrectDelayedTyposInExpr(LHS);
14663     RHS = S.CorrectDelayedTyposInExpr(
14664         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14665         [Opc, LHS](Expr *E) {
14666           if (Opc != BO_Assign)
14667             return ExprResult(E);
14668           // Avoid correcting the RHS to the same Expr as the LHS.
14669           Decl *D = getDeclFromExpr(E);
14670           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14671         });
14672   }
14673   return std::make_pair(LHS, RHS);
14674 }
14675 
14676 /// Returns true if conversion between vectors of halfs and vectors of floats
14677 /// is needed.
14678 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14679                                      Expr *E0, Expr *E1 = nullptr) {
14680   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14681       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14682     return false;
14683 
14684   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14685     QualType Ty = E->IgnoreImplicit()->getType();
14686 
14687     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14688     // to vectors of floats. Although the element type of the vectors is __fp16,
14689     // the vectors shouldn't be treated as storage-only types. See the
14690     // discussion here: https://reviews.llvm.org/rG825235c140e7
14691     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14692       if (VT->getVectorKind() == VectorType::NeonVector)
14693         return false;
14694       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14695     }
14696     return false;
14697   };
14698 
14699   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14700 }
14701 
14702 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14703 /// operator @p Opc at location @c TokLoc. This routine only supports
14704 /// built-in operations; ActOnBinOp handles overloaded operators.
14705 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14706                                     BinaryOperatorKind Opc,
14707                                     Expr *LHSExpr, Expr *RHSExpr) {
14708   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14709     // The syntax only allows initializer lists on the RHS of assignment,
14710     // so we don't need to worry about accepting invalid code for
14711     // non-assignment operators.
14712     // C++11 5.17p9:
14713     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14714     //   of x = {} is x = T().
14715     InitializationKind Kind = InitializationKind::CreateDirectList(
14716         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14717     InitializedEntity Entity =
14718         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14719     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14720     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14721     if (Init.isInvalid())
14722       return Init;
14723     RHSExpr = Init.get();
14724   }
14725 
14726   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14727   QualType ResultTy;     // Result type of the binary operator.
14728   // The following two variables are used for compound assignment operators
14729   QualType CompLHSTy;    // Type of LHS after promotions for computation
14730   QualType CompResultTy; // Type of computation result
14731   ExprValueKind VK = VK_PRValue;
14732   ExprObjectKind OK = OK_Ordinary;
14733   bool ConvertHalfVec = false;
14734 
14735   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14736   if (!LHS.isUsable() || !RHS.isUsable())
14737     return ExprError();
14738 
14739   if (getLangOpts().OpenCL) {
14740     QualType LHSTy = LHSExpr->getType();
14741     QualType RHSTy = RHSExpr->getType();
14742     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14743     // the ATOMIC_VAR_INIT macro.
14744     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14745       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14746       if (BO_Assign == Opc)
14747         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14748       else
14749         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14750       return ExprError();
14751     }
14752 
14753     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14754     // only with a builtin functions and therefore should be disallowed here.
14755     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14756         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14757         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14758         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14759       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14760       return ExprError();
14761     }
14762   }
14763 
14764   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14765   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14766 
14767   switch (Opc) {
14768   case BO_Assign:
14769     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14770     if (getLangOpts().CPlusPlus &&
14771         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14772       VK = LHS.get()->getValueKind();
14773       OK = LHS.get()->getObjectKind();
14774     }
14775     if (!ResultTy.isNull()) {
14776       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14777       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14778 
14779       // Avoid copying a block to the heap if the block is assigned to a local
14780       // auto variable that is declared in the same scope as the block. This
14781       // optimization is unsafe if the local variable is declared in an outer
14782       // scope. For example:
14783       //
14784       // BlockTy b;
14785       // {
14786       //   b = ^{...};
14787       // }
14788       // // It is unsafe to invoke the block here if it wasn't copied to the
14789       // // heap.
14790       // b();
14791 
14792       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14793         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14794           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14795             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14796               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14797 
14798       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14799         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14800                               NTCUC_Assignment, NTCUK_Copy);
14801     }
14802     RecordModifiableNonNullParam(*this, LHS.get());
14803     break;
14804   case BO_PtrMemD:
14805   case BO_PtrMemI:
14806     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14807                                             Opc == BO_PtrMemI);
14808     break;
14809   case BO_Mul:
14810   case BO_Div:
14811     ConvertHalfVec = true;
14812     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14813                                            Opc == BO_Div);
14814     break;
14815   case BO_Rem:
14816     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14817     break;
14818   case BO_Add:
14819     ConvertHalfVec = true;
14820     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14821     break;
14822   case BO_Sub:
14823     ConvertHalfVec = true;
14824     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14825     break;
14826   case BO_Shl:
14827   case BO_Shr:
14828     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14829     break;
14830   case BO_LE:
14831   case BO_LT:
14832   case BO_GE:
14833   case BO_GT:
14834     ConvertHalfVec = true;
14835     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14836     break;
14837   case BO_EQ:
14838   case BO_NE:
14839     ConvertHalfVec = true;
14840     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14841     break;
14842   case BO_Cmp:
14843     ConvertHalfVec = true;
14844     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14845     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14846     break;
14847   case BO_And:
14848     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14849     LLVM_FALLTHROUGH;
14850   case BO_Xor:
14851   case BO_Or:
14852     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14853     break;
14854   case BO_LAnd:
14855   case BO_LOr:
14856     ConvertHalfVec = true;
14857     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14858     break;
14859   case BO_MulAssign:
14860   case BO_DivAssign:
14861     ConvertHalfVec = true;
14862     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14863                                                Opc == BO_DivAssign);
14864     CompLHSTy = CompResultTy;
14865     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14866       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14867     break;
14868   case BO_RemAssign:
14869     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14870     CompLHSTy = CompResultTy;
14871     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14872       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14873     break;
14874   case BO_AddAssign:
14875     ConvertHalfVec = true;
14876     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14877     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14878       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14879     break;
14880   case BO_SubAssign:
14881     ConvertHalfVec = true;
14882     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14883     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14884       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14885     break;
14886   case BO_ShlAssign:
14887   case BO_ShrAssign:
14888     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14889     CompLHSTy = CompResultTy;
14890     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14891       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14892     break;
14893   case BO_AndAssign:
14894   case BO_OrAssign: // fallthrough
14895     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14896     LLVM_FALLTHROUGH;
14897   case BO_XorAssign:
14898     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14899     CompLHSTy = CompResultTy;
14900     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14901       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14902     break;
14903   case BO_Comma:
14904     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14905     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14906       VK = RHS.get()->getValueKind();
14907       OK = RHS.get()->getObjectKind();
14908     }
14909     break;
14910   }
14911   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14912     return ExprError();
14913 
14914   // Some of the binary operations require promoting operands of half vector to
14915   // float vectors and truncating the result back to half vector. For now, we do
14916   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14917   // arm64).
14918   assert(
14919       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14920                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14921       "both sides are half vectors or neither sides are");
14922   ConvertHalfVec =
14923       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14924 
14925   // Check for array bounds violations for both sides of the BinaryOperator
14926   CheckArrayAccess(LHS.get());
14927   CheckArrayAccess(RHS.get());
14928 
14929   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14930     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14931                                                  &Context.Idents.get("object_setClass"),
14932                                                  SourceLocation(), LookupOrdinaryName);
14933     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14934       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14935       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14936           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14937                                         "object_setClass(")
14938           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14939                                           ",")
14940           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14941     }
14942     else
14943       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14944   }
14945   else if (const ObjCIvarRefExpr *OIRE =
14946            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14947     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14948 
14949   // Opc is not a compound assignment if CompResultTy is null.
14950   if (CompResultTy.isNull()) {
14951     if (ConvertHalfVec)
14952       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14953                                  OpLoc, CurFPFeatureOverrides());
14954     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14955                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14956   }
14957 
14958   // Handle compound assignments.
14959   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14960       OK_ObjCProperty) {
14961     VK = VK_LValue;
14962     OK = LHS.get()->getObjectKind();
14963   }
14964 
14965   // The LHS is not converted to the result type for fixed-point compound
14966   // assignment as the common type is computed on demand. Reset the CompLHSTy
14967   // to the LHS type we would have gotten after unary conversions.
14968   if (CompResultTy->isFixedPointType())
14969     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14970 
14971   if (ConvertHalfVec)
14972     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14973                                OpLoc, CurFPFeatureOverrides());
14974 
14975   return CompoundAssignOperator::Create(
14976       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14977       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14978 }
14979 
14980 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14981 /// operators are mixed in a way that suggests that the programmer forgot that
14982 /// comparison operators have higher precedence. The most typical example of
14983 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14984 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14985                                       SourceLocation OpLoc, Expr *LHSExpr,
14986                                       Expr *RHSExpr) {
14987   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14988   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14989 
14990   // Check that one of the sides is a comparison operator and the other isn't.
14991   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14992   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14993   if (isLeftComp == isRightComp)
14994     return;
14995 
14996   // Bitwise operations are sometimes used as eager logical ops.
14997   // Don't diagnose this.
14998   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14999   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15000   if (isLeftBitwise || isRightBitwise)
15001     return;
15002 
15003   SourceRange DiagRange = isLeftComp
15004                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15005                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
15006   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15007   SourceRange ParensRange =
15008       isLeftComp
15009           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15010           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15011 
15012   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15013     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15014   SuggestParentheses(Self, OpLoc,
15015     Self.PDiag(diag::note_precedence_silence) << OpStr,
15016     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15017   SuggestParentheses(Self, OpLoc,
15018     Self.PDiag(diag::note_precedence_bitwise_first)
15019       << BinaryOperator::getOpcodeStr(Opc),
15020     ParensRange);
15021 }
15022 
15023 /// It accepts a '&&' expr that is inside a '||' one.
15024 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15025 /// in parentheses.
15026 static void
15027 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15028                                        BinaryOperator *Bop) {
15029   assert(Bop->getOpcode() == BO_LAnd);
15030   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15031       << Bop->getSourceRange() << OpLoc;
15032   SuggestParentheses(Self, Bop->getOperatorLoc(),
15033     Self.PDiag(diag::note_precedence_silence)
15034       << Bop->getOpcodeStr(),
15035     Bop->getSourceRange());
15036 }
15037 
15038 /// Returns true if the given expression can be evaluated as a constant
15039 /// 'true'.
15040 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15041   bool Res;
15042   return !E->isValueDependent() &&
15043          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15044 }
15045 
15046 /// Returns true if the given expression can be evaluated as a constant
15047 /// 'false'.
15048 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15049   bool Res;
15050   return !E->isValueDependent() &&
15051          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15052 }
15053 
15054 /// Look for '&&' in the left hand of a '||' expr.
15055 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15056                                              Expr *LHSExpr, Expr *RHSExpr) {
15057   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15058     if (Bop->getOpcode() == BO_LAnd) {
15059       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15060       if (EvaluatesAsFalse(S, RHSExpr))
15061         return;
15062       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15063       if (!EvaluatesAsTrue(S, Bop->getLHS()))
15064         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15065     } else if (Bop->getOpcode() == BO_LOr) {
15066       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15067         // If it's "a || b && 1 || c" we didn't warn earlier for
15068         // "a || b && 1", but warn now.
15069         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15070           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15071       }
15072     }
15073   }
15074 }
15075 
15076 /// Look for '&&' in the right hand of a '||' expr.
15077 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15078                                              Expr *LHSExpr, Expr *RHSExpr) {
15079   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15080     if (Bop->getOpcode() == BO_LAnd) {
15081       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15082       if (EvaluatesAsFalse(S, LHSExpr))
15083         return;
15084       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15085       if (!EvaluatesAsTrue(S, Bop->getRHS()))
15086         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15087     }
15088   }
15089 }
15090 
15091 /// Look for bitwise op in the left or right hand of a bitwise op with
15092 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15093 /// the '&' expression in parentheses.
15094 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15095                                          SourceLocation OpLoc, Expr *SubExpr) {
15096   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15097     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15098       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15099         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15100         << Bop->getSourceRange() << OpLoc;
15101       SuggestParentheses(S, Bop->getOperatorLoc(),
15102         S.PDiag(diag::note_precedence_silence)
15103           << Bop->getOpcodeStr(),
15104         Bop->getSourceRange());
15105     }
15106   }
15107 }
15108 
15109 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15110                                     Expr *SubExpr, StringRef Shift) {
15111   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15112     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15113       StringRef Op = Bop->getOpcodeStr();
15114       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15115           << Bop->getSourceRange() << OpLoc << Shift << Op;
15116       SuggestParentheses(S, Bop->getOperatorLoc(),
15117           S.PDiag(diag::note_precedence_silence) << Op,
15118           Bop->getSourceRange());
15119     }
15120   }
15121 }
15122 
15123 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15124                                  Expr *LHSExpr, Expr *RHSExpr) {
15125   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15126   if (!OCE)
15127     return;
15128 
15129   FunctionDecl *FD = OCE->getDirectCallee();
15130   if (!FD || !FD->isOverloadedOperator())
15131     return;
15132 
15133   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15134   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15135     return;
15136 
15137   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15138       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15139       << (Kind == OO_LessLess);
15140   SuggestParentheses(S, OCE->getOperatorLoc(),
15141                      S.PDiag(diag::note_precedence_silence)
15142                          << (Kind == OO_LessLess ? "<<" : ">>"),
15143                      OCE->getSourceRange());
15144   SuggestParentheses(
15145       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15146       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15147 }
15148 
15149 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15150 /// precedence.
15151 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15152                                     SourceLocation OpLoc, Expr *LHSExpr,
15153                                     Expr *RHSExpr){
15154   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15155   if (BinaryOperator::isBitwiseOp(Opc))
15156     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15157 
15158   // Diagnose "arg1 & arg2 | arg3"
15159   if ((Opc == BO_Or || Opc == BO_Xor) &&
15160       !OpLoc.isMacroID()/* Don't warn in macros. */) {
15161     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15162     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15163   }
15164 
15165   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15166   // We don't warn for 'assert(a || b && "bad")' since this is safe.
15167   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15168     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15169     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15170   }
15171 
15172   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15173       || Opc == BO_Shr) {
15174     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15175     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15176     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15177   }
15178 
15179   // Warn on overloaded shift operators and comparisons, such as:
15180   // cout << 5 == 4;
15181   if (BinaryOperator::isComparisonOp(Opc))
15182     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15183 }
15184 
15185 // Binary Operators.  'Tok' is the token for the operator.
15186 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15187                             tok::TokenKind Kind,
15188                             Expr *LHSExpr, Expr *RHSExpr) {
15189   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15190   assert(LHSExpr && "ActOnBinOp(): missing left expression");
15191   assert(RHSExpr && "ActOnBinOp(): missing right expression");
15192 
15193   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15194   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15195 
15196   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15197 }
15198 
15199 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15200                        UnresolvedSetImpl &Functions) {
15201   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15202   if (OverOp != OO_None && OverOp != OO_Equal)
15203     LookupOverloadedOperatorName(OverOp, S, Functions);
15204 
15205   // In C++20 onwards, we may have a second operator to look up.
15206   if (getLangOpts().CPlusPlus20) {
15207     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15208       LookupOverloadedOperatorName(ExtraOp, S, Functions);
15209   }
15210 }
15211 
15212 /// Build an overloaded binary operator expression in the given scope.
15213 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15214                                        BinaryOperatorKind Opc,
15215                                        Expr *LHS, Expr *RHS) {
15216   switch (Opc) {
15217   case BO_Assign:
15218   case BO_DivAssign:
15219   case BO_RemAssign:
15220   case BO_SubAssign:
15221   case BO_AndAssign:
15222   case BO_OrAssign:
15223   case BO_XorAssign:
15224     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15225     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15226     break;
15227   default:
15228     break;
15229   }
15230 
15231   // Find all of the overloaded operators visible from this point.
15232   UnresolvedSet<16> Functions;
15233   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15234 
15235   // Build the (potentially-overloaded, potentially-dependent)
15236   // binary operation.
15237   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15238 }
15239 
15240 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15241                             BinaryOperatorKind Opc,
15242                             Expr *LHSExpr, Expr *RHSExpr) {
15243   ExprResult LHS, RHS;
15244   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15245   if (!LHS.isUsable() || !RHS.isUsable())
15246     return ExprError();
15247   LHSExpr = LHS.get();
15248   RHSExpr = RHS.get();
15249 
15250   // We want to end up calling one of checkPseudoObjectAssignment
15251   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15252   // both expressions are overloadable or either is type-dependent),
15253   // or CreateBuiltinBinOp (in any other case).  We also want to get
15254   // any placeholder types out of the way.
15255 
15256   // Handle pseudo-objects in the LHS.
15257   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15258     // Assignments with a pseudo-object l-value need special analysis.
15259     if (pty->getKind() == BuiltinType::PseudoObject &&
15260         BinaryOperator::isAssignmentOp(Opc))
15261       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15262 
15263     // Don't resolve overloads if the other type is overloadable.
15264     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15265       // We can't actually test that if we still have a placeholder,
15266       // though.  Fortunately, none of the exceptions we see in that
15267       // code below are valid when the LHS is an overload set.  Note
15268       // that an overload set can be dependently-typed, but it never
15269       // instantiates to having an overloadable type.
15270       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15271       if (resolvedRHS.isInvalid()) return ExprError();
15272       RHSExpr = resolvedRHS.get();
15273 
15274       if (RHSExpr->isTypeDependent() ||
15275           RHSExpr->getType()->isOverloadableType())
15276         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15277     }
15278 
15279     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15280     // template, diagnose the missing 'template' keyword instead of diagnosing
15281     // an invalid use of a bound member function.
15282     //
15283     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15284     // to C++1z [over.over]/1.4, but we already checked for that case above.
15285     if (Opc == BO_LT && inTemplateInstantiation() &&
15286         (pty->getKind() == BuiltinType::BoundMember ||
15287          pty->getKind() == BuiltinType::Overload)) {
15288       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15289       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15290           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15291             return isa<FunctionTemplateDecl>(ND);
15292           })) {
15293         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15294                                 : OE->getNameLoc(),
15295              diag::err_template_kw_missing)
15296           << OE->getName().getAsString() << "";
15297         return ExprError();
15298       }
15299     }
15300 
15301     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15302     if (LHS.isInvalid()) return ExprError();
15303     LHSExpr = LHS.get();
15304   }
15305 
15306   // Handle pseudo-objects in the RHS.
15307   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15308     // An overload in the RHS can potentially be resolved by the type
15309     // being assigned to.
15310     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15311       if (getLangOpts().CPlusPlus &&
15312           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15313            LHSExpr->getType()->isOverloadableType()))
15314         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15315 
15316       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15317     }
15318 
15319     // Don't resolve overloads if the other type is overloadable.
15320     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15321         LHSExpr->getType()->isOverloadableType())
15322       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15323 
15324     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15325     if (!resolvedRHS.isUsable()) return ExprError();
15326     RHSExpr = resolvedRHS.get();
15327   }
15328 
15329   if (getLangOpts().CPlusPlus) {
15330     // If either expression is type-dependent, always build an
15331     // overloaded op.
15332     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15333       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15334 
15335     // Otherwise, build an overloaded op if either expression has an
15336     // overloadable type.
15337     if (LHSExpr->getType()->isOverloadableType() ||
15338         RHSExpr->getType()->isOverloadableType())
15339       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15340   }
15341 
15342   if (getLangOpts().RecoveryAST &&
15343       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15344     assert(!getLangOpts().CPlusPlus);
15345     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15346            "Should only occur in error-recovery path.");
15347     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15348       // C [6.15.16] p3:
15349       // An assignment expression has the value of the left operand after the
15350       // assignment, but is not an lvalue.
15351       return CompoundAssignOperator::Create(
15352           Context, LHSExpr, RHSExpr, Opc,
15353           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15354           OpLoc, CurFPFeatureOverrides());
15355     QualType ResultType;
15356     switch (Opc) {
15357     case BO_Assign:
15358       ResultType = LHSExpr->getType().getUnqualifiedType();
15359       break;
15360     case BO_LT:
15361     case BO_GT:
15362     case BO_LE:
15363     case BO_GE:
15364     case BO_EQ:
15365     case BO_NE:
15366     case BO_LAnd:
15367     case BO_LOr:
15368       // These operators have a fixed result type regardless of operands.
15369       ResultType = Context.IntTy;
15370       break;
15371     case BO_Comma:
15372       ResultType = RHSExpr->getType();
15373       break;
15374     default:
15375       ResultType = Context.DependentTy;
15376       break;
15377     }
15378     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15379                                   VK_PRValue, OK_Ordinary, OpLoc,
15380                                   CurFPFeatureOverrides());
15381   }
15382 
15383   // Build a built-in binary operation.
15384   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15385 }
15386 
15387 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15388   if (T.isNull() || T->isDependentType())
15389     return false;
15390 
15391   if (!T->isPromotableIntegerType())
15392     return true;
15393 
15394   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15395 }
15396 
15397 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15398                                       UnaryOperatorKind Opc,
15399                                       Expr *InputExpr) {
15400   ExprResult Input = InputExpr;
15401   ExprValueKind VK = VK_PRValue;
15402   ExprObjectKind OK = OK_Ordinary;
15403   QualType resultType;
15404   bool CanOverflow = false;
15405 
15406   bool ConvertHalfVec = false;
15407   if (getLangOpts().OpenCL) {
15408     QualType Ty = InputExpr->getType();
15409     // The only legal unary operation for atomics is '&'.
15410     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15411     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15412     // only with a builtin functions and therefore should be disallowed here.
15413         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15414         || Ty->isBlockPointerType())) {
15415       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15416                        << InputExpr->getType()
15417                        << Input.get()->getSourceRange());
15418     }
15419   }
15420 
15421   if (getLangOpts().HLSL) {
15422     if (Opc == UO_AddrOf)
15423       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15424     if (Opc == UO_Deref)
15425       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15426   }
15427 
15428   switch (Opc) {
15429   case UO_PreInc:
15430   case UO_PreDec:
15431   case UO_PostInc:
15432   case UO_PostDec:
15433     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15434                                                 OpLoc,
15435                                                 Opc == UO_PreInc ||
15436                                                 Opc == UO_PostInc,
15437                                                 Opc == UO_PreInc ||
15438                                                 Opc == UO_PreDec);
15439     CanOverflow = isOverflowingIntegerType(Context, resultType);
15440     break;
15441   case UO_AddrOf:
15442     resultType = CheckAddressOfOperand(Input, OpLoc);
15443     CheckAddressOfNoDeref(InputExpr);
15444     RecordModifiableNonNullParam(*this, InputExpr);
15445     break;
15446   case UO_Deref: {
15447     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15448     if (Input.isInvalid()) return ExprError();
15449     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15450     break;
15451   }
15452   case UO_Plus:
15453   case UO_Minus:
15454     CanOverflow = Opc == UO_Minus &&
15455                   isOverflowingIntegerType(Context, Input.get()->getType());
15456     Input = UsualUnaryConversions(Input.get());
15457     if (Input.isInvalid()) return ExprError();
15458     // Unary plus and minus require promoting an operand of half vector to a
15459     // float vector and truncating the result back to a half vector. For now, we
15460     // do this only when HalfArgsAndReturns is set (that is, when the target is
15461     // arm or arm64).
15462     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15463 
15464     // If the operand is a half vector, promote it to a float vector.
15465     if (ConvertHalfVec)
15466       Input = convertVector(Input.get(), Context.FloatTy, *this);
15467     resultType = Input.get()->getType();
15468     if (resultType->isDependentType())
15469       break;
15470     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15471       break;
15472     else if (resultType->isVectorType() &&
15473              // The z vector extensions don't allow + or - with bool vectors.
15474              (!Context.getLangOpts().ZVector ||
15475               resultType->castAs<VectorType>()->getVectorKind() !=
15476               VectorType::AltiVecBool))
15477       break;
15478     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15479              Opc == UO_Plus &&
15480              resultType->isPointerType())
15481       break;
15482 
15483     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15484       << resultType << Input.get()->getSourceRange());
15485 
15486   case UO_Not: // bitwise complement
15487     Input = UsualUnaryConversions(Input.get());
15488     if (Input.isInvalid())
15489       return ExprError();
15490     resultType = Input.get()->getType();
15491     if (resultType->isDependentType())
15492       break;
15493     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15494     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15495       // C99 does not support '~' for complex conjugation.
15496       Diag(OpLoc, diag::ext_integer_complement_complex)
15497           << resultType << Input.get()->getSourceRange();
15498     else if (resultType->hasIntegerRepresentation())
15499       break;
15500     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15501       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15502       // on vector float types.
15503       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15504       if (!T->isIntegerType())
15505         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15506                           << resultType << Input.get()->getSourceRange());
15507     } else {
15508       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15509                        << resultType << Input.get()->getSourceRange());
15510     }
15511     break;
15512 
15513   case UO_LNot: // logical negation
15514     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15515     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15516     if (Input.isInvalid()) return ExprError();
15517     resultType = Input.get()->getType();
15518 
15519     // Though we still have to promote half FP to float...
15520     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15521       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15522       resultType = Context.FloatTy;
15523     }
15524 
15525     if (resultType->isDependentType())
15526       break;
15527     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15528       // C99 6.5.3.3p1: ok, fallthrough;
15529       if (Context.getLangOpts().CPlusPlus) {
15530         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15531         // operand contextually converted to bool.
15532         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15533                                   ScalarTypeToBooleanCastKind(resultType));
15534       } else if (Context.getLangOpts().OpenCL &&
15535                  Context.getLangOpts().OpenCLVersion < 120) {
15536         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15537         // operate on scalar float types.
15538         if (!resultType->isIntegerType() && !resultType->isPointerType())
15539           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15540                            << resultType << Input.get()->getSourceRange());
15541       }
15542     } else if (resultType->isExtVectorType()) {
15543       if (Context.getLangOpts().OpenCL &&
15544           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15545         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15546         // operate on vector float types.
15547         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15548         if (!T->isIntegerType())
15549           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15550                            << resultType << Input.get()->getSourceRange());
15551       }
15552       // Vector logical not returns the signed variant of the operand type.
15553       resultType = GetSignedVectorType(resultType);
15554       break;
15555     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15556       const VectorType *VTy = resultType->castAs<VectorType>();
15557       if (VTy->getVectorKind() != VectorType::GenericVector)
15558         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15559                          << resultType << Input.get()->getSourceRange());
15560 
15561       // Vector logical not returns the signed variant of the operand type.
15562       resultType = GetSignedVectorType(resultType);
15563       break;
15564     } else {
15565       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15566         << resultType << Input.get()->getSourceRange());
15567     }
15568 
15569     // LNot always has type int. C99 6.5.3.3p5.
15570     // In C++, it's bool. C++ 5.3.1p8
15571     resultType = Context.getLogicalOperationType();
15572     break;
15573   case UO_Real:
15574   case UO_Imag:
15575     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15576     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15577     // complex l-values to ordinary l-values and all other values to r-values.
15578     if (Input.isInvalid()) return ExprError();
15579     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15580       if (Input.get()->isGLValue() &&
15581           Input.get()->getObjectKind() == OK_Ordinary)
15582         VK = Input.get()->getValueKind();
15583     } else if (!getLangOpts().CPlusPlus) {
15584       // In C, a volatile scalar is read by __imag. In C++, it is not.
15585       Input = DefaultLvalueConversion(Input.get());
15586     }
15587     break;
15588   case UO_Extension:
15589     resultType = Input.get()->getType();
15590     VK = Input.get()->getValueKind();
15591     OK = Input.get()->getObjectKind();
15592     break;
15593   case UO_Coawait:
15594     // It's unnecessary to represent the pass-through operator co_await in the
15595     // AST; just return the input expression instead.
15596     assert(!Input.get()->getType()->isDependentType() &&
15597                    "the co_await expression must be non-dependant before "
15598                    "building operator co_await");
15599     return Input;
15600   }
15601   if (resultType.isNull() || Input.isInvalid())
15602     return ExprError();
15603 
15604   // Check for array bounds violations in the operand of the UnaryOperator,
15605   // except for the '*' and '&' operators that have to be handled specially
15606   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15607   // that are explicitly defined as valid by the standard).
15608   if (Opc != UO_AddrOf && Opc != UO_Deref)
15609     CheckArrayAccess(Input.get());
15610 
15611   auto *UO =
15612       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15613                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15614 
15615   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15616       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15617       !isUnevaluatedContext())
15618     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15619 
15620   // Convert the result back to a half vector.
15621   if (ConvertHalfVec)
15622     return convertVector(UO, Context.HalfTy, *this);
15623   return UO;
15624 }
15625 
15626 /// Determine whether the given expression is a qualified member
15627 /// access expression, of a form that could be turned into a pointer to member
15628 /// with the address-of operator.
15629 bool Sema::isQualifiedMemberAccess(Expr *E) {
15630   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15631     if (!DRE->getQualifier())
15632       return false;
15633 
15634     ValueDecl *VD = DRE->getDecl();
15635     if (!VD->isCXXClassMember())
15636       return false;
15637 
15638     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15639       return true;
15640     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15641       return Method->isInstance();
15642 
15643     return false;
15644   }
15645 
15646   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15647     if (!ULE->getQualifier())
15648       return false;
15649 
15650     for (NamedDecl *D : ULE->decls()) {
15651       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15652         if (Method->isInstance())
15653           return true;
15654       } else {
15655         // Overload set does not contain methods.
15656         break;
15657       }
15658     }
15659 
15660     return false;
15661   }
15662 
15663   return false;
15664 }
15665 
15666 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15667                               UnaryOperatorKind Opc, Expr *Input) {
15668   // First things first: handle placeholders so that the
15669   // overloaded-operator check considers the right type.
15670   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15671     // Increment and decrement of pseudo-object references.
15672     if (pty->getKind() == BuiltinType::PseudoObject &&
15673         UnaryOperator::isIncrementDecrementOp(Opc))
15674       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15675 
15676     // extension is always a builtin operator.
15677     if (Opc == UO_Extension)
15678       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15679 
15680     // & gets special logic for several kinds of placeholder.
15681     // The builtin code knows what to do.
15682     if (Opc == UO_AddrOf &&
15683         (pty->getKind() == BuiltinType::Overload ||
15684          pty->getKind() == BuiltinType::UnknownAny ||
15685          pty->getKind() == BuiltinType::BoundMember))
15686       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15687 
15688     // Anything else needs to be handled now.
15689     ExprResult Result = CheckPlaceholderExpr(Input);
15690     if (Result.isInvalid()) return ExprError();
15691     Input = Result.get();
15692   }
15693 
15694   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15695       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15696       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15697     // Find all of the overloaded operators visible from this point.
15698     UnresolvedSet<16> Functions;
15699     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15700     if (S && OverOp != OO_None)
15701       LookupOverloadedOperatorName(OverOp, S, Functions);
15702 
15703     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15704   }
15705 
15706   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15707 }
15708 
15709 // Unary Operators.  'Tok' is the token for the operator.
15710 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15711                               tok::TokenKind Op, Expr *Input) {
15712   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15713 }
15714 
15715 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15716 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15717                                 LabelDecl *TheDecl) {
15718   TheDecl->markUsed(Context);
15719   // Create the AST node.  The address of a label always has type 'void*'.
15720   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15721                                      Context.getPointerType(Context.VoidTy));
15722 }
15723 
15724 void Sema::ActOnStartStmtExpr() {
15725   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15726 }
15727 
15728 void Sema::ActOnStmtExprError() {
15729   // Note that function is also called by TreeTransform when leaving a
15730   // StmtExpr scope without rebuilding anything.
15731 
15732   DiscardCleanupsInEvaluationContext();
15733   PopExpressionEvaluationContext();
15734 }
15735 
15736 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15737                                SourceLocation RPLoc) {
15738   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15739 }
15740 
15741 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15742                                SourceLocation RPLoc, unsigned TemplateDepth) {
15743   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15744   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15745 
15746   if (hasAnyUnrecoverableErrorsInThisFunction())
15747     DiscardCleanupsInEvaluationContext();
15748   assert(!Cleanup.exprNeedsCleanups() &&
15749          "cleanups within StmtExpr not correctly bound!");
15750   PopExpressionEvaluationContext();
15751 
15752   // FIXME: there are a variety of strange constraints to enforce here, for
15753   // example, it is not possible to goto into a stmt expression apparently.
15754   // More semantic analysis is needed.
15755 
15756   // If there are sub-stmts in the compound stmt, take the type of the last one
15757   // as the type of the stmtexpr.
15758   QualType Ty = Context.VoidTy;
15759   bool StmtExprMayBindToTemp = false;
15760   if (!Compound->body_empty()) {
15761     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15762     if (const auto *LastStmt =
15763             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15764       if (const Expr *Value = LastStmt->getExprStmt()) {
15765         StmtExprMayBindToTemp = true;
15766         Ty = Value->getType();
15767       }
15768     }
15769   }
15770 
15771   // FIXME: Check that expression type is complete/non-abstract; statement
15772   // expressions are not lvalues.
15773   Expr *ResStmtExpr =
15774       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15775   if (StmtExprMayBindToTemp)
15776     return MaybeBindToTemporary(ResStmtExpr);
15777   return ResStmtExpr;
15778 }
15779 
15780 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15781   if (ER.isInvalid())
15782     return ExprError();
15783 
15784   // Do function/array conversion on the last expression, but not
15785   // lvalue-to-rvalue.  However, initialize an unqualified type.
15786   ER = DefaultFunctionArrayConversion(ER.get());
15787   if (ER.isInvalid())
15788     return ExprError();
15789   Expr *E = ER.get();
15790 
15791   if (E->isTypeDependent())
15792     return E;
15793 
15794   // In ARC, if the final expression ends in a consume, splice
15795   // the consume out and bind it later.  In the alternate case
15796   // (when dealing with a retainable type), the result
15797   // initialization will create a produce.  In both cases the
15798   // result will be +1, and we'll need to balance that out with
15799   // a bind.
15800   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15801   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15802     return Cast->getSubExpr();
15803 
15804   // FIXME: Provide a better location for the initialization.
15805   return PerformCopyInitialization(
15806       InitializedEntity::InitializeStmtExprResult(
15807           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15808       SourceLocation(), E);
15809 }
15810 
15811 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15812                                       TypeSourceInfo *TInfo,
15813                                       ArrayRef<OffsetOfComponent> Components,
15814                                       SourceLocation RParenLoc) {
15815   QualType ArgTy = TInfo->getType();
15816   bool Dependent = ArgTy->isDependentType();
15817   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15818 
15819   // We must have at least one component that refers to the type, and the first
15820   // one is known to be a field designator.  Verify that the ArgTy represents
15821   // a struct/union/class.
15822   if (!Dependent && !ArgTy->isRecordType())
15823     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15824                        << ArgTy << TypeRange);
15825 
15826   // Type must be complete per C99 7.17p3 because a declaring a variable
15827   // with an incomplete type would be ill-formed.
15828   if (!Dependent
15829       && RequireCompleteType(BuiltinLoc, ArgTy,
15830                              diag::err_offsetof_incomplete_type, TypeRange))
15831     return ExprError();
15832 
15833   bool DidWarnAboutNonPOD = false;
15834   QualType CurrentType = ArgTy;
15835   SmallVector<OffsetOfNode, 4> Comps;
15836   SmallVector<Expr*, 4> Exprs;
15837   for (const OffsetOfComponent &OC : Components) {
15838     if (OC.isBrackets) {
15839       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15840       if (!CurrentType->isDependentType()) {
15841         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15842         if(!AT)
15843           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15844                            << CurrentType);
15845         CurrentType = AT->getElementType();
15846       } else
15847         CurrentType = Context.DependentTy;
15848 
15849       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15850       if (IdxRval.isInvalid())
15851         return ExprError();
15852       Expr *Idx = IdxRval.get();
15853 
15854       // The expression must be an integral expression.
15855       // FIXME: An integral constant expression?
15856       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15857           !Idx->getType()->isIntegerType())
15858         return ExprError(
15859             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15860             << Idx->getSourceRange());
15861 
15862       // Record this array index.
15863       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15864       Exprs.push_back(Idx);
15865       continue;
15866     }
15867 
15868     // Offset of a field.
15869     if (CurrentType->isDependentType()) {
15870       // We have the offset of a field, but we can't look into the dependent
15871       // type. Just record the identifier of the field.
15872       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15873       CurrentType = Context.DependentTy;
15874       continue;
15875     }
15876 
15877     // We need to have a complete type to look into.
15878     if (RequireCompleteType(OC.LocStart, CurrentType,
15879                             diag::err_offsetof_incomplete_type))
15880       return ExprError();
15881 
15882     // Look for the designated field.
15883     const RecordType *RC = CurrentType->getAs<RecordType>();
15884     if (!RC)
15885       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15886                        << CurrentType);
15887     RecordDecl *RD = RC->getDecl();
15888 
15889     // C++ [lib.support.types]p5:
15890     //   The macro offsetof accepts a restricted set of type arguments in this
15891     //   International Standard. type shall be a POD structure or a POD union
15892     //   (clause 9).
15893     // C++11 [support.types]p4:
15894     //   If type is not a standard-layout class (Clause 9), the results are
15895     //   undefined.
15896     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15897       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15898       unsigned DiagID =
15899         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15900                             : diag::ext_offsetof_non_pod_type;
15901 
15902       if (!IsSafe && !DidWarnAboutNonPOD &&
15903           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15904                               PDiag(DiagID)
15905                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15906                               << CurrentType))
15907         DidWarnAboutNonPOD = true;
15908     }
15909 
15910     // Look for the field.
15911     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15912     LookupQualifiedName(R, RD);
15913     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15914     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15915     if (!MemberDecl) {
15916       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15917         MemberDecl = IndirectMemberDecl->getAnonField();
15918     }
15919 
15920     if (!MemberDecl)
15921       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15922                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15923                                                               OC.LocEnd));
15924 
15925     // C99 7.17p3:
15926     //   (If the specified member is a bit-field, the behavior is undefined.)
15927     //
15928     // We diagnose this as an error.
15929     if (MemberDecl->isBitField()) {
15930       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15931         << MemberDecl->getDeclName()
15932         << SourceRange(BuiltinLoc, RParenLoc);
15933       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15934       return ExprError();
15935     }
15936 
15937     RecordDecl *Parent = MemberDecl->getParent();
15938     if (IndirectMemberDecl)
15939       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15940 
15941     // If the member was found in a base class, introduce OffsetOfNodes for
15942     // the base class indirections.
15943     CXXBasePaths Paths;
15944     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15945                       Paths)) {
15946       if (Paths.getDetectedVirtual()) {
15947         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15948           << MemberDecl->getDeclName()
15949           << SourceRange(BuiltinLoc, RParenLoc);
15950         return ExprError();
15951       }
15952 
15953       CXXBasePath &Path = Paths.front();
15954       for (const CXXBasePathElement &B : Path)
15955         Comps.push_back(OffsetOfNode(B.Base));
15956     }
15957 
15958     if (IndirectMemberDecl) {
15959       for (auto *FI : IndirectMemberDecl->chain()) {
15960         assert(isa<FieldDecl>(FI));
15961         Comps.push_back(OffsetOfNode(OC.LocStart,
15962                                      cast<FieldDecl>(FI), OC.LocEnd));
15963       }
15964     } else
15965       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15966 
15967     CurrentType = MemberDecl->getType().getNonReferenceType();
15968   }
15969 
15970   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15971                               Comps, Exprs, RParenLoc);
15972 }
15973 
15974 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15975                                       SourceLocation BuiltinLoc,
15976                                       SourceLocation TypeLoc,
15977                                       ParsedType ParsedArgTy,
15978                                       ArrayRef<OffsetOfComponent> Components,
15979                                       SourceLocation RParenLoc) {
15980 
15981   TypeSourceInfo *ArgTInfo;
15982   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15983   if (ArgTy.isNull())
15984     return ExprError();
15985 
15986   if (!ArgTInfo)
15987     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15988 
15989   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15990 }
15991 
15992 
15993 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15994                                  Expr *CondExpr,
15995                                  Expr *LHSExpr, Expr *RHSExpr,
15996                                  SourceLocation RPLoc) {
15997   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15998 
15999   ExprValueKind VK = VK_PRValue;
16000   ExprObjectKind OK = OK_Ordinary;
16001   QualType resType;
16002   bool CondIsTrue = false;
16003   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16004     resType = Context.DependentTy;
16005   } else {
16006     // The conditional expression is required to be a constant expression.
16007     llvm::APSInt condEval(32);
16008     ExprResult CondICE = VerifyIntegerConstantExpression(
16009         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16010     if (CondICE.isInvalid())
16011       return ExprError();
16012     CondExpr = CondICE.get();
16013     CondIsTrue = condEval.getZExtValue();
16014 
16015     // If the condition is > zero, then the AST type is the same as the LHSExpr.
16016     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16017 
16018     resType = ActiveExpr->getType();
16019     VK = ActiveExpr->getValueKind();
16020     OK = ActiveExpr->getObjectKind();
16021   }
16022 
16023   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16024                                   resType, VK, OK, RPLoc, CondIsTrue);
16025 }
16026 
16027 //===----------------------------------------------------------------------===//
16028 // Clang Extensions.
16029 //===----------------------------------------------------------------------===//
16030 
16031 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16032 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16033   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16034 
16035   if (LangOpts.CPlusPlus) {
16036     MangleNumberingContext *MCtx;
16037     Decl *ManglingContextDecl;
16038     std::tie(MCtx, ManglingContextDecl) =
16039         getCurrentMangleNumberContext(Block->getDeclContext());
16040     if (MCtx) {
16041       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16042       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16043     }
16044   }
16045 
16046   PushBlockScope(CurScope, Block);
16047   CurContext->addDecl(Block);
16048   if (CurScope)
16049     PushDeclContext(CurScope, Block);
16050   else
16051     CurContext = Block;
16052 
16053   getCurBlock()->HasImplicitReturnType = true;
16054 
16055   // Enter a new evaluation context to insulate the block from any
16056   // cleanups from the enclosing full-expression.
16057   PushExpressionEvaluationContext(
16058       ExpressionEvaluationContext::PotentiallyEvaluated);
16059 }
16060 
16061 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16062                                Scope *CurScope) {
16063   assert(ParamInfo.getIdentifier() == nullptr &&
16064          "block-id should have no identifier!");
16065   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16066   BlockScopeInfo *CurBlock = getCurBlock();
16067 
16068   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16069   QualType T = Sig->getType();
16070 
16071   // FIXME: We should allow unexpanded parameter packs here, but that would,
16072   // in turn, make the block expression contain unexpanded parameter packs.
16073   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16074     // Drop the parameters.
16075     FunctionProtoType::ExtProtoInfo EPI;
16076     EPI.HasTrailingReturn = false;
16077     EPI.TypeQuals.addConst();
16078     T = Context.getFunctionType(Context.DependentTy, None, EPI);
16079     Sig = Context.getTrivialTypeSourceInfo(T);
16080   }
16081 
16082   // GetTypeForDeclarator always produces a function type for a block
16083   // literal signature.  Furthermore, it is always a FunctionProtoType
16084   // unless the function was written with a typedef.
16085   assert(T->isFunctionType() &&
16086          "GetTypeForDeclarator made a non-function block signature");
16087 
16088   // Look for an explicit signature in that function type.
16089   FunctionProtoTypeLoc ExplicitSignature;
16090 
16091   if ((ExplicitSignature = Sig->getTypeLoc()
16092                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
16093 
16094     // Check whether that explicit signature was synthesized by
16095     // GetTypeForDeclarator.  If so, don't save that as part of the
16096     // written signature.
16097     if (ExplicitSignature.getLocalRangeBegin() ==
16098         ExplicitSignature.getLocalRangeEnd()) {
16099       // This would be much cheaper if we stored TypeLocs instead of
16100       // TypeSourceInfos.
16101       TypeLoc Result = ExplicitSignature.getReturnLoc();
16102       unsigned Size = Result.getFullDataSize();
16103       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16104       Sig->getTypeLoc().initializeFullCopy(Result, Size);
16105 
16106       ExplicitSignature = FunctionProtoTypeLoc();
16107     }
16108   }
16109 
16110   CurBlock->TheDecl->setSignatureAsWritten(Sig);
16111   CurBlock->FunctionType = T;
16112 
16113   const auto *Fn = T->castAs<FunctionType>();
16114   QualType RetTy = Fn->getReturnType();
16115   bool isVariadic =
16116       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16117 
16118   CurBlock->TheDecl->setIsVariadic(isVariadic);
16119 
16120   // Context.DependentTy is used as a placeholder for a missing block
16121   // return type.  TODO:  what should we do with declarators like:
16122   //   ^ * { ... }
16123   // If the answer is "apply template argument deduction"....
16124   if (RetTy != Context.DependentTy) {
16125     CurBlock->ReturnType = RetTy;
16126     CurBlock->TheDecl->setBlockMissingReturnType(false);
16127     CurBlock->HasImplicitReturnType = false;
16128   }
16129 
16130   // Push block parameters from the declarator if we had them.
16131   SmallVector<ParmVarDecl*, 8> Params;
16132   if (ExplicitSignature) {
16133     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16134       ParmVarDecl *Param = ExplicitSignature.getParam(I);
16135       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16136           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16137         // Diagnose this as an extension in C17 and earlier.
16138         if (!getLangOpts().C2x)
16139           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16140       }
16141       Params.push_back(Param);
16142     }
16143 
16144   // Fake up parameter variables if we have a typedef, like
16145   //   ^ fntype { ... }
16146   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16147     for (const auto &I : Fn->param_types()) {
16148       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16149           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16150       Params.push_back(Param);
16151     }
16152   }
16153 
16154   // Set the parameters on the block decl.
16155   if (!Params.empty()) {
16156     CurBlock->TheDecl->setParams(Params);
16157     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16158                              /*CheckParameterNames=*/false);
16159   }
16160 
16161   // Finally we can process decl attributes.
16162   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16163 
16164   // Put the parameter variables in scope.
16165   for (auto AI : CurBlock->TheDecl->parameters()) {
16166     AI->setOwningFunction(CurBlock->TheDecl);
16167 
16168     // If this has an identifier, add it to the scope stack.
16169     if (AI->getIdentifier()) {
16170       CheckShadow(CurBlock->TheScope, AI);
16171 
16172       PushOnScopeChains(AI, CurBlock->TheScope);
16173     }
16174   }
16175 }
16176 
16177 /// ActOnBlockError - If there is an error parsing a block, this callback
16178 /// is invoked to pop the information about the block from the action impl.
16179 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16180   // Leave the expression-evaluation context.
16181   DiscardCleanupsInEvaluationContext();
16182   PopExpressionEvaluationContext();
16183 
16184   // Pop off CurBlock, handle nested blocks.
16185   PopDeclContext();
16186   PopFunctionScopeInfo();
16187 }
16188 
16189 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16190 /// literal was successfully completed.  ^(int x){...}
16191 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16192                                     Stmt *Body, Scope *CurScope) {
16193   // If blocks are disabled, emit an error.
16194   if (!LangOpts.Blocks)
16195     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16196 
16197   // Leave the expression-evaluation context.
16198   if (hasAnyUnrecoverableErrorsInThisFunction())
16199     DiscardCleanupsInEvaluationContext();
16200   assert(!Cleanup.exprNeedsCleanups() &&
16201          "cleanups within block not correctly bound!");
16202   PopExpressionEvaluationContext();
16203 
16204   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16205   BlockDecl *BD = BSI->TheDecl;
16206 
16207   if (BSI->HasImplicitReturnType)
16208     deduceClosureReturnType(*BSI);
16209 
16210   QualType RetTy = Context.VoidTy;
16211   if (!BSI->ReturnType.isNull())
16212     RetTy = BSI->ReturnType;
16213 
16214   bool NoReturn = BD->hasAttr<NoReturnAttr>();
16215   QualType BlockTy;
16216 
16217   // If the user wrote a function type in some form, try to use that.
16218   if (!BSI->FunctionType.isNull()) {
16219     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16220 
16221     FunctionType::ExtInfo Ext = FTy->getExtInfo();
16222     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16223 
16224     // Turn protoless block types into nullary block types.
16225     if (isa<FunctionNoProtoType>(FTy)) {
16226       FunctionProtoType::ExtProtoInfo EPI;
16227       EPI.ExtInfo = Ext;
16228       BlockTy = Context.getFunctionType(RetTy, None, EPI);
16229 
16230     // Otherwise, if we don't need to change anything about the function type,
16231     // preserve its sugar structure.
16232     } else if (FTy->getReturnType() == RetTy &&
16233                (!NoReturn || FTy->getNoReturnAttr())) {
16234       BlockTy = BSI->FunctionType;
16235 
16236     // Otherwise, make the minimal modifications to the function type.
16237     } else {
16238       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16239       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16240       EPI.TypeQuals = Qualifiers();
16241       EPI.ExtInfo = Ext;
16242       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16243     }
16244 
16245   // If we don't have a function type, just build one from nothing.
16246   } else {
16247     FunctionProtoType::ExtProtoInfo EPI;
16248     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16249     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16250   }
16251 
16252   DiagnoseUnusedParameters(BD->parameters());
16253   BlockTy = Context.getBlockPointerType(BlockTy);
16254 
16255   // If needed, diagnose invalid gotos and switches in the block.
16256   if (getCurFunction()->NeedsScopeChecking() &&
16257       !PP.isCodeCompletionEnabled())
16258     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16259 
16260   BD->setBody(cast<CompoundStmt>(Body));
16261 
16262   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16263     DiagnoseUnguardedAvailabilityViolations(BD);
16264 
16265   // Try to apply the named return value optimization. We have to check again
16266   // if we can do this, though, because blocks keep return statements around
16267   // to deduce an implicit return type.
16268   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16269       !BD->isDependentContext())
16270     computeNRVO(Body, BSI);
16271 
16272   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16273       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16274     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16275                           NTCUK_Destruct|NTCUK_Copy);
16276 
16277   PopDeclContext();
16278 
16279   // Set the captured variables on the block.
16280   SmallVector<BlockDecl::Capture, 4> Captures;
16281   for (Capture &Cap : BSI->Captures) {
16282     if (Cap.isInvalid() || Cap.isThisCapture())
16283       continue;
16284 
16285     VarDecl *Var = Cap.getVariable();
16286     Expr *CopyExpr = nullptr;
16287     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16288       if (const RecordType *Record =
16289               Cap.getCaptureType()->getAs<RecordType>()) {
16290         // The capture logic needs the destructor, so make sure we mark it.
16291         // Usually this is unnecessary because most local variables have
16292         // their destructors marked at declaration time, but parameters are
16293         // an exception because it's technically only the call site that
16294         // actually requires the destructor.
16295         if (isa<ParmVarDecl>(Var))
16296           FinalizeVarWithDestructor(Var, Record);
16297 
16298         // Enter a separate potentially-evaluated context while building block
16299         // initializers to isolate their cleanups from those of the block
16300         // itself.
16301         // FIXME: Is this appropriate even when the block itself occurs in an
16302         // unevaluated operand?
16303         EnterExpressionEvaluationContext EvalContext(
16304             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16305 
16306         SourceLocation Loc = Cap.getLocation();
16307 
16308         ExprResult Result = BuildDeclarationNameExpr(
16309             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16310 
16311         // According to the blocks spec, the capture of a variable from
16312         // the stack requires a const copy constructor.  This is not true
16313         // of the copy/move done to move a __block variable to the heap.
16314         if (!Result.isInvalid() &&
16315             !Result.get()->getType().isConstQualified()) {
16316           Result = ImpCastExprToType(Result.get(),
16317                                      Result.get()->getType().withConst(),
16318                                      CK_NoOp, VK_LValue);
16319         }
16320 
16321         if (!Result.isInvalid()) {
16322           Result = PerformCopyInitialization(
16323               InitializedEntity::InitializeBlock(Var->getLocation(),
16324                                                  Cap.getCaptureType()),
16325               Loc, Result.get());
16326         }
16327 
16328         // Build a full-expression copy expression if initialization
16329         // succeeded and used a non-trivial constructor.  Recover from
16330         // errors by pretending that the copy isn't necessary.
16331         if (!Result.isInvalid() &&
16332             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16333                 ->isTrivial()) {
16334           Result = MaybeCreateExprWithCleanups(Result);
16335           CopyExpr = Result.get();
16336         }
16337       }
16338     }
16339 
16340     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16341                               CopyExpr);
16342     Captures.push_back(NewCap);
16343   }
16344   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16345 
16346   // Pop the block scope now but keep it alive to the end of this function.
16347   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16348   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16349 
16350   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16351 
16352   // If the block isn't obviously global, i.e. it captures anything at
16353   // all, then we need to do a few things in the surrounding context:
16354   if (Result->getBlockDecl()->hasCaptures()) {
16355     // First, this expression has a new cleanup object.
16356     ExprCleanupObjects.push_back(Result->getBlockDecl());
16357     Cleanup.setExprNeedsCleanups(true);
16358 
16359     // It also gets a branch-protected scope if any of the captured
16360     // variables needs destruction.
16361     for (const auto &CI : Result->getBlockDecl()->captures()) {
16362       const VarDecl *var = CI.getVariable();
16363       if (var->getType().isDestructedType() != QualType::DK_none) {
16364         setFunctionHasBranchProtectedScope();
16365         break;
16366       }
16367     }
16368   }
16369 
16370   if (getCurFunction())
16371     getCurFunction()->addBlock(BD);
16372 
16373   return Result;
16374 }
16375 
16376 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16377                             SourceLocation RPLoc) {
16378   TypeSourceInfo *TInfo;
16379   GetTypeFromParser(Ty, &TInfo);
16380   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16381 }
16382 
16383 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16384                                 Expr *E, TypeSourceInfo *TInfo,
16385                                 SourceLocation RPLoc) {
16386   Expr *OrigExpr = E;
16387   bool IsMS = false;
16388 
16389   // CUDA device code does not support varargs.
16390   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16391     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16392       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16393       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16394         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16395     }
16396   }
16397 
16398   // NVPTX does not support va_arg expression.
16399   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16400       Context.getTargetInfo().getTriple().isNVPTX())
16401     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16402 
16403   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16404   // as Microsoft ABI on an actual Microsoft platform, where
16405   // __builtin_ms_va_list and __builtin_va_list are the same.)
16406   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16407       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16408     QualType MSVaListType = Context.getBuiltinMSVaListType();
16409     if (Context.hasSameType(MSVaListType, E->getType())) {
16410       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16411         return ExprError();
16412       IsMS = true;
16413     }
16414   }
16415 
16416   // Get the va_list type
16417   QualType VaListType = Context.getBuiltinVaListType();
16418   if (!IsMS) {
16419     if (VaListType->isArrayType()) {
16420       // Deal with implicit array decay; for example, on x86-64,
16421       // va_list is an array, but it's supposed to decay to
16422       // a pointer for va_arg.
16423       VaListType = Context.getArrayDecayedType(VaListType);
16424       // Make sure the input expression also decays appropriately.
16425       ExprResult Result = UsualUnaryConversions(E);
16426       if (Result.isInvalid())
16427         return ExprError();
16428       E = Result.get();
16429     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16430       // If va_list is a record type and we are compiling in C++ mode,
16431       // check the argument using reference binding.
16432       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16433           Context, Context.getLValueReferenceType(VaListType), false);
16434       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16435       if (Init.isInvalid())
16436         return ExprError();
16437       E = Init.getAs<Expr>();
16438     } else {
16439       // Otherwise, the va_list argument must be an l-value because
16440       // it is modified by va_arg.
16441       if (!E->isTypeDependent() &&
16442           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16443         return ExprError();
16444     }
16445   }
16446 
16447   if (!IsMS && !E->isTypeDependent() &&
16448       !Context.hasSameType(VaListType, E->getType()))
16449     return ExprError(
16450         Diag(E->getBeginLoc(),
16451              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16452         << OrigExpr->getType() << E->getSourceRange());
16453 
16454   if (!TInfo->getType()->isDependentType()) {
16455     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16456                             diag::err_second_parameter_to_va_arg_incomplete,
16457                             TInfo->getTypeLoc()))
16458       return ExprError();
16459 
16460     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16461                                TInfo->getType(),
16462                                diag::err_second_parameter_to_va_arg_abstract,
16463                                TInfo->getTypeLoc()))
16464       return ExprError();
16465 
16466     if (!TInfo->getType().isPODType(Context)) {
16467       Diag(TInfo->getTypeLoc().getBeginLoc(),
16468            TInfo->getType()->isObjCLifetimeType()
16469              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16470              : diag::warn_second_parameter_to_va_arg_not_pod)
16471         << TInfo->getType()
16472         << TInfo->getTypeLoc().getSourceRange();
16473     }
16474 
16475     // Check for va_arg where arguments of the given type will be promoted
16476     // (i.e. this va_arg is guaranteed to have undefined behavior).
16477     QualType PromoteType;
16478     if (TInfo->getType()->isPromotableIntegerType()) {
16479       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16480       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16481       // and C2x 7.16.1.1p2 says, in part:
16482       //   If type is not compatible with the type of the actual next argument
16483       //   (as promoted according to the default argument promotions), the
16484       //   behavior is undefined, except for the following cases:
16485       //     - both types are pointers to qualified or unqualified versions of
16486       //       compatible types;
16487       //     - one type is a signed integer type, the other type is the
16488       //       corresponding unsigned integer type, and the value is
16489       //       representable in both types;
16490       //     - one type is pointer to qualified or unqualified void and the
16491       //       other is a pointer to a qualified or unqualified character type.
16492       // Given that type compatibility is the primary requirement (ignoring
16493       // qualifications), you would think we could call typesAreCompatible()
16494       // directly to test this. However, in C++, that checks for *same type*,
16495       // which causes false positives when passing an enumeration type to
16496       // va_arg. Instead, get the underlying type of the enumeration and pass
16497       // that.
16498       QualType UnderlyingType = TInfo->getType();
16499       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16500         UnderlyingType = ET->getDecl()->getIntegerType();
16501       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16502                                      /*CompareUnqualified*/ true))
16503         PromoteType = QualType();
16504 
16505       // If the types are still not compatible, we need to test whether the
16506       // promoted type and the underlying type are the same except for
16507       // signedness. Ask the AST for the correctly corresponding type and see
16508       // if that's compatible.
16509       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16510           PromoteType->isUnsignedIntegerType() !=
16511               UnderlyingType->isUnsignedIntegerType()) {
16512         UnderlyingType =
16513             UnderlyingType->isUnsignedIntegerType()
16514                 ? Context.getCorrespondingSignedType(UnderlyingType)
16515                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16516         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16517                                        /*CompareUnqualified*/ true))
16518           PromoteType = QualType();
16519       }
16520     }
16521     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16522       PromoteType = Context.DoubleTy;
16523     if (!PromoteType.isNull())
16524       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16525                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16526                           << TInfo->getType()
16527                           << PromoteType
16528                           << TInfo->getTypeLoc().getSourceRange());
16529   }
16530 
16531   QualType T = TInfo->getType().getNonLValueExprType(Context);
16532   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16533 }
16534 
16535 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16536   // The type of __null will be int or long, depending on the size of
16537   // pointers on the target.
16538   QualType Ty;
16539   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16540   if (pw == Context.getTargetInfo().getIntWidth())
16541     Ty = Context.IntTy;
16542   else if (pw == Context.getTargetInfo().getLongWidth())
16543     Ty = Context.LongTy;
16544   else if (pw == Context.getTargetInfo().getLongLongWidth())
16545     Ty = Context.LongLongTy;
16546   else {
16547     llvm_unreachable("I don't know size of pointer!");
16548   }
16549 
16550   return new (Context) GNUNullExpr(Ty, TokenLoc);
16551 }
16552 
16553 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16554   CXXRecordDecl *ImplDecl = nullptr;
16555 
16556   // Fetch the std::source_location::__impl decl.
16557   if (NamespaceDecl *Std = S.getStdNamespace()) {
16558     LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16559                           Loc, Sema::LookupOrdinaryName);
16560     if (S.LookupQualifiedName(ResultSL, Std)) {
16561       if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16562         LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16563                                 Loc, Sema::LookupOrdinaryName);
16564         if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16565             S.LookupQualifiedName(ResultImpl, SLDecl)) {
16566           ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16567         }
16568       }
16569     }
16570   }
16571 
16572   if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16573     S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16574     return nullptr;
16575   }
16576 
16577   // Verify that __impl is a trivial struct type, with no base classes, and with
16578   // only the four expected fields.
16579   if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16580       ImplDecl->getNumBases() != 0) {
16581     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16582     return nullptr;
16583   }
16584 
16585   unsigned Count = 0;
16586   for (FieldDecl *F : ImplDecl->fields()) {
16587     StringRef Name = F->getName();
16588 
16589     if (Name == "_M_file_name") {
16590       if (F->getType() !=
16591           S.Context.getPointerType(S.Context.CharTy.withConst()))
16592         break;
16593       Count++;
16594     } else if (Name == "_M_function_name") {
16595       if (F->getType() !=
16596           S.Context.getPointerType(S.Context.CharTy.withConst()))
16597         break;
16598       Count++;
16599     } else if (Name == "_M_line") {
16600       if (!F->getType()->isIntegerType())
16601         break;
16602       Count++;
16603     } else if (Name == "_M_column") {
16604       if (!F->getType()->isIntegerType())
16605         break;
16606       Count++;
16607     } else {
16608       Count = 100; // invalid
16609       break;
16610     }
16611   }
16612   if (Count != 4) {
16613     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16614     return nullptr;
16615   }
16616 
16617   return ImplDecl;
16618 }
16619 
16620 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16621                                     SourceLocation BuiltinLoc,
16622                                     SourceLocation RPLoc) {
16623   QualType ResultTy;
16624   switch (Kind) {
16625   case SourceLocExpr::File:
16626   case SourceLocExpr::Function: {
16627     QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16628     ResultTy =
16629         Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16630     break;
16631   }
16632   case SourceLocExpr::Line:
16633   case SourceLocExpr::Column:
16634     ResultTy = Context.UnsignedIntTy;
16635     break;
16636   case SourceLocExpr::SourceLocStruct:
16637     if (!StdSourceLocationImplDecl) {
16638       StdSourceLocationImplDecl =
16639           LookupStdSourceLocationImpl(*this, BuiltinLoc);
16640       if (!StdSourceLocationImplDecl)
16641         return ExprError();
16642     }
16643     ResultTy = Context.getPointerType(
16644         Context.getRecordType(StdSourceLocationImplDecl).withConst());
16645     break;
16646   }
16647 
16648   return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16649 }
16650 
16651 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16652                                     QualType ResultTy,
16653                                     SourceLocation BuiltinLoc,
16654                                     SourceLocation RPLoc,
16655                                     DeclContext *ParentContext) {
16656   return new (Context)
16657       SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16658 }
16659 
16660 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16661                                         bool Diagnose) {
16662   if (!getLangOpts().ObjC)
16663     return false;
16664 
16665   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16666   if (!PT)
16667     return false;
16668   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16669 
16670   // Ignore any parens, implicit casts (should only be
16671   // array-to-pointer decays), and not-so-opaque values.  The last is
16672   // important for making this trigger for property assignments.
16673   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16674   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16675     if (OV->getSourceExpr())
16676       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16677 
16678   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16679     if (!PT->isObjCIdType() &&
16680         !(ID && ID->getIdentifier()->isStr("NSString")))
16681       return false;
16682     if (!SL->isAscii())
16683       return false;
16684 
16685     if (Diagnose) {
16686       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16687           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16688       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16689     }
16690     return true;
16691   }
16692 
16693   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16694       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16695       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16696       !SrcExpr->isNullPointerConstant(
16697           getASTContext(), Expr::NPC_NeverValueDependent)) {
16698     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16699       return false;
16700     if (Diagnose) {
16701       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16702           << /*number*/1
16703           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16704       Expr *NumLit =
16705           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16706       if (NumLit)
16707         Exp = NumLit;
16708     }
16709     return true;
16710   }
16711 
16712   return false;
16713 }
16714 
16715 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16716                                               const Expr *SrcExpr) {
16717   if (!DstType->isFunctionPointerType() ||
16718       !SrcExpr->getType()->isFunctionType())
16719     return false;
16720 
16721   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16722   if (!DRE)
16723     return false;
16724 
16725   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16726   if (!FD)
16727     return false;
16728 
16729   return !S.checkAddressOfFunctionIsAvailable(FD,
16730                                               /*Complain=*/true,
16731                                               SrcExpr->getBeginLoc());
16732 }
16733 
16734 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16735                                     SourceLocation Loc,
16736                                     QualType DstType, QualType SrcType,
16737                                     Expr *SrcExpr, AssignmentAction Action,
16738                                     bool *Complained) {
16739   if (Complained)
16740     *Complained = false;
16741 
16742   // Decode the result (notice that AST's are still created for extensions).
16743   bool CheckInferredResultType = false;
16744   bool isInvalid = false;
16745   unsigned DiagKind = 0;
16746   ConversionFixItGenerator ConvHints;
16747   bool MayHaveConvFixit = false;
16748   bool MayHaveFunctionDiff = false;
16749   const ObjCInterfaceDecl *IFace = nullptr;
16750   const ObjCProtocolDecl *PDecl = nullptr;
16751 
16752   switch (ConvTy) {
16753   case Compatible:
16754       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16755       return false;
16756 
16757   case PointerToInt:
16758     if (getLangOpts().CPlusPlus) {
16759       DiagKind = diag::err_typecheck_convert_pointer_int;
16760       isInvalid = true;
16761     } else {
16762       DiagKind = diag::ext_typecheck_convert_pointer_int;
16763     }
16764     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16765     MayHaveConvFixit = true;
16766     break;
16767   case IntToPointer:
16768     if (getLangOpts().CPlusPlus) {
16769       DiagKind = diag::err_typecheck_convert_int_pointer;
16770       isInvalid = true;
16771     } else {
16772       DiagKind = diag::ext_typecheck_convert_int_pointer;
16773     }
16774     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16775     MayHaveConvFixit = true;
16776     break;
16777   case IncompatibleFunctionPointer:
16778     if (getLangOpts().CPlusPlus) {
16779       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16780       isInvalid = true;
16781     } else {
16782       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16783     }
16784     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16785     MayHaveConvFixit = true;
16786     break;
16787   case IncompatiblePointer:
16788     if (Action == AA_Passing_CFAudited) {
16789       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16790     } else if (getLangOpts().CPlusPlus) {
16791       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16792       isInvalid = true;
16793     } else {
16794       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16795     }
16796     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16797       SrcType->isObjCObjectPointerType();
16798     if (!CheckInferredResultType) {
16799       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16800     } else if (CheckInferredResultType) {
16801       SrcType = SrcType.getUnqualifiedType();
16802       DstType = DstType.getUnqualifiedType();
16803     }
16804     MayHaveConvFixit = true;
16805     break;
16806   case IncompatiblePointerSign:
16807     if (getLangOpts().CPlusPlus) {
16808       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16809       isInvalid = true;
16810     } else {
16811       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16812     }
16813     break;
16814   case FunctionVoidPointer:
16815     if (getLangOpts().CPlusPlus) {
16816       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16817       isInvalid = true;
16818     } else {
16819       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16820     }
16821     break;
16822   case IncompatiblePointerDiscardsQualifiers: {
16823     // Perform array-to-pointer decay if necessary.
16824     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16825 
16826     isInvalid = true;
16827 
16828     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16829     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16830     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16831       DiagKind = diag::err_typecheck_incompatible_address_space;
16832       break;
16833 
16834     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16835       DiagKind = diag::err_typecheck_incompatible_ownership;
16836       break;
16837     }
16838 
16839     llvm_unreachable("unknown error case for discarding qualifiers!");
16840     // fallthrough
16841   }
16842   case CompatiblePointerDiscardsQualifiers:
16843     // If the qualifiers lost were because we were applying the
16844     // (deprecated) C++ conversion from a string literal to a char*
16845     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16846     // Ideally, this check would be performed in
16847     // checkPointerTypesForAssignment. However, that would require a
16848     // bit of refactoring (so that the second argument is an
16849     // expression, rather than a type), which should be done as part
16850     // of a larger effort to fix checkPointerTypesForAssignment for
16851     // C++ semantics.
16852     if (getLangOpts().CPlusPlus &&
16853         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16854       return false;
16855     if (getLangOpts().CPlusPlus) {
16856       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16857       isInvalid = true;
16858     } else {
16859       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16860     }
16861 
16862     break;
16863   case IncompatibleNestedPointerQualifiers:
16864     if (getLangOpts().CPlusPlus) {
16865       isInvalid = true;
16866       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16867     } else {
16868       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16869     }
16870     break;
16871   case IncompatibleNestedPointerAddressSpaceMismatch:
16872     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16873     isInvalid = true;
16874     break;
16875   case IntToBlockPointer:
16876     DiagKind = diag::err_int_to_block_pointer;
16877     isInvalid = true;
16878     break;
16879   case IncompatibleBlockPointer:
16880     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16881     isInvalid = true;
16882     break;
16883   case IncompatibleObjCQualifiedId: {
16884     if (SrcType->isObjCQualifiedIdType()) {
16885       const ObjCObjectPointerType *srcOPT =
16886                 SrcType->castAs<ObjCObjectPointerType>();
16887       for (auto *srcProto : srcOPT->quals()) {
16888         PDecl = srcProto;
16889         break;
16890       }
16891       if (const ObjCInterfaceType *IFaceT =
16892             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16893         IFace = IFaceT->getDecl();
16894     }
16895     else if (DstType->isObjCQualifiedIdType()) {
16896       const ObjCObjectPointerType *dstOPT =
16897         DstType->castAs<ObjCObjectPointerType>();
16898       for (auto *dstProto : dstOPT->quals()) {
16899         PDecl = dstProto;
16900         break;
16901       }
16902       if (const ObjCInterfaceType *IFaceT =
16903             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16904         IFace = IFaceT->getDecl();
16905     }
16906     if (getLangOpts().CPlusPlus) {
16907       DiagKind = diag::err_incompatible_qualified_id;
16908       isInvalid = true;
16909     } else {
16910       DiagKind = diag::warn_incompatible_qualified_id;
16911     }
16912     break;
16913   }
16914   case IncompatibleVectors:
16915     if (getLangOpts().CPlusPlus) {
16916       DiagKind = diag::err_incompatible_vectors;
16917       isInvalid = true;
16918     } else {
16919       DiagKind = diag::warn_incompatible_vectors;
16920     }
16921     break;
16922   case IncompatibleObjCWeakRef:
16923     DiagKind = diag::err_arc_weak_unavailable_assign;
16924     isInvalid = true;
16925     break;
16926   case Incompatible:
16927     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16928       if (Complained)
16929         *Complained = true;
16930       return true;
16931     }
16932 
16933     DiagKind = diag::err_typecheck_convert_incompatible;
16934     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16935     MayHaveConvFixit = true;
16936     isInvalid = true;
16937     MayHaveFunctionDiff = true;
16938     break;
16939   }
16940 
16941   QualType FirstType, SecondType;
16942   switch (Action) {
16943   case AA_Assigning:
16944   case AA_Initializing:
16945     // The destination type comes first.
16946     FirstType = DstType;
16947     SecondType = SrcType;
16948     break;
16949 
16950   case AA_Returning:
16951   case AA_Passing:
16952   case AA_Passing_CFAudited:
16953   case AA_Converting:
16954   case AA_Sending:
16955   case AA_Casting:
16956     // The source type comes first.
16957     FirstType = SrcType;
16958     SecondType = DstType;
16959     break;
16960   }
16961 
16962   PartialDiagnostic FDiag = PDiag(DiagKind);
16963   AssignmentAction ActionForDiag = Action;
16964   if (Action == AA_Passing_CFAudited)
16965     ActionForDiag = AA_Passing;
16966 
16967   FDiag << FirstType << SecondType << ActionForDiag
16968         << SrcExpr->getSourceRange();
16969 
16970   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16971       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16972     auto isPlainChar = [](const clang::Type *Type) {
16973       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16974              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16975     };
16976     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16977               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16978   }
16979 
16980   // If we can fix the conversion, suggest the FixIts.
16981   if (!ConvHints.isNull()) {
16982     for (FixItHint &H : ConvHints.Hints)
16983       FDiag << H;
16984   }
16985 
16986   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16987 
16988   if (MayHaveFunctionDiff)
16989     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16990 
16991   Diag(Loc, FDiag);
16992   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16993        DiagKind == diag::err_incompatible_qualified_id) &&
16994       PDecl && IFace && !IFace->hasDefinition())
16995     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16996         << IFace << PDecl;
16997 
16998   if (SecondType == Context.OverloadTy)
16999     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17000                               FirstType, /*TakingAddress=*/true);
17001 
17002   if (CheckInferredResultType)
17003     EmitRelatedResultTypeNote(SrcExpr);
17004 
17005   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17006     EmitRelatedResultTypeNoteForReturn(DstType);
17007 
17008   if (Complained)
17009     *Complained = true;
17010   return isInvalid;
17011 }
17012 
17013 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17014                                                  llvm::APSInt *Result,
17015                                                  AllowFoldKind CanFold) {
17016   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17017   public:
17018     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17019                                              QualType T) override {
17020       return S.Diag(Loc, diag::err_ice_not_integral)
17021              << T << S.LangOpts.CPlusPlus;
17022     }
17023     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17024       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17025     }
17026   } Diagnoser;
17027 
17028   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17029 }
17030 
17031 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17032                                                  llvm::APSInt *Result,
17033                                                  unsigned DiagID,
17034                                                  AllowFoldKind CanFold) {
17035   class IDDiagnoser : public VerifyICEDiagnoser {
17036     unsigned DiagID;
17037 
17038   public:
17039     IDDiagnoser(unsigned DiagID)
17040       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17041 
17042     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17043       return S.Diag(Loc, DiagID);
17044     }
17045   } Diagnoser(DiagID);
17046 
17047   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17048 }
17049 
17050 Sema::SemaDiagnosticBuilder
17051 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17052                                              QualType T) {
17053   return diagnoseNotICE(S, Loc);
17054 }
17055 
17056 Sema::SemaDiagnosticBuilder
17057 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17058   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17059 }
17060 
17061 ExprResult
17062 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17063                                       VerifyICEDiagnoser &Diagnoser,
17064                                       AllowFoldKind CanFold) {
17065   SourceLocation DiagLoc = E->getBeginLoc();
17066 
17067   if (getLangOpts().CPlusPlus11) {
17068     // C++11 [expr.const]p5:
17069     //   If an expression of literal class type is used in a context where an
17070     //   integral constant expression is required, then that class type shall
17071     //   have a single non-explicit conversion function to an integral or
17072     //   unscoped enumeration type
17073     ExprResult Converted;
17074     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17075       VerifyICEDiagnoser &BaseDiagnoser;
17076     public:
17077       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17078           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17079                                 BaseDiagnoser.Suppress, true),
17080             BaseDiagnoser(BaseDiagnoser) {}
17081 
17082       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17083                                            QualType T) override {
17084         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17085       }
17086 
17087       SemaDiagnosticBuilder diagnoseIncomplete(
17088           Sema &S, SourceLocation Loc, QualType T) override {
17089         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17090       }
17091 
17092       SemaDiagnosticBuilder diagnoseExplicitConv(
17093           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17094         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17095       }
17096 
17097       SemaDiagnosticBuilder noteExplicitConv(
17098           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17099         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17100                  << ConvTy->isEnumeralType() << ConvTy;
17101       }
17102 
17103       SemaDiagnosticBuilder diagnoseAmbiguous(
17104           Sema &S, SourceLocation Loc, QualType T) override {
17105         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17106       }
17107 
17108       SemaDiagnosticBuilder noteAmbiguous(
17109           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17110         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17111                  << ConvTy->isEnumeralType() << ConvTy;
17112       }
17113 
17114       SemaDiagnosticBuilder diagnoseConversion(
17115           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17116         llvm_unreachable("conversion functions are permitted");
17117       }
17118     } ConvertDiagnoser(Diagnoser);
17119 
17120     Converted = PerformContextualImplicitConversion(DiagLoc, E,
17121                                                     ConvertDiagnoser);
17122     if (Converted.isInvalid())
17123       return Converted;
17124     E = Converted.get();
17125     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17126       return ExprError();
17127   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17128     // An ICE must be of integral or unscoped enumeration type.
17129     if (!Diagnoser.Suppress)
17130       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17131           << E->getSourceRange();
17132     return ExprError();
17133   }
17134 
17135   ExprResult RValueExpr = DefaultLvalueConversion(E);
17136   if (RValueExpr.isInvalid())
17137     return ExprError();
17138 
17139   E = RValueExpr.get();
17140 
17141   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17142   // in the non-ICE case.
17143   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17144     if (Result)
17145       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17146     if (!isa<ConstantExpr>(E))
17147       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17148                  : ConstantExpr::Create(Context, E);
17149     return E;
17150   }
17151 
17152   Expr::EvalResult EvalResult;
17153   SmallVector<PartialDiagnosticAt, 8> Notes;
17154   EvalResult.Diag = &Notes;
17155 
17156   // Try to evaluate the expression, and produce diagnostics explaining why it's
17157   // not a constant expression as a side-effect.
17158   bool Folded =
17159       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17160       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17161 
17162   if (!isa<ConstantExpr>(E))
17163     E = ConstantExpr::Create(Context, E, EvalResult.Val);
17164 
17165   // In C++11, we can rely on diagnostics being produced for any expression
17166   // which is not a constant expression. If no diagnostics were produced, then
17167   // this is a constant expression.
17168   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17169     if (Result)
17170       *Result = EvalResult.Val.getInt();
17171     return E;
17172   }
17173 
17174   // If our only note is the usual "invalid subexpression" note, just point
17175   // the caret at its location rather than producing an essentially
17176   // redundant note.
17177   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17178         diag::note_invalid_subexpr_in_const_expr) {
17179     DiagLoc = Notes[0].first;
17180     Notes.clear();
17181   }
17182 
17183   if (!Folded || !CanFold) {
17184     if (!Diagnoser.Suppress) {
17185       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17186       for (const PartialDiagnosticAt &Note : Notes)
17187         Diag(Note.first, Note.second);
17188     }
17189 
17190     return ExprError();
17191   }
17192 
17193   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17194   for (const PartialDiagnosticAt &Note : Notes)
17195     Diag(Note.first, Note.second);
17196 
17197   if (Result)
17198     *Result = EvalResult.Val.getInt();
17199   return E;
17200 }
17201 
17202 namespace {
17203   // Handle the case where we conclude a expression which we speculatively
17204   // considered to be unevaluated is actually evaluated.
17205   class TransformToPE : public TreeTransform<TransformToPE> {
17206     typedef TreeTransform<TransformToPE> BaseTransform;
17207 
17208   public:
17209     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17210 
17211     // Make sure we redo semantic analysis
17212     bool AlwaysRebuild() { return true; }
17213     bool ReplacingOriginal() { return true; }
17214 
17215     // We need to special-case DeclRefExprs referring to FieldDecls which
17216     // are not part of a member pointer formation; normal TreeTransforming
17217     // doesn't catch this case because of the way we represent them in the AST.
17218     // FIXME: This is a bit ugly; is it really the best way to handle this
17219     // case?
17220     //
17221     // Error on DeclRefExprs referring to FieldDecls.
17222     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17223       if (isa<FieldDecl>(E->getDecl()) &&
17224           !SemaRef.isUnevaluatedContext())
17225         return SemaRef.Diag(E->getLocation(),
17226                             diag::err_invalid_non_static_member_use)
17227             << E->getDecl() << E->getSourceRange();
17228 
17229       return BaseTransform::TransformDeclRefExpr(E);
17230     }
17231 
17232     // Exception: filter out member pointer formation
17233     ExprResult TransformUnaryOperator(UnaryOperator *E) {
17234       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17235         return E;
17236 
17237       return BaseTransform::TransformUnaryOperator(E);
17238     }
17239 
17240     // The body of a lambda-expression is in a separate expression evaluation
17241     // context so never needs to be transformed.
17242     // FIXME: Ideally we wouldn't transform the closure type either, and would
17243     // just recreate the capture expressions and lambda expression.
17244     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17245       return SkipLambdaBody(E, Body);
17246     }
17247   };
17248 }
17249 
17250 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17251   assert(isUnevaluatedContext() &&
17252          "Should only transform unevaluated expressions");
17253   ExprEvalContexts.back().Context =
17254       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17255   if (isUnevaluatedContext())
17256     return E;
17257   return TransformToPE(*this).TransformExpr(E);
17258 }
17259 
17260 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17261   assert(isUnevaluatedContext() &&
17262          "Should only transform unevaluated expressions");
17263   ExprEvalContexts.back().Context =
17264       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17265   if (isUnevaluatedContext())
17266     return TInfo;
17267   return TransformToPE(*this).TransformType(TInfo);
17268 }
17269 
17270 void
17271 Sema::PushExpressionEvaluationContext(
17272     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17273     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17274   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17275                                 LambdaContextDecl, ExprContext);
17276 
17277   // Discarded statements and immediate contexts nested in other
17278   // discarded statements or immediate context are themselves
17279   // a discarded statement or an immediate context, respectively.
17280   ExprEvalContexts.back().InDiscardedStatement =
17281       ExprEvalContexts[ExprEvalContexts.size() - 2]
17282           .isDiscardedStatementContext();
17283   ExprEvalContexts.back().InImmediateFunctionContext =
17284       ExprEvalContexts[ExprEvalContexts.size() - 2]
17285           .isImmediateFunctionContext();
17286 
17287   Cleanup.reset();
17288   if (!MaybeODRUseExprs.empty())
17289     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17290 }
17291 
17292 void
17293 Sema::PushExpressionEvaluationContext(
17294     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17295     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17296   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17297   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17298 }
17299 
17300 namespace {
17301 
17302 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17303   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17304   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17305     if (E->getOpcode() == UO_Deref)
17306       return CheckPossibleDeref(S, E->getSubExpr());
17307   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17308     return CheckPossibleDeref(S, E->getBase());
17309   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17310     return CheckPossibleDeref(S, E->getBase());
17311   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17312     QualType Inner;
17313     QualType Ty = E->getType();
17314     if (const auto *Ptr = Ty->getAs<PointerType>())
17315       Inner = Ptr->getPointeeType();
17316     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17317       Inner = Arr->getElementType();
17318     else
17319       return nullptr;
17320 
17321     if (Inner->hasAttr(attr::NoDeref))
17322       return E;
17323   }
17324   return nullptr;
17325 }
17326 
17327 } // namespace
17328 
17329 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17330   for (const Expr *E : Rec.PossibleDerefs) {
17331     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17332     if (DeclRef) {
17333       const ValueDecl *Decl = DeclRef->getDecl();
17334       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17335           << Decl->getName() << E->getSourceRange();
17336       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17337     } else {
17338       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17339           << E->getSourceRange();
17340     }
17341   }
17342   Rec.PossibleDerefs.clear();
17343 }
17344 
17345 /// Check whether E, which is either a discarded-value expression or an
17346 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17347 /// and if so, remove it from the list of volatile-qualified assignments that
17348 /// we are going to warn are deprecated.
17349 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17350   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17351     return;
17352 
17353   // Note: ignoring parens here is not justified by the standard rules, but
17354   // ignoring parentheses seems like a more reasonable approach, and this only
17355   // drives a deprecation warning so doesn't affect conformance.
17356   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17357     if (BO->getOpcode() == BO_Assign) {
17358       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17359       llvm::erase_value(LHSs, BO->getLHS());
17360     }
17361   }
17362 }
17363 
17364 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17365   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17366       !Decl->isConsteval() || isConstantEvaluated() ||
17367       RebuildingImmediateInvocation || isImmediateFunctionContext())
17368     return E;
17369 
17370   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17371   /// It's OK if this fails; we'll also remove this in
17372   /// HandleImmediateInvocations, but catching it here allows us to avoid
17373   /// walking the AST looking for it in simple cases.
17374   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17375     if (auto *DeclRef =
17376             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17377       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17378 
17379   E = MaybeCreateExprWithCleanups(E);
17380 
17381   ConstantExpr *Res = ConstantExpr::Create(
17382       getASTContext(), E.get(),
17383       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17384                                    getASTContext()),
17385       /*IsImmediateInvocation*/ true);
17386   /// Value-dependent constant expressions should not be immediately
17387   /// evaluated until they are instantiated.
17388   if (!Res->isValueDependent())
17389     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17390   return Res;
17391 }
17392 
17393 static void EvaluateAndDiagnoseImmediateInvocation(
17394     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17395   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17396   Expr::EvalResult Eval;
17397   Eval.Diag = &Notes;
17398   ConstantExpr *CE = Candidate.getPointer();
17399   bool Result = CE->EvaluateAsConstantExpr(
17400       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17401   if (!Result || !Notes.empty()) {
17402     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17403     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17404       InnerExpr = FunctionalCast->getSubExpr();
17405     FunctionDecl *FD = nullptr;
17406     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17407       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17408     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17409       FD = Call->getConstructor();
17410     else
17411       llvm_unreachable("unhandled decl kind");
17412     assert(FD->isConsteval());
17413     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17414     for (auto &Note : Notes)
17415       SemaRef.Diag(Note.first, Note.second);
17416     return;
17417   }
17418   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17419 }
17420 
17421 static void RemoveNestedImmediateInvocation(
17422     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17423     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17424   struct ComplexRemove : TreeTransform<ComplexRemove> {
17425     using Base = TreeTransform<ComplexRemove>;
17426     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17427     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17428     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17429         CurrentII;
17430     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17431                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17432                   SmallVector<Sema::ImmediateInvocationCandidate,
17433                               4>::reverse_iterator Current)
17434         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17435     void RemoveImmediateInvocation(ConstantExpr* E) {
17436       auto It = std::find_if(CurrentII, IISet.rend(),
17437                              [E](Sema::ImmediateInvocationCandidate Elem) {
17438                                return Elem.getPointer() == E;
17439                              });
17440       assert(It != IISet.rend() &&
17441              "ConstantExpr marked IsImmediateInvocation should "
17442              "be present");
17443       It->setInt(1); // Mark as deleted
17444     }
17445     ExprResult TransformConstantExpr(ConstantExpr *E) {
17446       if (!E->isImmediateInvocation())
17447         return Base::TransformConstantExpr(E);
17448       RemoveImmediateInvocation(E);
17449       return Base::TransformExpr(E->getSubExpr());
17450     }
17451     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17452     /// we need to remove its DeclRefExpr from the DRSet.
17453     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17454       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17455       return Base::TransformCXXOperatorCallExpr(E);
17456     }
17457     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17458     /// here.
17459     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17460       if (!Init)
17461         return Init;
17462       /// ConstantExpr are the first layer of implicit node to be removed so if
17463       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17464       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17465         if (CE->isImmediateInvocation())
17466           RemoveImmediateInvocation(CE);
17467       return Base::TransformInitializer(Init, NotCopyInit);
17468     }
17469     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17470       DRSet.erase(E);
17471       return E;
17472     }
17473     bool AlwaysRebuild() { return false; }
17474     bool ReplacingOriginal() { return true; }
17475     bool AllowSkippingCXXConstructExpr() {
17476       bool Res = AllowSkippingFirstCXXConstructExpr;
17477       AllowSkippingFirstCXXConstructExpr = true;
17478       return Res;
17479     }
17480     bool AllowSkippingFirstCXXConstructExpr = true;
17481   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17482                 Rec.ImmediateInvocationCandidates, It);
17483 
17484   /// CXXConstructExpr with a single argument are getting skipped by
17485   /// TreeTransform in some situtation because they could be implicit. This
17486   /// can only occur for the top-level CXXConstructExpr because it is used
17487   /// nowhere in the expression being transformed therefore will not be rebuilt.
17488   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17489   /// skipping the first CXXConstructExpr.
17490   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17491     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17492 
17493   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17494   assert(Res.isUsable());
17495   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17496   It->getPointer()->setSubExpr(Res.get());
17497 }
17498 
17499 static void
17500 HandleImmediateInvocations(Sema &SemaRef,
17501                            Sema::ExpressionEvaluationContextRecord &Rec) {
17502   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17503        Rec.ReferenceToConsteval.size() == 0) ||
17504       SemaRef.RebuildingImmediateInvocation)
17505     return;
17506 
17507   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17508   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17509   /// need to remove ReferenceToConsteval in the immediate invocation.
17510   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17511 
17512     /// Prevent sema calls during the tree transform from adding pointers that
17513     /// are already in the sets.
17514     llvm::SaveAndRestore<bool> DisableIITracking(
17515         SemaRef.RebuildingImmediateInvocation, true);
17516 
17517     /// Prevent diagnostic during tree transfrom as they are duplicates
17518     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17519 
17520     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17521          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17522       if (!It->getInt())
17523         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17524   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17525              Rec.ReferenceToConsteval.size()) {
17526     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17527       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17528       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17529       bool VisitDeclRefExpr(DeclRefExpr *E) {
17530         DRSet.erase(E);
17531         return DRSet.size();
17532       }
17533     } Visitor(Rec.ReferenceToConsteval);
17534     Visitor.TraverseStmt(
17535         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17536   }
17537   for (auto CE : Rec.ImmediateInvocationCandidates)
17538     if (!CE.getInt())
17539       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17540   for (auto DR : Rec.ReferenceToConsteval) {
17541     auto *FD = cast<FunctionDecl>(DR->getDecl());
17542     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17543         << FD;
17544     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17545   }
17546 }
17547 
17548 void Sema::PopExpressionEvaluationContext() {
17549   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17550   unsigned NumTypos = Rec.NumTypos;
17551 
17552   if (!Rec.Lambdas.empty()) {
17553     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17554     if (!getLangOpts().CPlusPlus20 &&
17555         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17556          Rec.isUnevaluated() ||
17557          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17558       unsigned D;
17559       if (Rec.isUnevaluated()) {
17560         // C++11 [expr.prim.lambda]p2:
17561         //   A lambda-expression shall not appear in an unevaluated operand
17562         //   (Clause 5).
17563         D = diag::err_lambda_unevaluated_operand;
17564       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17565         // C++1y [expr.const]p2:
17566         //   A conditional-expression e is a core constant expression unless the
17567         //   evaluation of e, following the rules of the abstract machine, would
17568         //   evaluate [...] a lambda-expression.
17569         D = diag::err_lambda_in_constant_expression;
17570       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17571         // C++17 [expr.prim.lamda]p2:
17572         // A lambda-expression shall not appear [...] in a template-argument.
17573         D = diag::err_lambda_in_invalid_context;
17574       } else
17575         llvm_unreachable("Couldn't infer lambda error message.");
17576 
17577       for (const auto *L : Rec.Lambdas)
17578         Diag(L->getBeginLoc(), D);
17579     }
17580   }
17581 
17582   WarnOnPendingNoDerefs(Rec);
17583   HandleImmediateInvocations(*this, Rec);
17584 
17585   // Warn on any volatile-qualified simple-assignments that are not discarded-
17586   // value expressions nor unevaluated operands (those cases get removed from
17587   // this list by CheckUnusedVolatileAssignment).
17588   for (auto *BO : Rec.VolatileAssignmentLHSs)
17589     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17590         << BO->getType();
17591 
17592   // When are coming out of an unevaluated context, clear out any
17593   // temporaries that we may have created as part of the evaluation of
17594   // the expression in that context: they aren't relevant because they
17595   // will never be constructed.
17596   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17597     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17598                              ExprCleanupObjects.end());
17599     Cleanup = Rec.ParentCleanup;
17600     CleanupVarDeclMarking();
17601     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17602   // Otherwise, merge the contexts together.
17603   } else {
17604     Cleanup.mergeFrom(Rec.ParentCleanup);
17605     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17606                             Rec.SavedMaybeODRUseExprs.end());
17607   }
17608 
17609   // Pop the current expression evaluation context off the stack.
17610   ExprEvalContexts.pop_back();
17611 
17612   // The global expression evaluation context record is never popped.
17613   ExprEvalContexts.back().NumTypos += NumTypos;
17614 }
17615 
17616 void Sema::DiscardCleanupsInEvaluationContext() {
17617   ExprCleanupObjects.erase(
17618          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17619          ExprCleanupObjects.end());
17620   Cleanup.reset();
17621   MaybeODRUseExprs.clear();
17622 }
17623 
17624 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17625   ExprResult Result = CheckPlaceholderExpr(E);
17626   if (Result.isInvalid())
17627     return ExprError();
17628   E = Result.get();
17629   if (!E->getType()->isVariablyModifiedType())
17630     return E;
17631   return TransformToPotentiallyEvaluated(E);
17632 }
17633 
17634 /// Are we in a context that is potentially constant evaluated per C++20
17635 /// [expr.const]p12?
17636 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17637   /// C++2a [expr.const]p12:
17638   //   An expression or conversion is potentially constant evaluated if it is
17639   switch (SemaRef.ExprEvalContexts.back().Context) {
17640     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17641     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17642 
17643       // -- a manifestly constant-evaluated expression,
17644     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17645     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17646     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17647       // -- a potentially-evaluated expression,
17648     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17649       // -- an immediate subexpression of a braced-init-list,
17650 
17651       // -- [FIXME] an expression of the form & cast-expression that occurs
17652       //    within a templated entity
17653       // -- a subexpression of one of the above that is not a subexpression of
17654       // a nested unevaluated operand.
17655       return true;
17656 
17657     case Sema::ExpressionEvaluationContext::Unevaluated:
17658     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17659       // Expressions in this context are never evaluated.
17660       return false;
17661   }
17662   llvm_unreachable("Invalid context");
17663 }
17664 
17665 /// Return true if this function has a calling convention that requires mangling
17666 /// in the size of the parameter pack.
17667 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17668   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17669   // we don't need parameter type sizes.
17670   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17671   if (!TT.isOSWindows() || !TT.isX86())
17672     return false;
17673 
17674   // If this is C++ and this isn't an extern "C" function, parameters do not
17675   // need to be complete. In this case, C++ mangling will apply, which doesn't
17676   // use the size of the parameters.
17677   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17678     return false;
17679 
17680   // Stdcall, fastcall, and vectorcall need this special treatment.
17681   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17682   switch (CC) {
17683   case CC_X86StdCall:
17684   case CC_X86FastCall:
17685   case CC_X86VectorCall:
17686     return true;
17687   default:
17688     break;
17689   }
17690   return false;
17691 }
17692 
17693 /// Require that all of the parameter types of function be complete. Normally,
17694 /// parameter types are only required to be complete when a function is called
17695 /// or defined, but to mangle functions with certain calling conventions, the
17696 /// mangler needs to know the size of the parameter list. In this situation,
17697 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17698 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17699 /// result in a linker error. Clang doesn't implement this behavior, and instead
17700 /// attempts to error at compile time.
17701 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17702                                                   SourceLocation Loc) {
17703   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17704     FunctionDecl *FD;
17705     ParmVarDecl *Param;
17706 
17707   public:
17708     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17709         : FD(FD), Param(Param) {}
17710 
17711     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17712       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17713       StringRef CCName;
17714       switch (CC) {
17715       case CC_X86StdCall:
17716         CCName = "stdcall";
17717         break;
17718       case CC_X86FastCall:
17719         CCName = "fastcall";
17720         break;
17721       case CC_X86VectorCall:
17722         CCName = "vectorcall";
17723         break;
17724       default:
17725         llvm_unreachable("CC does not need mangling");
17726       }
17727 
17728       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17729           << Param->getDeclName() << FD->getDeclName() << CCName;
17730     }
17731   };
17732 
17733   for (ParmVarDecl *Param : FD->parameters()) {
17734     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17735     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17736   }
17737 }
17738 
17739 namespace {
17740 enum class OdrUseContext {
17741   /// Declarations in this context are not odr-used.
17742   None,
17743   /// Declarations in this context are formally odr-used, but this is a
17744   /// dependent context.
17745   Dependent,
17746   /// Declarations in this context are odr-used but not actually used (yet).
17747   FormallyOdrUsed,
17748   /// Declarations in this context are used.
17749   Used
17750 };
17751 }
17752 
17753 /// Are we within a context in which references to resolved functions or to
17754 /// variables result in odr-use?
17755 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17756   OdrUseContext Result;
17757 
17758   switch (SemaRef.ExprEvalContexts.back().Context) {
17759     case Sema::ExpressionEvaluationContext::Unevaluated:
17760     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17761     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17762       return OdrUseContext::None;
17763 
17764     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17765     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17766     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17767       Result = OdrUseContext::Used;
17768       break;
17769 
17770     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17771       Result = OdrUseContext::FormallyOdrUsed;
17772       break;
17773 
17774     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17775       // A default argument formally results in odr-use, but doesn't actually
17776       // result in a use in any real sense until it itself is used.
17777       Result = OdrUseContext::FormallyOdrUsed;
17778       break;
17779   }
17780 
17781   if (SemaRef.CurContext->isDependentContext())
17782     return OdrUseContext::Dependent;
17783 
17784   return Result;
17785 }
17786 
17787 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17788   if (!Func->isConstexpr())
17789     return false;
17790 
17791   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17792     return true;
17793   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17794   return CCD && CCD->getInheritedConstructor();
17795 }
17796 
17797 /// Mark a function referenced, and check whether it is odr-used
17798 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17799 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17800                                   bool MightBeOdrUse) {
17801   assert(Func && "No function?");
17802 
17803   Func->setReferenced();
17804 
17805   // Recursive functions aren't really used until they're used from some other
17806   // context.
17807   bool IsRecursiveCall = CurContext == Func;
17808 
17809   // C++11 [basic.def.odr]p3:
17810   //   A function whose name appears as a potentially-evaluated expression is
17811   //   odr-used if it is the unique lookup result or the selected member of a
17812   //   set of overloaded functions [...].
17813   //
17814   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17815   // can just check that here.
17816   OdrUseContext OdrUse =
17817       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17818   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17819     OdrUse = OdrUseContext::FormallyOdrUsed;
17820 
17821   // Trivial default constructors and destructors are never actually used.
17822   // FIXME: What about other special members?
17823   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17824       OdrUse == OdrUseContext::Used) {
17825     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17826       if (Constructor->isDefaultConstructor())
17827         OdrUse = OdrUseContext::FormallyOdrUsed;
17828     if (isa<CXXDestructorDecl>(Func))
17829       OdrUse = OdrUseContext::FormallyOdrUsed;
17830   }
17831 
17832   // C++20 [expr.const]p12:
17833   //   A function [...] is needed for constant evaluation if it is [...] a
17834   //   constexpr function that is named by an expression that is potentially
17835   //   constant evaluated
17836   bool NeededForConstantEvaluation =
17837       isPotentiallyConstantEvaluatedContext(*this) &&
17838       isImplicitlyDefinableConstexprFunction(Func);
17839 
17840   // Determine whether we require a function definition to exist, per
17841   // C++11 [temp.inst]p3:
17842   //   Unless a function template specialization has been explicitly
17843   //   instantiated or explicitly specialized, the function template
17844   //   specialization is implicitly instantiated when the specialization is
17845   //   referenced in a context that requires a function definition to exist.
17846   // C++20 [temp.inst]p7:
17847   //   The existence of a definition of a [...] function is considered to
17848   //   affect the semantics of the program if the [...] function is needed for
17849   //   constant evaluation by an expression
17850   // C++20 [basic.def.odr]p10:
17851   //   Every program shall contain exactly one definition of every non-inline
17852   //   function or variable that is odr-used in that program outside of a
17853   //   discarded statement
17854   // C++20 [special]p1:
17855   //   The implementation will implicitly define [defaulted special members]
17856   //   if they are odr-used or needed for constant evaluation.
17857   //
17858   // Note that we skip the implicit instantiation of templates that are only
17859   // used in unused default arguments or by recursive calls to themselves.
17860   // This is formally non-conforming, but seems reasonable in practice.
17861   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17862                                              NeededForConstantEvaluation);
17863 
17864   // C++14 [temp.expl.spec]p6:
17865   //   If a template [...] is explicitly specialized then that specialization
17866   //   shall be declared before the first use of that specialization that would
17867   //   cause an implicit instantiation to take place, in every translation unit
17868   //   in which such a use occurs
17869   if (NeedDefinition &&
17870       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17871        Func->getMemberSpecializationInfo()))
17872     checkSpecializationVisibility(Loc, Func);
17873 
17874   if (getLangOpts().CUDA)
17875     CheckCUDACall(Loc, Func);
17876 
17877   if (getLangOpts().SYCLIsDevice)
17878     checkSYCLDeviceFunction(Loc, Func);
17879 
17880   // If we need a definition, try to create one.
17881   if (NeedDefinition && !Func->getBody()) {
17882     runWithSufficientStackSpace(Loc, [&] {
17883       if (CXXConstructorDecl *Constructor =
17884               dyn_cast<CXXConstructorDecl>(Func)) {
17885         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17886         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17887           if (Constructor->isDefaultConstructor()) {
17888             if (Constructor->isTrivial() &&
17889                 !Constructor->hasAttr<DLLExportAttr>())
17890               return;
17891             DefineImplicitDefaultConstructor(Loc, Constructor);
17892           } else if (Constructor->isCopyConstructor()) {
17893             DefineImplicitCopyConstructor(Loc, Constructor);
17894           } else if (Constructor->isMoveConstructor()) {
17895             DefineImplicitMoveConstructor(Loc, Constructor);
17896           }
17897         } else if (Constructor->getInheritedConstructor()) {
17898           DefineInheritingConstructor(Loc, Constructor);
17899         }
17900       } else if (CXXDestructorDecl *Destructor =
17901                      dyn_cast<CXXDestructorDecl>(Func)) {
17902         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17903         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17904           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17905             return;
17906           DefineImplicitDestructor(Loc, Destructor);
17907         }
17908         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17909           MarkVTableUsed(Loc, Destructor->getParent());
17910       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17911         if (MethodDecl->isOverloadedOperator() &&
17912             MethodDecl->getOverloadedOperator() == OO_Equal) {
17913           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17914           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17915             if (MethodDecl->isCopyAssignmentOperator())
17916               DefineImplicitCopyAssignment(Loc, MethodDecl);
17917             else if (MethodDecl->isMoveAssignmentOperator())
17918               DefineImplicitMoveAssignment(Loc, MethodDecl);
17919           }
17920         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17921                    MethodDecl->getParent()->isLambda()) {
17922           CXXConversionDecl *Conversion =
17923               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17924           if (Conversion->isLambdaToBlockPointerConversion())
17925             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17926           else
17927             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17928         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17929           MarkVTableUsed(Loc, MethodDecl->getParent());
17930       }
17931 
17932       if (Func->isDefaulted() && !Func->isDeleted()) {
17933         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17934         if (DCK != DefaultedComparisonKind::None)
17935           DefineDefaultedComparison(Loc, Func, DCK);
17936       }
17937 
17938       // Implicit instantiation of function templates and member functions of
17939       // class templates.
17940       if (Func->isImplicitlyInstantiable()) {
17941         TemplateSpecializationKind TSK =
17942             Func->getTemplateSpecializationKindForInstantiation();
17943         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17944         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17945         if (FirstInstantiation) {
17946           PointOfInstantiation = Loc;
17947           if (auto *MSI = Func->getMemberSpecializationInfo())
17948             MSI->setPointOfInstantiation(Loc);
17949             // FIXME: Notify listener.
17950           else
17951             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17952         } else if (TSK != TSK_ImplicitInstantiation) {
17953           // Use the point of use as the point of instantiation, instead of the
17954           // point of explicit instantiation (which we track as the actual point
17955           // of instantiation). This gives better backtraces in diagnostics.
17956           PointOfInstantiation = Loc;
17957         }
17958 
17959         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17960             Func->isConstexpr()) {
17961           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17962               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17963               CodeSynthesisContexts.size())
17964             PendingLocalImplicitInstantiations.push_back(
17965                 std::make_pair(Func, PointOfInstantiation));
17966           else if (Func->isConstexpr())
17967             // Do not defer instantiations of constexpr functions, to avoid the
17968             // expression evaluator needing to call back into Sema if it sees a
17969             // call to such a function.
17970             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17971           else {
17972             Func->setInstantiationIsPending(true);
17973             PendingInstantiations.push_back(
17974                 std::make_pair(Func, PointOfInstantiation));
17975             // Notify the consumer that a function was implicitly instantiated.
17976             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17977           }
17978         }
17979       } else {
17980         // Walk redefinitions, as some of them may be instantiable.
17981         for (auto i : Func->redecls()) {
17982           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17983             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17984         }
17985       }
17986     });
17987   }
17988 
17989   // C++14 [except.spec]p17:
17990   //   An exception-specification is considered to be needed when:
17991   //   - the function is odr-used or, if it appears in an unevaluated operand,
17992   //     would be odr-used if the expression were potentially-evaluated;
17993   //
17994   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17995   // function is a pure virtual function we're calling, and in that case the
17996   // function was selected by overload resolution and we need to resolve its
17997   // exception specification for a different reason.
17998   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17999   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18000     ResolveExceptionSpec(Loc, FPT);
18001 
18002   // If this is the first "real" use, act on that.
18003   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18004     // Keep track of used but undefined functions.
18005     if (!Func->isDefined()) {
18006       if (mightHaveNonExternalLinkage(Func))
18007         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18008       else if (Func->getMostRecentDecl()->isInlined() &&
18009                !LangOpts.GNUInline &&
18010                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18011         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18012       else if (isExternalWithNoLinkageType(Func))
18013         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18014     }
18015 
18016     // Some x86 Windows calling conventions mangle the size of the parameter
18017     // pack into the name. Computing the size of the parameters requires the
18018     // parameter types to be complete. Check that now.
18019     if (funcHasParameterSizeMangling(*this, Func))
18020       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18021 
18022     // In the MS C++ ABI, the compiler emits destructor variants where they are
18023     // used. If the destructor is used here but defined elsewhere, mark the
18024     // virtual base destructors referenced. If those virtual base destructors
18025     // are inline, this will ensure they are defined when emitting the complete
18026     // destructor variant. This checking may be redundant if the destructor is
18027     // provided later in this TU.
18028     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18029       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18030         CXXRecordDecl *Parent = Dtor->getParent();
18031         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18032           CheckCompleteDestructorVariant(Loc, Dtor);
18033       }
18034     }
18035 
18036     Func->markUsed(Context);
18037   }
18038 }
18039 
18040 /// Directly mark a variable odr-used. Given a choice, prefer to use
18041 /// MarkVariableReferenced since it does additional checks and then
18042 /// calls MarkVarDeclODRUsed.
18043 /// If the variable must be captured:
18044 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18045 ///  - else capture it in the DeclContext that maps to the
18046 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18047 static void
18048 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18049                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18050   // Keep track of used but undefined variables.
18051   // FIXME: We shouldn't suppress this warning for static data members.
18052   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18053       (!Var->isExternallyVisible() || Var->isInline() ||
18054        SemaRef.isExternalWithNoLinkageType(Var)) &&
18055       !(Var->isStaticDataMember() && Var->hasInit())) {
18056     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18057     if (old.isInvalid())
18058       old = Loc;
18059   }
18060   QualType CaptureType, DeclRefType;
18061   if (SemaRef.LangOpts.OpenMP)
18062     SemaRef.tryCaptureOpenMPLambdas(Var);
18063   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18064     /*EllipsisLoc*/ SourceLocation(),
18065     /*BuildAndDiagnose*/ true,
18066     CaptureType, DeclRefType,
18067     FunctionScopeIndexToStopAt);
18068 
18069   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18070     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18071     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18072     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18073     if (VarTarget == Sema::CVT_Host &&
18074         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18075          UserTarget == Sema::CFT_Global)) {
18076       // Diagnose ODR-use of host global variables in device functions.
18077       // Reference of device global variables in host functions is allowed
18078       // through shadow variables therefore it is not diagnosed.
18079       if (SemaRef.LangOpts.CUDAIsDevice) {
18080         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18081             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18082         SemaRef.targetDiag(Var->getLocation(),
18083                            Var->getType().isConstQualified()
18084                                ? diag::note_cuda_const_var_unpromoted
18085                                : diag::note_cuda_host_var);
18086       }
18087     } else if (VarTarget == Sema::CVT_Device &&
18088                (UserTarget == Sema::CFT_Host ||
18089                 UserTarget == Sema::CFT_HostDevice)) {
18090       // Record a CUDA/HIP device side variable if it is ODR-used
18091       // by host code. This is done conservatively, when the variable is
18092       // referenced in any of the following contexts:
18093       //   - a non-function context
18094       //   - a host function
18095       //   - a host device function
18096       // This makes the ODR-use of the device side variable by host code to
18097       // be visible in the device compilation for the compiler to be able to
18098       // emit template variables instantiated by host code only and to
18099       // externalize the static device side variable ODR-used by host code.
18100       if (!Var->hasExternalStorage())
18101         SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18102       else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18103         SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18104     }
18105   }
18106 
18107   Var->markUsed(SemaRef.Context);
18108 }
18109 
18110 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18111                                              SourceLocation Loc,
18112                                              unsigned CapturingScopeIndex) {
18113   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18114 }
18115 
18116 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18117                                                ValueDecl *var) {
18118   DeclContext *VarDC = var->getDeclContext();
18119 
18120   //  If the parameter still belongs to the translation unit, then
18121   //  we're actually just using one parameter in the declaration of
18122   //  the next.
18123   if (isa<ParmVarDecl>(var) &&
18124       isa<TranslationUnitDecl>(VarDC))
18125     return;
18126 
18127   // For C code, don't diagnose about capture if we're not actually in code
18128   // right now; it's impossible to write a non-constant expression outside of
18129   // function context, so we'll get other (more useful) diagnostics later.
18130   //
18131   // For C++, things get a bit more nasty... it would be nice to suppress this
18132   // diagnostic for certain cases like using a local variable in an array bound
18133   // for a member of a local class, but the correct predicate is not obvious.
18134   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18135     return;
18136 
18137   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18138   unsigned ContextKind = 3; // unknown
18139   if (isa<CXXMethodDecl>(VarDC) &&
18140       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18141     ContextKind = 2;
18142   } else if (isa<FunctionDecl>(VarDC)) {
18143     ContextKind = 0;
18144   } else if (isa<BlockDecl>(VarDC)) {
18145     ContextKind = 1;
18146   }
18147 
18148   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18149     << var << ValueKind << ContextKind << VarDC;
18150   S.Diag(var->getLocation(), diag::note_entity_declared_at)
18151       << var;
18152 
18153   // FIXME: Add additional diagnostic info about class etc. which prevents
18154   // capture.
18155 }
18156 
18157 
18158 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18159                                       bool &SubCapturesAreNested,
18160                                       QualType &CaptureType,
18161                                       QualType &DeclRefType) {
18162    // Check whether we've already captured it.
18163   if (CSI->CaptureMap.count(Var)) {
18164     // If we found a capture, any subcaptures are nested.
18165     SubCapturesAreNested = true;
18166 
18167     // Retrieve the capture type for this variable.
18168     CaptureType = CSI->getCapture(Var).getCaptureType();
18169 
18170     // Compute the type of an expression that refers to this variable.
18171     DeclRefType = CaptureType.getNonReferenceType();
18172 
18173     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18174     // are mutable in the sense that user can change their value - they are
18175     // private instances of the captured declarations.
18176     const Capture &Cap = CSI->getCapture(Var);
18177     if (Cap.isCopyCapture() &&
18178         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18179         !(isa<CapturedRegionScopeInfo>(CSI) &&
18180           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18181       DeclRefType.addConst();
18182     return true;
18183   }
18184   return false;
18185 }
18186 
18187 // Only block literals, captured statements, and lambda expressions can
18188 // capture; other scopes don't work.
18189 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18190                                  SourceLocation Loc,
18191                                  const bool Diagnose, Sema &S) {
18192   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18193     return getLambdaAwareParentOfDeclContext(DC);
18194   else if (Var->hasLocalStorage()) {
18195     if (Diagnose)
18196        diagnoseUncapturableValueReference(S, Loc, Var);
18197   }
18198   return nullptr;
18199 }
18200 
18201 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18202 // certain types of variables (unnamed, variably modified types etc.)
18203 // so check for eligibility.
18204 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18205                                  SourceLocation Loc,
18206                                  const bool Diagnose, Sema &S) {
18207 
18208   bool IsBlock = isa<BlockScopeInfo>(CSI);
18209   bool IsLambda = isa<LambdaScopeInfo>(CSI);
18210 
18211   // Lambdas are not allowed to capture unnamed variables
18212   // (e.g. anonymous unions).
18213   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18214   // assuming that's the intent.
18215   if (IsLambda && !Var->getDeclName()) {
18216     if (Diagnose) {
18217       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18218       S.Diag(Var->getLocation(), diag::note_declared_at);
18219     }
18220     return false;
18221   }
18222 
18223   // Prohibit variably-modified types in blocks; they're difficult to deal with.
18224   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18225     if (Diagnose) {
18226       S.Diag(Loc, diag::err_ref_vm_type);
18227       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18228     }
18229     return false;
18230   }
18231   // Prohibit structs with flexible array members too.
18232   // We cannot capture what is in the tail end of the struct.
18233   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18234     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18235       if (Diagnose) {
18236         if (IsBlock)
18237           S.Diag(Loc, diag::err_ref_flexarray_type);
18238         else
18239           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18240         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18241       }
18242       return false;
18243     }
18244   }
18245   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18246   // Lambdas and captured statements are not allowed to capture __block
18247   // variables; they don't support the expected semantics.
18248   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18249     if (Diagnose) {
18250       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18251       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18252     }
18253     return false;
18254   }
18255   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18256   if (S.getLangOpts().OpenCL && IsBlock &&
18257       Var->getType()->isBlockPointerType()) {
18258     if (Diagnose)
18259       S.Diag(Loc, diag::err_opencl_block_ref_block);
18260     return false;
18261   }
18262 
18263   return true;
18264 }
18265 
18266 // Returns true if the capture by block was successful.
18267 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18268                                  SourceLocation Loc,
18269                                  const bool BuildAndDiagnose,
18270                                  QualType &CaptureType,
18271                                  QualType &DeclRefType,
18272                                  const bool Nested,
18273                                  Sema &S, bool Invalid) {
18274   bool ByRef = false;
18275 
18276   // Blocks are not allowed to capture arrays, excepting OpenCL.
18277   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18278   // (decayed to pointers).
18279   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18280     if (BuildAndDiagnose) {
18281       S.Diag(Loc, diag::err_ref_array_type);
18282       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18283       Invalid = true;
18284     } else {
18285       return false;
18286     }
18287   }
18288 
18289   // Forbid the block-capture of autoreleasing variables.
18290   if (!Invalid &&
18291       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18292     if (BuildAndDiagnose) {
18293       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18294         << /*block*/ 0;
18295       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18296       Invalid = true;
18297     } else {
18298       return false;
18299     }
18300   }
18301 
18302   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18303   if (const auto *PT = CaptureType->getAs<PointerType>()) {
18304     QualType PointeeTy = PT->getPointeeType();
18305 
18306     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18307         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18308         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18309       if (BuildAndDiagnose) {
18310         SourceLocation VarLoc = Var->getLocation();
18311         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18312         S.Diag(VarLoc, diag::note_declare_parameter_strong);
18313       }
18314     }
18315   }
18316 
18317   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18318   if (HasBlocksAttr || CaptureType->isReferenceType() ||
18319       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18320     // Block capture by reference does not change the capture or
18321     // declaration reference types.
18322     ByRef = true;
18323   } else {
18324     // Block capture by copy introduces 'const'.
18325     CaptureType = CaptureType.getNonReferenceType().withConst();
18326     DeclRefType = CaptureType;
18327   }
18328 
18329   // Actually capture the variable.
18330   if (BuildAndDiagnose)
18331     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18332                     CaptureType, Invalid);
18333 
18334   return !Invalid;
18335 }
18336 
18337 
18338 /// Capture the given variable in the captured region.
18339 static bool captureInCapturedRegion(
18340     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18341     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18342     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18343     bool IsTopScope, Sema &S, bool Invalid) {
18344   // By default, capture variables by reference.
18345   bool ByRef = true;
18346   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18347     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18348   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18349     // Using an LValue reference type is consistent with Lambdas (see below).
18350     if (S.isOpenMPCapturedDecl(Var)) {
18351       bool HasConst = DeclRefType.isConstQualified();
18352       DeclRefType = DeclRefType.getUnqualifiedType();
18353       // Don't lose diagnostics about assignments to const.
18354       if (HasConst)
18355         DeclRefType.addConst();
18356     }
18357     // Do not capture firstprivates in tasks.
18358     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18359         OMPC_unknown)
18360       return true;
18361     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18362                                     RSI->OpenMPCaptureLevel);
18363   }
18364 
18365   if (ByRef)
18366     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18367   else
18368     CaptureType = DeclRefType;
18369 
18370   // Actually capture the variable.
18371   if (BuildAndDiagnose)
18372     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18373                     Loc, SourceLocation(), CaptureType, Invalid);
18374 
18375   return !Invalid;
18376 }
18377 
18378 /// Capture the given variable in the lambda.
18379 static bool captureInLambda(LambdaScopeInfo *LSI,
18380                             VarDecl *Var,
18381                             SourceLocation Loc,
18382                             const bool BuildAndDiagnose,
18383                             QualType &CaptureType,
18384                             QualType &DeclRefType,
18385                             const bool RefersToCapturedVariable,
18386                             const Sema::TryCaptureKind Kind,
18387                             SourceLocation EllipsisLoc,
18388                             const bool IsTopScope,
18389                             Sema &S, bool Invalid) {
18390   // Determine whether we are capturing by reference or by value.
18391   bool ByRef = false;
18392   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18393     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18394   } else {
18395     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18396   }
18397 
18398   // Compute the type of the field that will capture this variable.
18399   if (ByRef) {
18400     // C++11 [expr.prim.lambda]p15:
18401     //   An entity is captured by reference if it is implicitly or
18402     //   explicitly captured but not captured by copy. It is
18403     //   unspecified whether additional unnamed non-static data
18404     //   members are declared in the closure type for entities
18405     //   captured by reference.
18406     //
18407     // FIXME: It is not clear whether we want to build an lvalue reference
18408     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18409     // to do the former, while EDG does the latter. Core issue 1249 will
18410     // clarify, but for now we follow GCC because it's a more permissive and
18411     // easily defensible position.
18412     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18413   } else {
18414     // C++11 [expr.prim.lambda]p14:
18415     //   For each entity captured by copy, an unnamed non-static
18416     //   data member is declared in the closure type. The
18417     //   declaration order of these members is unspecified. The type
18418     //   of such a data member is the type of the corresponding
18419     //   captured entity if the entity is not a reference to an
18420     //   object, or the referenced type otherwise. [Note: If the
18421     //   captured entity is a reference to a function, the
18422     //   corresponding data member is also a reference to a
18423     //   function. - end note ]
18424     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18425       if (!RefType->getPointeeType()->isFunctionType())
18426         CaptureType = RefType->getPointeeType();
18427     }
18428 
18429     // Forbid the lambda copy-capture of autoreleasing variables.
18430     if (!Invalid &&
18431         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18432       if (BuildAndDiagnose) {
18433         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18434         S.Diag(Var->getLocation(), diag::note_previous_decl)
18435           << Var->getDeclName();
18436         Invalid = true;
18437       } else {
18438         return false;
18439       }
18440     }
18441 
18442     // Make sure that by-copy captures are of a complete and non-abstract type.
18443     if (!Invalid && BuildAndDiagnose) {
18444       if (!CaptureType->isDependentType() &&
18445           S.RequireCompleteSizedType(
18446               Loc, CaptureType,
18447               diag::err_capture_of_incomplete_or_sizeless_type,
18448               Var->getDeclName()))
18449         Invalid = true;
18450       else if (S.RequireNonAbstractType(Loc, CaptureType,
18451                                         diag::err_capture_of_abstract_type))
18452         Invalid = true;
18453     }
18454   }
18455 
18456   // Compute the type of a reference to this captured variable.
18457   if (ByRef)
18458     DeclRefType = CaptureType.getNonReferenceType();
18459   else {
18460     // C++ [expr.prim.lambda]p5:
18461     //   The closure type for a lambda-expression has a public inline
18462     //   function call operator [...]. This function call operator is
18463     //   declared const (9.3.1) if and only if the lambda-expression's
18464     //   parameter-declaration-clause is not followed by mutable.
18465     DeclRefType = CaptureType.getNonReferenceType();
18466     if (!LSI->Mutable && !CaptureType->isReferenceType())
18467       DeclRefType.addConst();
18468   }
18469 
18470   // Add the capture.
18471   if (BuildAndDiagnose)
18472     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18473                     Loc, EllipsisLoc, CaptureType, Invalid);
18474 
18475   return !Invalid;
18476 }
18477 
18478 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18479   // Offer a Copy fix even if the type is dependent.
18480   if (Var->getType()->isDependentType())
18481     return true;
18482   QualType T = Var->getType().getNonReferenceType();
18483   if (T.isTriviallyCopyableType(Context))
18484     return true;
18485   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18486 
18487     if (!(RD = RD->getDefinition()))
18488       return false;
18489     if (RD->hasSimpleCopyConstructor())
18490       return true;
18491     if (RD->hasUserDeclaredCopyConstructor())
18492       for (CXXConstructorDecl *Ctor : RD->ctors())
18493         if (Ctor->isCopyConstructor())
18494           return !Ctor->isDeleted();
18495   }
18496   return false;
18497 }
18498 
18499 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18500 /// default capture. Fixes may be omitted if they aren't allowed by the
18501 /// standard, for example we can't emit a default copy capture fix-it if we
18502 /// already explicitly copy capture capture another variable.
18503 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18504                                     VarDecl *Var) {
18505   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18506   // Don't offer Capture by copy of default capture by copy fixes if Var is
18507   // known not to be copy constructible.
18508   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18509 
18510   SmallString<32> FixBuffer;
18511   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18512   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18513     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18514     if (ShouldOfferCopyFix) {
18515       // Offer fixes to insert an explicit capture for the variable.
18516       // [] -> [VarName]
18517       // [OtherCapture] -> [OtherCapture, VarName]
18518       FixBuffer.assign({Separator, Var->getName()});
18519       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18520           << Var << /*value*/ 0
18521           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18522     }
18523     // As above but capture by reference.
18524     FixBuffer.assign({Separator, "&", Var->getName()});
18525     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18526         << Var << /*reference*/ 1
18527         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18528   }
18529 
18530   // Only try to offer default capture if there are no captures excluding this
18531   // and init captures.
18532   // [this]: OK.
18533   // [X = Y]: OK.
18534   // [&A, &B]: Don't offer.
18535   // [A, B]: Don't offer.
18536   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18537         return !C.isThisCapture() && !C.isInitCapture();
18538       }))
18539     return;
18540 
18541   // The default capture specifiers, '=' or '&', must appear first in the
18542   // capture body.
18543   SourceLocation DefaultInsertLoc =
18544       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18545 
18546   if (ShouldOfferCopyFix) {
18547     bool CanDefaultCopyCapture = true;
18548     // [=, *this] OK since c++17
18549     // [=, this] OK since c++20
18550     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18551       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18552                                   ? LSI->getCXXThisCapture().isCopyCapture()
18553                                   : false;
18554     // We can't use default capture by copy if any captures already specified
18555     // capture by copy.
18556     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18557           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18558         })) {
18559       FixBuffer.assign({"=", Separator});
18560       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18561           << /*value*/ 0
18562           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18563     }
18564   }
18565 
18566   // We can't use default capture by reference if any captures already specified
18567   // capture by reference.
18568   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18569         return !C.isInitCapture() && C.isReferenceCapture() &&
18570                !C.isThisCapture();
18571       })) {
18572     FixBuffer.assign({"&", Separator});
18573     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18574         << /*reference*/ 1
18575         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18576   }
18577 }
18578 
18579 bool Sema::tryCaptureVariable(
18580     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18581     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18582     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18583   // An init-capture is notionally from the context surrounding its
18584   // declaration, but its parent DC is the lambda class.
18585   DeclContext *VarDC = Var->getDeclContext();
18586   if (Var->isInitCapture())
18587     VarDC = VarDC->getParent();
18588 
18589   DeclContext *DC = CurContext;
18590   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18591       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18592   // We need to sync up the Declaration Context with the
18593   // FunctionScopeIndexToStopAt
18594   if (FunctionScopeIndexToStopAt) {
18595     unsigned FSIndex = FunctionScopes.size() - 1;
18596     while (FSIndex != MaxFunctionScopesIndex) {
18597       DC = getLambdaAwareParentOfDeclContext(DC);
18598       --FSIndex;
18599     }
18600   }
18601 
18602 
18603   // If the variable is declared in the current context, there is no need to
18604   // capture it.
18605   if (VarDC == DC) return true;
18606 
18607   // Capture global variables if it is required to use private copy of this
18608   // variable.
18609   bool IsGlobal = !Var->hasLocalStorage();
18610   if (IsGlobal &&
18611       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18612                                                 MaxFunctionScopesIndex)))
18613     return true;
18614   Var = Var->getCanonicalDecl();
18615 
18616   // Walk up the stack to determine whether we can capture the variable,
18617   // performing the "simple" checks that don't depend on type. We stop when
18618   // we've either hit the declared scope of the variable or find an existing
18619   // capture of that variable.  We start from the innermost capturing-entity
18620   // (the DC) and ensure that all intervening capturing-entities
18621   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18622   // declcontext can either capture the variable or have already captured
18623   // the variable.
18624   CaptureType = Var->getType();
18625   DeclRefType = CaptureType.getNonReferenceType();
18626   bool Nested = false;
18627   bool Explicit = (Kind != TryCapture_Implicit);
18628   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18629   do {
18630     // Only block literals, captured statements, and lambda expressions can
18631     // capture; other scopes don't work.
18632     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18633                                                               ExprLoc,
18634                                                               BuildAndDiagnose,
18635                                                               *this);
18636     // We need to check for the parent *first* because, if we *have*
18637     // private-captured a global variable, we need to recursively capture it in
18638     // intermediate blocks, lambdas, etc.
18639     if (!ParentDC) {
18640       if (IsGlobal) {
18641         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18642         break;
18643       }
18644       return true;
18645     }
18646 
18647     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18648     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18649 
18650 
18651     // Check whether we've already captured it.
18652     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18653                                              DeclRefType)) {
18654       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18655       break;
18656     }
18657     // If we are instantiating a generic lambda call operator body,
18658     // we do not want to capture new variables.  What was captured
18659     // during either a lambdas transformation or initial parsing
18660     // should be used.
18661     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18662       if (BuildAndDiagnose) {
18663         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18664         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18665           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18666           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18667           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18668           buildLambdaCaptureFixit(*this, LSI, Var);
18669         } else
18670           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18671       }
18672       return true;
18673     }
18674 
18675     // Try to capture variable-length arrays types.
18676     if (Var->getType()->isVariablyModifiedType()) {
18677       // We're going to walk down into the type and look for VLA
18678       // expressions.
18679       QualType QTy = Var->getType();
18680       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18681         QTy = PVD->getOriginalType();
18682       captureVariablyModifiedType(Context, QTy, CSI);
18683     }
18684 
18685     if (getLangOpts().OpenMP) {
18686       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18687         // OpenMP private variables should not be captured in outer scope, so
18688         // just break here. Similarly, global variables that are captured in a
18689         // target region should not be captured outside the scope of the region.
18690         if (RSI->CapRegionKind == CR_OpenMP) {
18691           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18692               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18693           // If the variable is private (i.e. not captured) and has variably
18694           // modified type, we still need to capture the type for correct
18695           // codegen in all regions, associated with the construct. Currently,
18696           // it is captured in the innermost captured region only.
18697           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18698               Var->getType()->isVariablyModifiedType()) {
18699             QualType QTy = Var->getType();
18700             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18701               QTy = PVD->getOriginalType();
18702             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18703                  I < E; ++I) {
18704               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18705                   FunctionScopes[FunctionScopesIndex - I]);
18706               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18707                      "Wrong number of captured regions associated with the "
18708                      "OpenMP construct.");
18709               captureVariablyModifiedType(Context, QTy, OuterRSI);
18710             }
18711           }
18712           bool IsTargetCap =
18713               IsOpenMPPrivateDecl != OMPC_private &&
18714               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18715                                          RSI->OpenMPCaptureLevel);
18716           // Do not capture global if it is not privatized in outer regions.
18717           bool IsGlobalCap =
18718               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18719                                                      RSI->OpenMPCaptureLevel);
18720 
18721           // When we detect target captures we are looking from inside the
18722           // target region, therefore we need to propagate the capture from the
18723           // enclosing region. Therefore, the capture is not initially nested.
18724           if (IsTargetCap)
18725             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18726 
18727           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18728               (IsGlobal && !IsGlobalCap)) {
18729             Nested = !IsTargetCap;
18730             bool HasConst = DeclRefType.isConstQualified();
18731             DeclRefType = DeclRefType.getUnqualifiedType();
18732             // Don't lose diagnostics about assignments to const.
18733             if (HasConst)
18734               DeclRefType.addConst();
18735             CaptureType = Context.getLValueReferenceType(DeclRefType);
18736             break;
18737           }
18738         }
18739       }
18740     }
18741     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18742       // No capture-default, and this is not an explicit capture
18743       // so cannot capture this variable.
18744       if (BuildAndDiagnose) {
18745         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18746         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18747         auto *LSI = cast<LambdaScopeInfo>(CSI);
18748         if (LSI->Lambda) {
18749           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18750           buildLambdaCaptureFixit(*this, LSI, Var);
18751         }
18752         // FIXME: If we error out because an outer lambda can not implicitly
18753         // capture a variable that an inner lambda explicitly captures, we
18754         // should have the inner lambda do the explicit capture - because
18755         // it makes for cleaner diagnostics later.  This would purely be done
18756         // so that the diagnostic does not misleadingly claim that a variable
18757         // can not be captured by a lambda implicitly even though it is captured
18758         // explicitly.  Suggestion:
18759         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18760         //    at the function head
18761         //  - cache the StartingDeclContext - this must be a lambda
18762         //  - captureInLambda in the innermost lambda the variable.
18763       }
18764       return true;
18765     }
18766 
18767     FunctionScopesIndex--;
18768     DC = ParentDC;
18769     Explicit = false;
18770   } while (!VarDC->Equals(DC));
18771 
18772   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18773   // computing the type of the capture at each step, checking type-specific
18774   // requirements, and adding captures if requested.
18775   // If the variable had already been captured previously, we start capturing
18776   // at the lambda nested within that one.
18777   bool Invalid = false;
18778   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18779        ++I) {
18780     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18781 
18782     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18783     // certain types of variables (unnamed, variably modified types etc.)
18784     // so check for eligibility.
18785     if (!Invalid)
18786       Invalid =
18787           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18788 
18789     // After encountering an error, if we're actually supposed to capture, keep
18790     // capturing in nested contexts to suppress any follow-on diagnostics.
18791     if (Invalid && !BuildAndDiagnose)
18792       return true;
18793 
18794     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18795       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18796                                DeclRefType, Nested, *this, Invalid);
18797       Nested = true;
18798     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18799       Invalid = !captureInCapturedRegion(
18800           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18801           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18802       Nested = true;
18803     } else {
18804       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18805       Invalid =
18806           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18807                            DeclRefType, Nested, Kind, EllipsisLoc,
18808                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18809       Nested = true;
18810     }
18811 
18812     if (Invalid && !BuildAndDiagnose)
18813       return true;
18814   }
18815   return Invalid;
18816 }
18817 
18818 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18819                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18820   QualType CaptureType;
18821   QualType DeclRefType;
18822   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18823                             /*BuildAndDiagnose=*/true, CaptureType,
18824                             DeclRefType, nullptr);
18825 }
18826 
18827 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18828   QualType CaptureType;
18829   QualType DeclRefType;
18830   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18831                              /*BuildAndDiagnose=*/false, CaptureType,
18832                              DeclRefType, nullptr);
18833 }
18834 
18835 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18836   QualType CaptureType;
18837   QualType DeclRefType;
18838 
18839   // Determine whether we can capture this variable.
18840   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18841                          /*BuildAndDiagnose=*/false, CaptureType,
18842                          DeclRefType, nullptr))
18843     return QualType();
18844 
18845   return DeclRefType;
18846 }
18847 
18848 namespace {
18849 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18850 // The produced TemplateArgumentListInfo* points to data stored within this
18851 // object, so should only be used in contexts where the pointer will not be
18852 // used after the CopiedTemplateArgs object is destroyed.
18853 class CopiedTemplateArgs {
18854   bool HasArgs;
18855   TemplateArgumentListInfo TemplateArgStorage;
18856 public:
18857   template<typename RefExpr>
18858   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18859     if (HasArgs)
18860       E->copyTemplateArgumentsInto(TemplateArgStorage);
18861   }
18862   operator TemplateArgumentListInfo*()
18863 #ifdef __has_cpp_attribute
18864 #if __has_cpp_attribute(clang::lifetimebound)
18865   [[clang::lifetimebound]]
18866 #endif
18867 #endif
18868   {
18869     return HasArgs ? &TemplateArgStorage : nullptr;
18870   }
18871 };
18872 }
18873 
18874 /// Walk the set of potential results of an expression and mark them all as
18875 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18876 ///
18877 /// \return A new expression if we found any potential results, ExprEmpty() if
18878 ///         not, and ExprError() if we diagnosed an error.
18879 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18880                                                       NonOdrUseReason NOUR) {
18881   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18882   // an object that satisfies the requirements for appearing in a
18883   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18884   // is immediately applied."  This function handles the lvalue-to-rvalue
18885   // conversion part.
18886   //
18887   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18888   // transform it into the relevant kind of non-odr-use node and rebuild the
18889   // tree of nodes leading to it.
18890   //
18891   // This is a mini-TreeTransform that only transforms a restricted subset of
18892   // nodes (and only certain operands of them).
18893 
18894   // Rebuild a subexpression.
18895   auto Rebuild = [&](Expr *Sub) {
18896     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18897   };
18898 
18899   // Check whether a potential result satisfies the requirements of NOUR.
18900   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18901     // Any entity other than a VarDecl is always odr-used whenever it's named
18902     // in a potentially-evaluated expression.
18903     auto *VD = dyn_cast<VarDecl>(D);
18904     if (!VD)
18905       return true;
18906 
18907     // C++2a [basic.def.odr]p4:
18908     //   A variable x whose name appears as a potentially-evalauted expression
18909     //   e is odr-used by e unless
18910     //   -- x is a reference that is usable in constant expressions, or
18911     //   -- x is a variable of non-reference type that is usable in constant
18912     //      expressions and has no mutable subobjects, and e is an element of
18913     //      the set of potential results of an expression of
18914     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18915     //      conversion is applied, or
18916     //   -- x is a variable of non-reference type, and e is an element of the
18917     //      set of potential results of a discarded-value expression to which
18918     //      the lvalue-to-rvalue conversion is not applied
18919     //
18920     // We check the first bullet and the "potentially-evaluated" condition in
18921     // BuildDeclRefExpr. We check the type requirements in the second bullet
18922     // in CheckLValueToRValueConversionOperand below.
18923     switch (NOUR) {
18924     case NOUR_None:
18925     case NOUR_Unevaluated:
18926       llvm_unreachable("unexpected non-odr-use-reason");
18927 
18928     case NOUR_Constant:
18929       // Constant references were handled when they were built.
18930       if (VD->getType()->isReferenceType())
18931         return true;
18932       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18933         if (RD->hasMutableFields())
18934           return true;
18935       if (!VD->isUsableInConstantExpressions(S.Context))
18936         return true;
18937       break;
18938 
18939     case NOUR_Discarded:
18940       if (VD->getType()->isReferenceType())
18941         return true;
18942       break;
18943     }
18944     return false;
18945   };
18946 
18947   // Mark that this expression does not constitute an odr-use.
18948   auto MarkNotOdrUsed = [&] {
18949     S.MaybeODRUseExprs.remove(E);
18950     if (LambdaScopeInfo *LSI = S.getCurLambda())
18951       LSI->markVariableExprAsNonODRUsed(E);
18952   };
18953 
18954   // C++2a [basic.def.odr]p2:
18955   //   The set of potential results of an expression e is defined as follows:
18956   switch (E->getStmtClass()) {
18957   //   -- If e is an id-expression, ...
18958   case Expr::DeclRefExprClass: {
18959     auto *DRE = cast<DeclRefExpr>(E);
18960     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18961       break;
18962 
18963     // Rebuild as a non-odr-use DeclRefExpr.
18964     MarkNotOdrUsed();
18965     return DeclRefExpr::Create(
18966         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18967         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18968         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18969         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18970   }
18971 
18972   case Expr::FunctionParmPackExprClass: {
18973     auto *FPPE = cast<FunctionParmPackExpr>(E);
18974     // If any of the declarations in the pack is odr-used, then the expression
18975     // as a whole constitutes an odr-use.
18976     for (VarDecl *D : *FPPE)
18977       if (IsPotentialResultOdrUsed(D))
18978         return ExprEmpty();
18979 
18980     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18981     // nothing cares about whether we marked this as an odr-use, but it might
18982     // be useful for non-compiler tools.
18983     MarkNotOdrUsed();
18984     break;
18985   }
18986 
18987   //   -- If e is a subscripting operation with an array operand...
18988   case Expr::ArraySubscriptExprClass: {
18989     auto *ASE = cast<ArraySubscriptExpr>(E);
18990     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18991     if (!OldBase->getType()->isArrayType())
18992       break;
18993     ExprResult Base = Rebuild(OldBase);
18994     if (!Base.isUsable())
18995       return Base;
18996     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18997     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18998     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18999     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19000                                      ASE->getRBracketLoc());
19001   }
19002 
19003   case Expr::MemberExprClass: {
19004     auto *ME = cast<MemberExpr>(E);
19005     // -- If e is a class member access expression [...] naming a non-static
19006     //    data member...
19007     if (isa<FieldDecl>(ME->getMemberDecl())) {
19008       ExprResult Base = Rebuild(ME->getBase());
19009       if (!Base.isUsable())
19010         return Base;
19011       return MemberExpr::Create(
19012           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19013           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19014           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19015           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19016           ME->getObjectKind(), ME->isNonOdrUse());
19017     }
19018 
19019     if (ME->getMemberDecl()->isCXXInstanceMember())
19020       break;
19021 
19022     // -- If e is a class member access expression naming a static data member,
19023     //    ...
19024     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19025       break;
19026 
19027     // Rebuild as a non-odr-use MemberExpr.
19028     MarkNotOdrUsed();
19029     return MemberExpr::Create(
19030         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19031         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19032         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19033         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19034   }
19035 
19036   case Expr::BinaryOperatorClass: {
19037     auto *BO = cast<BinaryOperator>(E);
19038     Expr *LHS = BO->getLHS();
19039     Expr *RHS = BO->getRHS();
19040     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19041     if (BO->getOpcode() == BO_PtrMemD) {
19042       ExprResult Sub = Rebuild(LHS);
19043       if (!Sub.isUsable())
19044         return Sub;
19045       LHS = Sub.get();
19046     //   -- If e is a comma expression, ...
19047     } else if (BO->getOpcode() == BO_Comma) {
19048       ExprResult Sub = Rebuild(RHS);
19049       if (!Sub.isUsable())
19050         return Sub;
19051       RHS = Sub.get();
19052     } else {
19053       break;
19054     }
19055     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19056                         LHS, RHS);
19057   }
19058 
19059   //   -- If e has the form (e1)...
19060   case Expr::ParenExprClass: {
19061     auto *PE = cast<ParenExpr>(E);
19062     ExprResult Sub = Rebuild(PE->getSubExpr());
19063     if (!Sub.isUsable())
19064       return Sub;
19065     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19066   }
19067 
19068   //   -- If e is a glvalue conditional expression, ...
19069   // We don't apply this to a binary conditional operator. FIXME: Should we?
19070   case Expr::ConditionalOperatorClass: {
19071     auto *CO = cast<ConditionalOperator>(E);
19072     ExprResult LHS = Rebuild(CO->getLHS());
19073     if (LHS.isInvalid())
19074       return ExprError();
19075     ExprResult RHS = Rebuild(CO->getRHS());
19076     if (RHS.isInvalid())
19077       return ExprError();
19078     if (!LHS.isUsable() && !RHS.isUsable())
19079       return ExprEmpty();
19080     if (!LHS.isUsable())
19081       LHS = CO->getLHS();
19082     if (!RHS.isUsable())
19083       RHS = CO->getRHS();
19084     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19085                                 CO->getCond(), LHS.get(), RHS.get());
19086   }
19087 
19088   // [Clang extension]
19089   //   -- If e has the form __extension__ e1...
19090   case Expr::UnaryOperatorClass: {
19091     auto *UO = cast<UnaryOperator>(E);
19092     if (UO->getOpcode() != UO_Extension)
19093       break;
19094     ExprResult Sub = Rebuild(UO->getSubExpr());
19095     if (!Sub.isUsable())
19096       return Sub;
19097     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19098                           Sub.get());
19099   }
19100 
19101   // [Clang extension]
19102   //   -- If e has the form _Generic(...), the set of potential results is the
19103   //      union of the sets of potential results of the associated expressions.
19104   case Expr::GenericSelectionExprClass: {
19105     auto *GSE = cast<GenericSelectionExpr>(E);
19106 
19107     SmallVector<Expr *, 4> AssocExprs;
19108     bool AnyChanged = false;
19109     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19110       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19111       if (AssocExpr.isInvalid())
19112         return ExprError();
19113       if (AssocExpr.isUsable()) {
19114         AssocExprs.push_back(AssocExpr.get());
19115         AnyChanged = true;
19116       } else {
19117         AssocExprs.push_back(OrigAssocExpr);
19118       }
19119     }
19120 
19121     return AnyChanged ? S.CreateGenericSelectionExpr(
19122                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
19123                             GSE->getRParenLoc(), GSE->getControllingExpr(),
19124                             GSE->getAssocTypeSourceInfos(), AssocExprs)
19125                       : ExprEmpty();
19126   }
19127 
19128   // [Clang extension]
19129   //   -- If e has the form __builtin_choose_expr(...), the set of potential
19130   //      results is the union of the sets of potential results of the
19131   //      second and third subexpressions.
19132   case Expr::ChooseExprClass: {
19133     auto *CE = cast<ChooseExpr>(E);
19134 
19135     ExprResult LHS = Rebuild(CE->getLHS());
19136     if (LHS.isInvalid())
19137       return ExprError();
19138 
19139     ExprResult RHS = Rebuild(CE->getLHS());
19140     if (RHS.isInvalid())
19141       return ExprError();
19142 
19143     if (!LHS.get() && !RHS.get())
19144       return ExprEmpty();
19145     if (!LHS.isUsable())
19146       LHS = CE->getLHS();
19147     if (!RHS.isUsable())
19148       RHS = CE->getRHS();
19149 
19150     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19151                              RHS.get(), CE->getRParenLoc());
19152   }
19153 
19154   // Step through non-syntactic nodes.
19155   case Expr::ConstantExprClass: {
19156     auto *CE = cast<ConstantExpr>(E);
19157     ExprResult Sub = Rebuild(CE->getSubExpr());
19158     if (!Sub.isUsable())
19159       return Sub;
19160     return ConstantExpr::Create(S.Context, Sub.get());
19161   }
19162 
19163   // We could mostly rely on the recursive rebuilding to rebuild implicit
19164   // casts, but not at the top level, so rebuild them here.
19165   case Expr::ImplicitCastExprClass: {
19166     auto *ICE = cast<ImplicitCastExpr>(E);
19167     // Only step through the narrow set of cast kinds we expect to encounter.
19168     // Anything else suggests we've left the region in which potential results
19169     // can be found.
19170     switch (ICE->getCastKind()) {
19171     case CK_NoOp:
19172     case CK_DerivedToBase:
19173     case CK_UncheckedDerivedToBase: {
19174       ExprResult Sub = Rebuild(ICE->getSubExpr());
19175       if (!Sub.isUsable())
19176         return Sub;
19177       CXXCastPath Path(ICE->path());
19178       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19179                                  ICE->getValueKind(), &Path);
19180     }
19181 
19182     default:
19183       break;
19184     }
19185     break;
19186   }
19187 
19188   default:
19189     break;
19190   }
19191 
19192   // Can't traverse through this node. Nothing to do.
19193   return ExprEmpty();
19194 }
19195 
19196 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19197   // Check whether the operand is or contains an object of non-trivial C union
19198   // type.
19199   if (E->getType().isVolatileQualified() &&
19200       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19201        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19202     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19203                           Sema::NTCUC_LValueToRValueVolatile,
19204                           NTCUK_Destruct|NTCUK_Copy);
19205 
19206   // C++2a [basic.def.odr]p4:
19207   //   [...] an expression of non-volatile-qualified non-class type to which
19208   //   the lvalue-to-rvalue conversion is applied [...]
19209   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19210     return E;
19211 
19212   ExprResult Result =
19213       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19214   if (Result.isInvalid())
19215     return ExprError();
19216   return Result.get() ? Result : E;
19217 }
19218 
19219 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19220   Res = CorrectDelayedTyposInExpr(Res);
19221 
19222   if (!Res.isUsable())
19223     return Res;
19224 
19225   // If a constant-expression is a reference to a variable where we delay
19226   // deciding whether it is an odr-use, just assume we will apply the
19227   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
19228   // (a non-type template argument), we have special handling anyway.
19229   return CheckLValueToRValueConversionOperand(Res.get());
19230 }
19231 
19232 void Sema::CleanupVarDeclMarking() {
19233   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19234   // call.
19235   MaybeODRUseExprSet LocalMaybeODRUseExprs;
19236   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19237 
19238   for (Expr *E : LocalMaybeODRUseExprs) {
19239     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19240       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19241                          DRE->getLocation(), *this);
19242     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19243       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19244                          *this);
19245     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19246       for (VarDecl *VD : *FP)
19247         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19248     } else {
19249       llvm_unreachable("Unexpected expression");
19250     }
19251   }
19252 
19253   assert(MaybeODRUseExprs.empty() &&
19254          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19255 }
19256 
19257 static void DoMarkVarDeclReferenced(
19258     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19259     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19260   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19261           isa<FunctionParmPackExpr>(E)) &&
19262          "Invalid Expr argument to DoMarkVarDeclReferenced");
19263   Var->setReferenced();
19264 
19265   if (Var->isInvalidDecl())
19266     return;
19267 
19268   auto *MSI = Var->getMemberSpecializationInfo();
19269   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19270                                        : Var->getTemplateSpecializationKind();
19271 
19272   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19273   bool UsableInConstantExpr =
19274       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19275 
19276   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19277     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19278   }
19279 
19280   // C++20 [expr.const]p12:
19281   //   A variable [...] is needed for constant evaluation if it is [...] a
19282   //   variable whose name appears as a potentially constant evaluated
19283   //   expression that is either a contexpr variable or is of non-volatile
19284   //   const-qualified integral type or of reference type
19285   bool NeededForConstantEvaluation =
19286       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19287 
19288   bool NeedDefinition =
19289       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19290 
19291   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19292          "Can't instantiate a partial template specialization.");
19293 
19294   // If this might be a member specialization of a static data member, check
19295   // the specialization is visible. We already did the checks for variable
19296   // template specializations when we created them.
19297   if (NeedDefinition && TSK != TSK_Undeclared &&
19298       !isa<VarTemplateSpecializationDecl>(Var))
19299     SemaRef.checkSpecializationVisibility(Loc, Var);
19300 
19301   // Perform implicit instantiation of static data members, static data member
19302   // templates of class templates, and variable template specializations. Delay
19303   // instantiations of variable templates, except for those that could be used
19304   // in a constant expression.
19305   if (NeedDefinition && isTemplateInstantiation(TSK)) {
19306     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19307     // instantiation declaration if a variable is usable in a constant
19308     // expression (among other cases).
19309     bool TryInstantiating =
19310         TSK == TSK_ImplicitInstantiation ||
19311         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19312 
19313     if (TryInstantiating) {
19314       SourceLocation PointOfInstantiation =
19315           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19316       bool FirstInstantiation = PointOfInstantiation.isInvalid();
19317       if (FirstInstantiation) {
19318         PointOfInstantiation = Loc;
19319         if (MSI)
19320           MSI->setPointOfInstantiation(PointOfInstantiation);
19321           // FIXME: Notify listener.
19322         else
19323           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19324       }
19325 
19326       if (UsableInConstantExpr) {
19327         // Do not defer instantiations of variables that could be used in a
19328         // constant expression.
19329         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19330           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19331         });
19332 
19333         // Re-set the member to trigger a recomputation of the dependence bits
19334         // for the expression.
19335         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19336           DRE->setDecl(DRE->getDecl());
19337         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19338           ME->setMemberDecl(ME->getMemberDecl());
19339       } else if (FirstInstantiation ||
19340                  isa<VarTemplateSpecializationDecl>(Var)) {
19341         // FIXME: For a specialization of a variable template, we don't
19342         // distinguish between "declaration and type implicitly instantiated"
19343         // and "implicit instantiation of definition requested", so we have
19344         // no direct way to avoid enqueueing the pending instantiation
19345         // multiple times.
19346         SemaRef.PendingInstantiations
19347             .push_back(std::make_pair(Var, PointOfInstantiation));
19348       }
19349     }
19350   }
19351 
19352   // C++2a [basic.def.odr]p4:
19353   //   A variable x whose name appears as a potentially-evaluated expression e
19354   //   is odr-used by e unless
19355   //   -- x is a reference that is usable in constant expressions
19356   //   -- x is a variable of non-reference type that is usable in constant
19357   //      expressions and has no mutable subobjects [FIXME], and e is an
19358   //      element of the set of potential results of an expression of
19359   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19360   //      conversion is applied
19361   //   -- x is a variable of non-reference type, and e is an element of the set
19362   //      of potential results of a discarded-value expression to which the
19363   //      lvalue-to-rvalue conversion is not applied [FIXME]
19364   //
19365   // We check the first part of the second bullet here, and
19366   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19367   // FIXME: To get the third bullet right, we need to delay this even for
19368   // variables that are not usable in constant expressions.
19369 
19370   // If we already know this isn't an odr-use, there's nothing more to do.
19371   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19372     if (DRE->isNonOdrUse())
19373       return;
19374   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19375     if (ME->isNonOdrUse())
19376       return;
19377 
19378   switch (OdrUse) {
19379   case OdrUseContext::None:
19380     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19381            "missing non-odr-use marking for unevaluated decl ref");
19382     break;
19383 
19384   case OdrUseContext::FormallyOdrUsed:
19385     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19386     // behavior.
19387     break;
19388 
19389   case OdrUseContext::Used:
19390     // If we might later find that this expression isn't actually an odr-use,
19391     // delay the marking.
19392     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19393       SemaRef.MaybeODRUseExprs.insert(E);
19394     else
19395       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19396     break;
19397 
19398   case OdrUseContext::Dependent:
19399     // If this is a dependent context, we don't need to mark variables as
19400     // odr-used, but we may still need to track them for lambda capture.
19401     // FIXME: Do we also need to do this inside dependent typeid expressions
19402     // (which are modeled as unevaluated at this point)?
19403     const bool RefersToEnclosingScope =
19404         (SemaRef.CurContext != Var->getDeclContext() &&
19405          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19406     if (RefersToEnclosingScope) {
19407       LambdaScopeInfo *const LSI =
19408           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19409       if (LSI && (!LSI->CallOperator ||
19410                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19411         // If a variable could potentially be odr-used, defer marking it so
19412         // until we finish analyzing the full expression for any
19413         // lvalue-to-rvalue
19414         // or discarded value conversions that would obviate odr-use.
19415         // Add it to the list of potential captures that will be analyzed
19416         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19417         // unless the variable is a reference that was initialized by a constant
19418         // expression (this will never need to be captured or odr-used).
19419         //
19420         // FIXME: We can simplify this a lot after implementing P0588R1.
19421         assert(E && "Capture variable should be used in an expression.");
19422         if (!Var->getType()->isReferenceType() ||
19423             !Var->isUsableInConstantExpressions(SemaRef.Context))
19424           LSI->addPotentialCapture(E->IgnoreParens());
19425       }
19426     }
19427     break;
19428   }
19429 }
19430 
19431 /// Mark a variable referenced, and check whether it is odr-used
19432 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19433 /// used directly for normal expressions referring to VarDecl.
19434 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19435   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19436 }
19437 
19438 static void
19439 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19440                    bool MightBeOdrUse,
19441                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19442   if (SemaRef.isInOpenMPDeclareTargetContext())
19443     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19444 
19445   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19446     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19447     return;
19448   }
19449 
19450   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19451 
19452   // If this is a call to a method via a cast, also mark the method in the
19453   // derived class used in case codegen can devirtualize the call.
19454   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19455   if (!ME)
19456     return;
19457   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19458   if (!MD)
19459     return;
19460   // Only attempt to devirtualize if this is truly a virtual call.
19461   bool IsVirtualCall = MD->isVirtual() &&
19462                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19463   if (!IsVirtualCall)
19464     return;
19465 
19466   // If it's possible to devirtualize the call, mark the called function
19467   // referenced.
19468   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19469       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19470   if (DM)
19471     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19472 }
19473 
19474 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19475 ///
19476 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19477 /// handled with care if the DeclRefExpr is not newly-created.
19478 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19479   // TODO: update this with DR# once a defect report is filed.
19480   // C++11 defect. The address of a pure member should not be an ODR use, even
19481   // if it's a qualified reference.
19482   bool OdrUse = true;
19483   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19484     if (Method->isVirtual() &&
19485         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19486       OdrUse = false;
19487 
19488   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19489     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19490         FD->isConsteval() && !RebuildingImmediateInvocation)
19491       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19492   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19493                      RefsMinusAssignments);
19494 }
19495 
19496 /// Perform reference-marking and odr-use handling for a MemberExpr.
19497 void Sema::MarkMemberReferenced(MemberExpr *E) {
19498   // C++11 [basic.def.odr]p2:
19499   //   A non-overloaded function whose name appears as a potentially-evaluated
19500   //   expression or a member of a set of candidate functions, if selected by
19501   //   overload resolution when referred to from a potentially-evaluated
19502   //   expression, is odr-used, unless it is a pure virtual function and its
19503   //   name is not explicitly qualified.
19504   bool MightBeOdrUse = true;
19505   if (E->performsVirtualDispatch(getLangOpts())) {
19506     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19507       if (Method->isPure())
19508         MightBeOdrUse = false;
19509   }
19510   SourceLocation Loc =
19511       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19512   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19513                      RefsMinusAssignments);
19514 }
19515 
19516 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19517 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19518   for (VarDecl *VD : *E)
19519     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19520                        RefsMinusAssignments);
19521 }
19522 
19523 /// Perform marking for a reference to an arbitrary declaration.  It
19524 /// marks the declaration referenced, and performs odr-use checking for
19525 /// functions and variables. This method should not be used when building a
19526 /// normal expression which refers to a variable.
19527 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19528                                  bool MightBeOdrUse) {
19529   if (MightBeOdrUse) {
19530     if (auto *VD = dyn_cast<VarDecl>(D)) {
19531       MarkVariableReferenced(Loc, VD);
19532       return;
19533     }
19534   }
19535   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19536     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19537     return;
19538   }
19539   D->setReferenced();
19540 }
19541 
19542 namespace {
19543   // Mark all of the declarations used by a type as referenced.
19544   // FIXME: Not fully implemented yet! We need to have a better understanding
19545   // of when we're entering a context we should not recurse into.
19546   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19547   // TreeTransforms rebuilding the type in a new context. Rather than
19548   // duplicating the TreeTransform logic, we should consider reusing it here.
19549   // Currently that causes problems when rebuilding LambdaExprs.
19550   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19551     Sema &S;
19552     SourceLocation Loc;
19553 
19554   public:
19555     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19556 
19557     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19558 
19559     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19560   };
19561 }
19562 
19563 bool MarkReferencedDecls::TraverseTemplateArgument(
19564     const TemplateArgument &Arg) {
19565   {
19566     // A non-type template argument is a constant-evaluated context.
19567     EnterExpressionEvaluationContext Evaluated(
19568         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19569     if (Arg.getKind() == TemplateArgument::Declaration) {
19570       if (Decl *D = Arg.getAsDecl())
19571         S.MarkAnyDeclReferenced(Loc, D, true);
19572     } else if (Arg.getKind() == TemplateArgument::Expression) {
19573       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19574     }
19575   }
19576 
19577   return Inherited::TraverseTemplateArgument(Arg);
19578 }
19579 
19580 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19581   MarkReferencedDecls Marker(*this, Loc);
19582   Marker.TraverseType(T);
19583 }
19584 
19585 namespace {
19586 /// Helper class that marks all of the declarations referenced by
19587 /// potentially-evaluated subexpressions as "referenced".
19588 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19589 public:
19590   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19591   bool SkipLocalVariables;
19592   ArrayRef<const Expr *> StopAt;
19593 
19594   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19595                       ArrayRef<const Expr *> StopAt)
19596       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19597 
19598   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19599     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19600   }
19601 
19602   void Visit(Expr *E) {
19603     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19604       return;
19605     Inherited::Visit(E);
19606   }
19607 
19608   void VisitDeclRefExpr(DeclRefExpr *E) {
19609     // If we were asked not to visit local variables, don't.
19610     if (SkipLocalVariables) {
19611       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19612         if (VD->hasLocalStorage())
19613           return;
19614     }
19615 
19616     // FIXME: This can trigger the instantiation of the initializer of a
19617     // variable, which can cause the expression to become value-dependent
19618     // or error-dependent. Do we need to propagate the new dependence bits?
19619     S.MarkDeclRefReferenced(E);
19620   }
19621 
19622   void VisitMemberExpr(MemberExpr *E) {
19623     S.MarkMemberReferenced(E);
19624     Visit(E->getBase());
19625   }
19626 };
19627 } // namespace
19628 
19629 /// Mark any declarations that appear within this expression or any
19630 /// potentially-evaluated subexpressions as "referenced".
19631 ///
19632 /// \param SkipLocalVariables If true, don't mark local variables as
19633 /// 'referenced'.
19634 /// \param StopAt Subexpressions that we shouldn't recurse into.
19635 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19636                                             bool SkipLocalVariables,
19637                                             ArrayRef<const Expr*> StopAt) {
19638   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19639 }
19640 
19641 /// Emit a diagnostic when statements are reachable.
19642 /// FIXME: check for reachability even in expressions for which we don't build a
19643 ///        CFG (eg, in the initializer of a global or in a constant expression).
19644 ///        For example,
19645 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19646 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19647                            const PartialDiagnostic &PD) {
19648   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19649     if (!FunctionScopes.empty())
19650       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19651           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19652     return true;
19653   }
19654 
19655   // The initializer of a constexpr variable or of the first declaration of a
19656   // static data member is not syntactically a constant evaluated constant,
19657   // but nonetheless is always required to be a constant expression, so we
19658   // can skip diagnosing.
19659   // FIXME: Using the mangling context here is a hack.
19660   if (auto *VD = dyn_cast_or_null<VarDecl>(
19661           ExprEvalContexts.back().ManglingContextDecl)) {
19662     if (VD->isConstexpr() ||
19663         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19664       return false;
19665     // FIXME: For any other kind of variable, we should build a CFG for its
19666     // initializer and check whether the context in question is reachable.
19667   }
19668 
19669   Diag(Loc, PD);
19670   return true;
19671 }
19672 
19673 /// Emit a diagnostic that describes an effect on the run-time behavior
19674 /// of the program being compiled.
19675 ///
19676 /// This routine emits the given diagnostic when the code currently being
19677 /// type-checked is "potentially evaluated", meaning that there is a
19678 /// possibility that the code will actually be executable. Code in sizeof()
19679 /// expressions, code used only during overload resolution, etc., are not
19680 /// potentially evaluated. This routine will suppress such diagnostics or,
19681 /// in the absolutely nutty case of potentially potentially evaluated
19682 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19683 /// later.
19684 ///
19685 /// This routine should be used for all diagnostics that describe the run-time
19686 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19687 /// Failure to do so will likely result in spurious diagnostics or failures
19688 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19689 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19690                                const PartialDiagnostic &PD) {
19691 
19692   if (ExprEvalContexts.back().isDiscardedStatementContext())
19693     return false;
19694 
19695   switch (ExprEvalContexts.back().Context) {
19696   case ExpressionEvaluationContext::Unevaluated:
19697   case ExpressionEvaluationContext::UnevaluatedList:
19698   case ExpressionEvaluationContext::UnevaluatedAbstract:
19699   case ExpressionEvaluationContext::DiscardedStatement:
19700     // The argument will never be evaluated, so don't complain.
19701     break;
19702 
19703   case ExpressionEvaluationContext::ConstantEvaluated:
19704   case ExpressionEvaluationContext::ImmediateFunctionContext:
19705     // Relevant diagnostics should be produced by constant evaluation.
19706     break;
19707 
19708   case ExpressionEvaluationContext::PotentiallyEvaluated:
19709   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19710     return DiagIfReachable(Loc, Stmts, PD);
19711   }
19712 
19713   return false;
19714 }
19715 
19716 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19717                                const PartialDiagnostic &PD) {
19718   return DiagRuntimeBehavior(
19719       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19720 }
19721 
19722 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19723                                CallExpr *CE, FunctionDecl *FD) {
19724   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19725     return false;
19726 
19727   // If we're inside a decltype's expression, don't check for a valid return
19728   // type or construct temporaries until we know whether this is the last call.
19729   if (ExprEvalContexts.back().ExprContext ==
19730       ExpressionEvaluationContextRecord::EK_Decltype) {
19731     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19732     return false;
19733   }
19734 
19735   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19736     FunctionDecl *FD;
19737     CallExpr *CE;
19738 
19739   public:
19740     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19741       : FD(FD), CE(CE) { }
19742 
19743     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19744       if (!FD) {
19745         S.Diag(Loc, diag::err_call_incomplete_return)
19746           << T << CE->getSourceRange();
19747         return;
19748       }
19749 
19750       S.Diag(Loc, diag::err_call_function_incomplete_return)
19751           << CE->getSourceRange() << FD << T;
19752       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19753           << FD->getDeclName();
19754     }
19755   } Diagnoser(FD, CE);
19756 
19757   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19758     return true;
19759 
19760   return false;
19761 }
19762 
19763 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19764 // will prevent this condition from triggering, which is what we want.
19765 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19766   SourceLocation Loc;
19767 
19768   unsigned diagnostic = diag::warn_condition_is_assignment;
19769   bool IsOrAssign = false;
19770 
19771   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19772     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19773       return;
19774 
19775     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19776 
19777     // Greylist some idioms by putting them into a warning subcategory.
19778     if (ObjCMessageExpr *ME
19779           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19780       Selector Sel = ME->getSelector();
19781 
19782       // self = [<foo> init...]
19783       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19784         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19785 
19786       // <foo> = [<bar> nextObject]
19787       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19788         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19789     }
19790 
19791     Loc = Op->getOperatorLoc();
19792   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19793     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19794       return;
19795 
19796     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19797     Loc = Op->getOperatorLoc();
19798   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19799     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19800   else {
19801     // Not an assignment.
19802     return;
19803   }
19804 
19805   Diag(Loc, diagnostic) << E->getSourceRange();
19806 
19807   SourceLocation Open = E->getBeginLoc();
19808   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19809   Diag(Loc, diag::note_condition_assign_silence)
19810         << FixItHint::CreateInsertion(Open, "(")
19811         << FixItHint::CreateInsertion(Close, ")");
19812 
19813   if (IsOrAssign)
19814     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19815       << FixItHint::CreateReplacement(Loc, "!=");
19816   else
19817     Diag(Loc, diag::note_condition_assign_to_comparison)
19818       << FixItHint::CreateReplacement(Loc, "==");
19819 }
19820 
19821 /// Redundant parentheses over an equality comparison can indicate
19822 /// that the user intended an assignment used as condition.
19823 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19824   // Don't warn if the parens came from a macro.
19825   SourceLocation parenLoc = ParenE->getBeginLoc();
19826   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19827     return;
19828   // Don't warn for dependent expressions.
19829   if (ParenE->isTypeDependent())
19830     return;
19831 
19832   Expr *E = ParenE->IgnoreParens();
19833 
19834   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19835     if (opE->getOpcode() == BO_EQ &&
19836         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19837                                                            == Expr::MLV_Valid) {
19838       SourceLocation Loc = opE->getOperatorLoc();
19839 
19840       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19841       SourceRange ParenERange = ParenE->getSourceRange();
19842       Diag(Loc, diag::note_equality_comparison_silence)
19843         << FixItHint::CreateRemoval(ParenERange.getBegin())
19844         << FixItHint::CreateRemoval(ParenERange.getEnd());
19845       Diag(Loc, diag::note_equality_comparison_to_assign)
19846         << FixItHint::CreateReplacement(Loc, "=");
19847     }
19848 }
19849 
19850 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19851                                        bool IsConstexpr) {
19852   DiagnoseAssignmentAsCondition(E);
19853   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19854     DiagnoseEqualityWithExtraParens(parenE);
19855 
19856   ExprResult result = CheckPlaceholderExpr(E);
19857   if (result.isInvalid()) return ExprError();
19858   E = result.get();
19859 
19860   if (!E->isTypeDependent()) {
19861     if (getLangOpts().CPlusPlus)
19862       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19863 
19864     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19865     if (ERes.isInvalid())
19866       return ExprError();
19867     E = ERes.get();
19868 
19869     QualType T = E->getType();
19870     if (!T->isScalarType()) { // C99 6.8.4.1p1
19871       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19872         << T << E->getSourceRange();
19873       return ExprError();
19874     }
19875     CheckBoolLikeConversion(E, Loc);
19876   }
19877 
19878   return E;
19879 }
19880 
19881 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19882                                            Expr *SubExpr, ConditionKind CK,
19883                                            bool MissingOK) {
19884   // MissingOK indicates whether having no condition expression is valid
19885   // (for loop) or invalid (e.g. while loop).
19886   if (!SubExpr)
19887     return MissingOK ? ConditionResult() : ConditionError();
19888 
19889   ExprResult Cond;
19890   switch (CK) {
19891   case ConditionKind::Boolean:
19892     Cond = CheckBooleanCondition(Loc, SubExpr);
19893     break;
19894 
19895   case ConditionKind::ConstexprIf:
19896     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19897     break;
19898 
19899   case ConditionKind::Switch:
19900     Cond = CheckSwitchCondition(Loc, SubExpr);
19901     break;
19902   }
19903   if (Cond.isInvalid()) {
19904     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19905                               {SubExpr}, PreferredConditionType(CK));
19906     if (!Cond.get())
19907       return ConditionError();
19908   }
19909   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19910   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19911   if (!FullExpr.get())
19912     return ConditionError();
19913 
19914   return ConditionResult(*this, nullptr, FullExpr,
19915                          CK == ConditionKind::ConstexprIf);
19916 }
19917 
19918 namespace {
19919   /// A visitor for rebuilding a call to an __unknown_any expression
19920   /// to have an appropriate type.
19921   struct RebuildUnknownAnyFunction
19922     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19923 
19924     Sema &S;
19925 
19926     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19927 
19928     ExprResult VisitStmt(Stmt *S) {
19929       llvm_unreachable("unexpected statement!");
19930     }
19931 
19932     ExprResult VisitExpr(Expr *E) {
19933       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19934         << E->getSourceRange();
19935       return ExprError();
19936     }
19937 
19938     /// Rebuild an expression which simply semantically wraps another
19939     /// expression which it shares the type and value kind of.
19940     template <class T> ExprResult rebuildSugarExpr(T *E) {
19941       ExprResult SubResult = Visit(E->getSubExpr());
19942       if (SubResult.isInvalid()) return ExprError();
19943 
19944       Expr *SubExpr = SubResult.get();
19945       E->setSubExpr(SubExpr);
19946       E->setType(SubExpr->getType());
19947       E->setValueKind(SubExpr->getValueKind());
19948       assert(E->getObjectKind() == OK_Ordinary);
19949       return E;
19950     }
19951 
19952     ExprResult VisitParenExpr(ParenExpr *E) {
19953       return rebuildSugarExpr(E);
19954     }
19955 
19956     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19957       return rebuildSugarExpr(E);
19958     }
19959 
19960     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19961       ExprResult SubResult = Visit(E->getSubExpr());
19962       if (SubResult.isInvalid()) return ExprError();
19963 
19964       Expr *SubExpr = SubResult.get();
19965       E->setSubExpr(SubExpr);
19966       E->setType(S.Context.getPointerType(SubExpr->getType()));
19967       assert(E->isPRValue());
19968       assert(E->getObjectKind() == OK_Ordinary);
19969       return E;
19970     }
19971 
19972     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19973       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19974 
19975       E->setType(VD->getType());
19976 
19977       assert(E->isPRValue());
19978       if (S.getLangOpts().CPlusPlus &&
19979           !(isa<CXXMethodDecl>(VD) &&
19980             cast<CXXMethodDecl>(VD)->isInstance()))
19981         E->setValueKind(VK_LValue);
19982 
19983       return E;
19984     }
19985 
19986     ExprResult VisitMemberExpr(MemberExpr *E) {
19987       return resolveDecl(E, E->getMemberDecl());
19988     }
19989 
19990     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19991       return resolveDecl(E, E->getDecl());
19992     }
19993   };
19994 }
19995 
19996 /// Given a function expression of unknown-any type, try to rebuild it
19997 /// to have a function type.
19998 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19999   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20000   if (Result.isInvalid()) return ExprError();
20001   return S.DefaultFunctionArrayConversion(Result.get());
20002 }
20003 
20004 namespace {
20005   /// A visitor for rebuilding an expression of type __unknown_anytype
20006   /// into one which resolves the type directly on the referring
20007   /// expression.  Strict preservation of the original source
20008   /// structure is not a goal.
20009   struct RebuildUnknownAnyExpr
20010     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20011 
20012     Sema &S;
20013 
20014     /// The current destination type.
20015     QualType DestType;
20016 
20017     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20018       : S(S), DestType(CastType) {}
20019 
20020     ExprResult VisitStmt(Stmt *S) {
20021       llvm_unreachable("unexpected statement!");
20022     }
20023 
20024     ExprResult VisitExpr(Expr *E) {
20025       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20026         << E->getSourceRange();
20027       return ExprError();
20028     }
20029 
20030     ExprResult VisitCallExpr(CallExpr *E);
20031     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20032 
20033     /// Rebuild an expression which simply semantically wraps another
20034     /// expression which it shares the type and value kind of.
20035     template <class T> ExprResult rebuildSugarExpr(T *E) {
20036       ExprResult SubResult = Visit(E->getSubExpr());
20037       if (SubResult.isInvalid()) return ExprError();
20038       Expr *SubExpr = SubResult.get();
20039       E->setSubExpr(SubExpr);
20040       E->setType(SubExpr->getType());
20041       E->setValueKind(SubExpr->getValueKind());
20042       assert(E->getObjectKind() == OK_Ordinary);
20043       return E;
20044     }
20045 
20046     ExprResult VisitParenExpr(ParenExpr *E) {
20047       return rebuildSugarExpr(E);
20048     }
20049 
20050     ExprResult VisitUnaryExtension(UnaryOperator *E) {
20051       return rebuildSugarExpr(E);
20052     }
20053 
20054     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20055       const PointerType *Ptr = DestType->getAs<PointerType>();
20056       if (!Ptr) {
20057         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20058           << E->getSourceRange();
20059         return ExprError();
20060       }
20061 
20062       if (isa<CallExpr>(E->getSubExpr())) {
20063         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20064           << E->getSourceRange();
20065         return ExprError();
20066       }
20067 
20068       assert(E->isPRValue());
20069       assert(E->getObjectKind() == OK_Ordinary);
20070       E->setType(DestType);
20071 
20072       // Build the sub-expression as if it were an object of the pointee type.
20073       DestType = Ptr->getPointeeType();
20074       ExprResult SubResult = Visit(E->getSubExpr());
20075       if (SubResult.isInvalid()) return ExprError();
20076       E->setSubExpr(SubResult.get());
20077       return E;
20078     }
20079 
20080     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20081 
20082     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20083 
20084     ExprResult VisitMemberExpr(MemberExpr *E) {
20085       return resolveDecl(E, E->getMemberDecl());
20086     }
20087 
20088     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20089       return resolveDecl(E, E->getDecl());
20090     }
20091   };
20092 }
20093 
20094 /// Rebuilds a call expression which yielded __unknown_anytype.
20095 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20096   Expr *CalleeExpr = E->getCallee();
20097 
20098   enum FnKind {
20099     FK_MemberFunction,
20100     FK_FunctionPointer,
20101     FK_BlockPointer
20102   };
20103 
20104   FnKind Kind;
20105   QualType CalleeType = CalleeExpr->getType();
20106   if (CalleeType == S.Context.BoundMemberTy) {
20107     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20108     Kind = FK_MemberFunction;
20109     CalleeType = Expr::findBoundMemberType(CalleeExpr);
20110   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20111     CalleeType = Ptr->getPointeeType();
20112     Kind = FK_FunctionPointer;
20113   } else {
20114     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20115     Kind = FK_BlockPointer;
20116   }
20117   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20118 
20119   // Verify that this is a legal result type of a function.
20120   if (DestType->isArrayType() || DestType->isFunctionType()) {
20121     unsigned diagID = diag::err_func_returning_array_function;
20122     if (Kind == FK_BlockPointer)
20123       diagID = diag::err_block_returning_array_function;
20124 
20125     S.Diag(E->getExprLoc(), diagID)
20126       << DestType->isFunctionType() << DestType;
20127     return ExprError();
20128   }
20129 
20130   // Otherwise, go ahead and set DestType as the call's result.
20131   E->setType(DestType.getNonLValueExprType(S.Context));
20132   E->setValueKind(Expr::getValueKindForType(DestType));
20133   assert(E->getObjectKind() == OK_Ordinary);
20134 
20135   // Rebuild the function type, replacing the result type with DestType.
20136   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20137   if (Proto) {
20138     // __unknown_anytype(...) is a special case used by the debugger when
20139     // it has no idea what a function's signature is.
20140     //
20141     // We want to build this call essentially under the K&R
20142     // unprototyped rules, but making a FunctionNoProtoType in C++
20143     // would foul up all sorts of assumptions.  However, we cannot
20144     // simply pass all arguments as variadic arguments, nor can we
20145     // portably just call the function under a non-variadic type; see
20146     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20147     // However, it turns out that in practice it is generally safe to
20148     // call a function declared as "A foo(B,C,D);" under the prototype
20149     // "A foo(B,C,D,...);".  The only known exception is with the
20150     // Windows ABI, where any variadic function is implicitly cdecl
20151     // regardless of its normal CC.  Therefore we change the parameter
20152     // types to match the types of the arguments.
20153     //
20154     // This is a hack, but it is far superior to moving the
20155     // corresponding target-specific code from IR-gen to Sema/AST.
20156 
20157     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20158     SmallVector<QualType, 8> ArgTypes;
20159     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20160       ArgTypes.reserve(E->getNumArgs());
20161       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20162         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20163       }
20164       ParamTypes = ArgTypes;
20165     }
20166     DestType = S.Context.getFunctionType(DestType, ParamTypes,
20167                                          Proto->getExtProtoInfo());
20168   } else {
20169     DestType = S.Context.getFunctionNoProtoType(DestType,
20170                                                 FnType->getExtInfo());
20171   }
20172 
20173   // Rebuild the appropriate pointer-to-function type.
20174   switch (Kind) {
20175   case FK_MemberFunction:
20176     // Nothing to do.
20177     break;
20178 
20179   case FK_FunctionPointer:
20180     DestType = S.Context.getPointerType(DestType);
20181     break;
20182 
20183   case FK_BlockPointer:
20184     DestType = S.Context.getBlockPointerType(DestType);
20185     break;
20186   }
20187 
20188   // Finally, we can recurse.
20189   ExprResult CalleeResult = Visit(CalleeExpr);
20190   if (!CalleeResult.isUsable()) return ExprError();
20191   E->setCallee(CalleeResult.get());
20192 
20193   // Bind a temporary if necessary.
20194   return S.MaybeBindToTemporary(E);
20195 }
20196 
20197 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20198   // Verify that this is a legal result type of a call.
20199   if (DestType->isArrayType() || DestType->isFunctionType()) {
20200     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20201       << DestType->isFunctionType() << DestType;
20202     return ExprError();
20203   }
20204 
20205   // Rewrite the method result type if available.
20206   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20207     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20208     Method->setReturnType(DestType);
20209   }
20210 
20211   // Change the type of the message.
20212   E->setType(DestType.getNonReferenceType());
20213   E->setValueKind(Expr::getValueKindForType(DestType));
20214 
20215   return S.MaybeBindToTemporary(E);
20216 }
20217 
20218 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20219   // The only case we should ever see here is a function-to-pointer decay.
20220   if (E->getCastKind() == CK_FunctionToPointerDecay) {
20221     assert(E->isPRValue());
20222     assert(E->getObjectKind() == OK_Ordinary);
20223 
20224     E->setType(DestType);
20225 
20226     // Rebuild the sub-expression as the pointee (function) type.
20227     DestType = DestType->castAs<PointerType>()->getPointeeType();
20228 
20229     ExprResult Result = Visit(E->getSubExpr());
20230     if (!Result.isUsable()) return ExprError();
20231 
20232     E->setSubExpr(Result.get());
20233     return E;
20234   } else if (E->getCastKind() == CK_LValueToRValue) {
20235     assert(E->isPRValue());
20236     assert(E->getObjectKind() == OK_Ordinary);
20237 
20238     assert(isa<BlockPointerType>(E->getType()));
20239 
20240     E->setType(DestType);
20241 
20242     // The sub-expression has to be a lvalue reference, so rebuild it as such.
20243     DestType = S.Context.getLValueReferenceType(DestType);
20244 
20245     ExprResult Result = Visit(E->getSubExpr());
20246     if (!Result.isUsable()) return ExprError();
20247 
20248     E->setSubExpr(Result.get());
20249     return E;
20250   } else {
20251     llvm_unreachable("Unhandled cast type!");
20252   }
20253 }
20254 
20255 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20256   ExprValueKind ValueKind = VK_LValue;
20257   QualType Type = DestType;
20258 
20259   // We know how to make this work for certain kinds of decls:
20260 
20261   //  - functions
20262   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20263     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20264       DestType = Ptr->getPointeeType();
20265       ExprResult Result = resolveDecl(E, VD);
20266       if (Result.isInvalid()) return ExprError();
20267       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20268                                  VK_PRValue);
20269     }
20270 
20271     if (!Type->isFunctionType()) {
20272       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20273         << VD << E->getSourceRange();
20274       return ExprError();
20275     }
20276     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20277       // We must match the FunctionDecl's type to the hack introduced in
20278       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20279       // type. See the lengthy commentary in that routine.
20280       QualType FDT = FD->getType();
20281       const FunctionType *FnType = FDT->castAs<FunctionType>();
20282       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20283       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20284       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20285         SourceLocation Loc = FD->getLocation();
20286         FunctionDecl *NewFD = FunctionDecl::Create(
20287             S.Context, FD->getDeclContext(), Loc, Loc,
20288             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20289             SC_None, S.getCurFPFeatures().isFPConstrained(),
20290             false /*isInlineSpecified*/, FD->hasPrototype(),
20291             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20292 
20293         if (FD->getQualifier())
20294           NewFD->setQualifierInfo(FD->getQualifierLoc());
20295 
20296         SmallVector<ParmVarDecl*, 16> Params;
20297         for (const auto &AI : FT->param_types()) {
20298           ParmVarDecl *Param =
20299             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20300           Param->setScopeInfo(0, Params.size());
20301           Params.push_back(Param);
20302         }
20303         NewFD->setParams(Params);
20304         DRE->setDecl(NewFD);
20305         VD = DRE->getDecl();
20306       }
20307     }
20308 
20309     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20310       if (MD->isInstance()) {
20311         ValueKind = VK_PRValue;
20312         Type = S.Context.BoundMemberTy;
20313       }
20314 
20315     // Function references aren't l-values in C.
20316     if (!S.getLangOpts().CPlusPlus)
20317       ValueKind = VK_PRValue;
20318 
20319   //  - variables
20320   } else if (isa<VarDecl>(VD)) {
20321     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20322       Type = RefTy->getPointeeType();
20323     } else if (Type->isFunctionType()) {
20324       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20325         << VD << E->getSourceRange();
20326       return ExprError();
20327     }
20328 
20329   //  - nothing else
20330   } else {
20331     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20332       << VD << E->getSourceRange();
20333     return ExprError();
20334   }
20335 
20336   // Modifying the declaration like this is friendly to IR-gen but
20337   // also really dangerous.
20338   VD->setType(DestType);
20339   E->setType(Type);
20340   E->setValueKind(ValueKind);
20341   return E;
20342 }
20343 
20344 /// Check a cast of an unknown-any type.  We intentionally only
20345 /// trigger this for C-style casts.
20346 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20347                                      Expr *CastExpr, CastKind &CastKind,
20348                                      ExprValueKind &VK, CXXCastPath &Path) {
20349   // The type we're casting to must be either void or complete.
20350   if (!CastType->isVoidType() &&
20351       RequireCompleteType(TypeRange.getBegin(), CastType,
20352                           diag::err_typecheck_cast_to_incomplete))
20353     return ExprError();
20354 
20355   // Rewrite the casted expression from scratch.
20356   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20357   if (!result.isUsable()) return ExprError();
20358 
20359   CastExpr = result.get();
20360   VK = CastExpr->getValueKind();
20361   CastKind = CK_NoOp;
20362 
20363   return CastExpr;
20364 }
20365 
20366 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20367   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20368 }
20369 
20370 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20371                                     Expr *arg, QualType &paramType) {
20372   // If the syntactic form of the argument is not an explicit cast of
20373   // any sort, just do default argument promotion.
20374   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20375   if (!castArg) {
20376     ExprResult result = DefaultArgumentPromotion(arg);
20377     if (result.isInvalid()) return ExprError();
20378     paramType = result.get()->getType();
20379     return result;
20380   }
20381 
20382   // Otherwise, use the type that was written in the explicit cast.
20383   assert(!arg->hasPlaceholderType());
20384   paramType = castArg->getTypeAsWritten();
20385 
20386   // Copy-initialize a parameter of that type.
20387   InitializedEntity entity =
20388     InitializedEntity::InitializeParameter(Context, paramType,
20389                                            /*consumed*/ false);
20390   return PerformCopyInitialization(entity, callLoc, arg);
20391 }
20392 
20393 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20394   Expr *orig = E;
20395   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20396   while (true) {
20397     E = E->IgnoreParenImpCasts();
20398     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20399       E = call->getCallee();
20400       diagID = diag::err_uncasted_call_of_unknown_any;
20401     } else {
20402       break;
20403     }
20404   }
20405 
20406   SourceLocation loc;
20407   NamedDecl *d;
20408   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20409     loc = ref->getLocation();
20410     d = ref->getDecl();
20411   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20412     loc = mem->getMemberLoc();
20413     d = mem->getMemberDecl();
20414   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20415     diagID = diag::err_uncasted_call_of_unknown_any;
20416     loc = msg->getSelectorStartLoc();
20417     d = msg->getMethodDecl();
20418     if (!d) {
20419       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20420         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20421         << orig->getSourceRange();
20422       return ExprError();
20423     }
20424   } else {
20425     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20426       << E->getSourceRange();
20427     return ExprError();
20428   }
20429 
20430   S.Diag(loc, diagID) << d << orig->getSourceRange();
20431 
20432   // Never recoverable.
20433   return ExprError();
20434 }
20435 
20436 /// Check for operands with placeholder types and complain if found.
20437 /// Returns ExprError() if there was an error and no recovery was possible.
20438 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20439   if (!Context.isDependenceAllowed()) {
20440     // C cannot handle TypoExpr nodes on either side of a binop because it
20441     // doesn't handle dependent types properly, so make sure any TypoExprs have
20442     // been dealt with before checking the operands.
20443     ExprResult Result = CorrectDelayedTyposInExpr(E);
20444     if (!Result.isUsable()) return ExprError();
20445     E = Result.get();
20446   }
20447 
20448   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20449   if (!placeholderType) return E;
20450 
20451   switch (placeholderType->getKind()) {
20452 
20453   // Overloaded expressions.
20454   case BuiltinType::Overload: {
20455     // Try to resolve a single function template specialization.
20456     // This is obligatory.
20457     ExprResult Result = E;
20458     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20459       return Result;
20460 
20461     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20462     // leaves Result unchanged on failure.
20463     Result = E;
20464     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20465       return Result;
20466 
20467     // If that failed, try to recover with a call.
20468     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20469                          /*complain*/ true);
20470     return Result;
20471   }
20472 
20473   // Bound member functions.
20474   case BuiltinType::BoundMember: {
20475     ExprResult result = E;
20476     const Expr *BME = E->IgnoreParens();
20477     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20478     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20479     if (isa<CXXPseudoDestructorExpr>(BME)) {
20480       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20481     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20482       if (ME->getMemberNameInfo().getName().getNameKind() ==
20483           DeclarationName::CXXDestructorName)
20484         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20485     }
20486     tryToRecoverWithCall(result, PD,
20487                          /*complain*/ true);
20488     return result;
20489   }
20490 
20491   // ARC unbridged casts.
20492   case BuiltinType::ARCUnbridgedCast: {
20493     Expr *realCast = stripARCUnbridgedCast(E);
20494     diagnoseARCUnbridgedCast(realCast);
20495     return realCast;
20496   }
20497 
20498   // Expressions of unknown type.
20499   case BuiltinType::UnknownAny:
20500     return diagnoseUnknownAnyExpr(*this, E);
20501 
20502   // Pseudo-objects.
20503   case BuiltinType::PseudoObject:
20504     return checkPseudoObjectRValue(E);
20505 
20506   case BuiltinType::BuiltinFn: {
20507     // Accept __noop without parens by implicitly converting it to a call expr.
20508     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20509     if (DRE) {
20510       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20511       unsigned BuiltinID = FD->getBuiltinID();
20512       if (BuiltinID == Builtin::BI__noop) {
20513         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20514                               CK_BuiltinFnToFnPtr)
20515                 .get();
20516         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20517                                 VK_PRValue, SourceLocation(),
20518                                 FPOptionsOverride());
20519       }
20520 
20521       if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20522         // Any use of these other than a direct call is ill-formed as of C++20,
20523         // because they are not addressable functions. In earlier language
20524         // modes, warn and force an instantiation of the real body.
20525         Diag(E->getBeginLoc(),
20526              getLangOpts().CPlusPlus20
20527                  ? diag::err_use_of_unaddressable_function
20528                  : diag::warn_cxx20_compat_use_of_unaddressable_function);
20529         if (FD->isImplicitlyInstantiable()) {
20530           // Require a definition here because a normal attempt at
20531           // instantiation for a builtin will be ignored, and we won't try
20532           // again later. We assume that the definition of the template
20533           // precedes this use.
20534           InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20535                                         /*Recursive=*/false,
20536                                         /*DefinitionRequired=*/true,
20537                                         /*AtEndOfTU=*/false);
20538         }
20539         // Produce a properly-typed reference to the function.
20540         CXXScopeSpec SS;
20541         SS.Adopt(DRE->getQualifierLoc());
20542         TemplateArgumentListInfo TemplateArgs;
20543         DRE->copyTemplateArgumentsInto(TemplateArgs);
20544         return BuildDeclRefExpr(
20545             FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20546             DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20547             DRE->getTemplateKeywordLoc(),
20548             DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20549       }
20550     }
20551 
20552     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20553     return ExprError();
20554   }
20555 
20556   case BuiltinType::IncompleteMatrixIdx:
20557     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20558              ->getRowIdx()
20559              ->getBeginLoc(),
20560          diag::err_matrix_incomplete_index);
20561     return ExprError();
20562 
20563   // Expressions of unknown type.
20564   case BuiltinType::OMPArraySection:
20565     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20566     return ExprError();
20567 
20568   // Expressions of unknown type.
20569   case BuiltinType::OMPArrayShaping:
20570     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20571 
20572   case BuiltinType::OMPIterator:
20573     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20574 
20575   // Everything else should be impossible.
20576 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20577   case BuiltinType::Id:
20578 #include "clang/Basic/OpenCLImageTypes.def"
20579 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20580   case BuiltinType::Id:
20581 #include "clang/Basic/OpenCLExtensionTypes.def"
20582 #define SVE_TYPE(Name, Id, SingletonId) \
20583   case BuiltinType::Id:
20584 #include "clang/Basic/AArch64SVEACLETypes.def"
20585 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20586   case BuiltinType::Id:
20587 #include "clang/Basic/PPCTypes.def"
20588 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20589 #include "clang/Basic/RISCVVTypes.def"
20590 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20591 #define PLACEHOLDER_TYPE(Id, SingletonId)
20592 #include "clang/AST/BuiltinTypes.def"
20593     break;
20594   }
20595 
20596   llvm_unreachable("invalid placeholder type!");
20597 }
20598 
20599 bool Sema::CheckCaseExpression(Expr *E) {
20600   if (E->isTypeDependent())
20601     return true;
20602   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20603     return E->getType()->isIntegralOrEnumerationType();
20604   return false;
20605 }
20606 
20607 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20608 ExprResult
20609 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20610   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20611          "Unknown Objective-C Boolean value!");
20612   QualType BoolT = Context.ObjCBuiltinBoolTy;
20613   if (!Context.getBOOLDecl()) {
20614     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20615                         Sema::LookupOrdinaryName);
20616     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20617       NamedDecl *ND = Result.getFoundDecl();
20618       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20619         Context.setBOOLDecl(TD);
20620     }
20621   }
20622   if (Context.getBOOLDecl())
20623     BoolT = Context.getBOOLType();
20624   return new (Context)
20625       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20626 }
20627 
20628 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20629     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20630     SourceLocation RParen) {
20631   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20632     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20633       return Spec.getPlatform() == Platform;
20634     });
20635     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20636     // for "maccatalyst" if "maccatalyst" is not specified.
20637     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20638       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20639         return Spec.getPlatform() == "ios";
20640       });
20641     }
20642     if (Spec == AvailSpecs.end())
20643       return None;
20644     return Spec->getVersion();
20645   };
20646 
20647   VersionTuple Version;
20648   if (auto MaybeVersion =
20649           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20650     Version = *MaybeVersion;
20651 
20652   // The use of `@available` in the enclosing context should be analyzed to
20653   // warn when it's used inappropriately (i.e. not if(@available)).
20654   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20655     Context->HasPotentialAvailabilityViolations = true;
20656 
20657   return new (Context)
20658       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20659 }
20660 
20661 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20662                                     ArrayRef<Expr *> SubExprs, QualType T) {
20663   if (!Context.getLangOpts().RecoveryAST)
20664     return ExprError();
20665 
20666   if (isSFINAEContext())
20667     return ExprError();
20668 
20669   if (T.isNull() || T->isUndeducedType() ||
20670       !Context.getLangOpts().RecoveryASTType)
20671     // We don't know the concrete type, fallback to dependent type.
20672     T = Context.DependentTy;
20673 
20674   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20675 }
20676