1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 
54 /// Determine whether the use of this declaration is valid, without
55 /// emitting diagnostics.
56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
57   // See if this is an auto-typed variable whose initializer we are parsing.
58   if (ParsingInitForAutoVars.count(D))
59     return false;
60 
61   // See if this is a deleted function.
62   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63     if (FD->isDeleted())
64       return false;
65 
66     // If the function has a deduced return type, and we can't deduce it,
67     // then we can't use it either.
68     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
69         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70       return false;
71 
72     // See if this is an aligned allocation/deallocation function that is
73     // unavailable.
74     if (TreatUnavailableAsInvalid &&
75         isUnavailableAlignedAllocationFunction(*FD))
76       return false;
77   }
78 
79   // See if this function is unavailable.
80   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
81       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
82     return false;
83 
84   return true;
85 }
86 
87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
88   // Warn if this is used but marked unused.
89   if (const auto *A = D->getAttr<UnusedAttr>()) {
90     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
91     // should diagnose them.
92     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
93         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
94       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
95       if (DC && !DC->hasAttr<UnusedAttr>())
96         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
97     }
98   }
99 }
100 
101 /// Emit a note explaining that this function is deleted.
102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
103   assert(Decl && Decl->isDeleted());
104 
105   if (Decl->isDefaulted()) {
106     // If the method was explicitly defaulted, point at that declaration.
107     if (!Decl->isImplicit())
108       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109 
110     // Try to diagnose why this special member function was implicitly
111     // deleted. This might fail, if that reason no longer applies.
112     DiagnoseDeletedDefaultedFunction(Decl);
113     return;
114   }
115 
116   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
117   if (Ctor && Ctor->isInheritingConstructor())
118     return NoteDeletedInheritingConstructor(Ctor);
119 
120   Diag(Decl->getLocation(), diag::note_availability_specified_here)
121     << Decl << 1;
122 }
123 
124 /// Determine whether a FunctionDecl was ever declared with an
125 /// explicit storage class.
126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
127   for (auto I : D->redecls()) {
128     if (I->getStorageClass() != SC_None)
129       return true;
130   }
131   return false;
132 }
133 
134 /// Check whether we're in an extern inline function and referring to a
135 /// variable or function with internal linkage (C11 6.7.4p3).
136 ///
137 /// This is only a warning because we used to silently accept this code, but
138 /// in many cases it will not behave correctly. This is not enabled in C++ mode
139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
140 /// and so while there may still be user mistakes, most of the time we can't
141 /// prove that there are errors.
142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
143                                                       const NamedDecl *D,
144                                                       SourceLocation Loc) {
145   // This is disabled under C++; there are too many ways for this to fire in
146   // contexts where the warning is a false positive, or where it is technically
147   // correct but benign.
148   if (S.getLangOpts().CPlusPlus)
149     return;
150 
151   // Check if this is an inlined function or method.
152   FunctionDecl *Current = S.getCurFunctionDecl();
153   if (!Current)
154     return;
155   if (!Current->isInlined())
156     return;
157   if (!Current->isExternallyVisible())
158     return;
159 
160   // Check if the decl has internal linkage.
161   if (D->getFormalLinkage() != InternalLinkage)
162     return;
163 
164   // Downgrade from ExtWarn to Extension if
165   //  (1) the supposedly external inline function is in the main file,
166   //      and probably won't be included anywhere else.
167   //  (2) the thing we're referencing is a pure function.
168   //  (3) the thing we're referencing is another inline function.
169   // This last can give us false negatives, but it's better than warning on
170   // wrappers for simple C library functions.
171   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
172   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
173   if (!DowngradeWarning && UsedFn)
174     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
175 
176   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
177                                : diag::ext_internal_in_extern_inline)
178     << /*IsVar=*/!UsedFn << D;
179 
180   S.MaybeSuggestAddingStaticToDecl(Current);
181 
182   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
183       << D;
184 }
185 
186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
187   const FunctionDecl *First = Cur->getFirstDecl();
188 
189   // Suggest "static" on the function, if possible.
190   if (!hasAnyExplicitStorageClass(First)) {
191     SourceLocation DeclBegin = First->getSourceRange().getBegin();
192     Diag(DeclBegin, diag::note_convert_inline_to_static)
193       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
194   }
195 }
196 
197 /// Determine whether the use of this declaration is valid, and
198 /// emit any corresponding diagnostics.
199 ///
200 /// This routine diagnoses various problems with referencing
201 /// declarations that can occur when using a declaration. For example,
202 /// it might warn if a deprecated or unavailable declaration is being
203 /// used, or produce an error (and return true) if a C++0x deleted
204 /// function is being used.
205 ///
206 /// \returns true if there was an error (this declaration cannot be
207 /// referenced), false otherwise.
208 ///
209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
210                              const ObjCInterfaceDecl *UnknownObjCClass,
211                              bool ObjCPropertyAccess,
212                              bool AvoidPartialAvailabilityChecks,
213                              ObjCInterfaceDecl *ClassReceiver) {
214   SourceLocation Loc = Locs.front();
215   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
216     // If there were any diagnostics suppressed by template argument deduction,
217     // emit them now.
218     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
219     if (Pos != SuppressedDiagnostics.end()) {
220       for (const PartialDiagnosticAt &Suppressed : Pos->second)
221         Diag(Suppressed.first, Suppressed.second);
222 
223       // Clear out the list of suppressed diagnostics, so that we don't emit
224       // them again for this specialization. However, we don't obsolete this
225       // entry from the table, because we want to avoid ever emitting these
226       // diagnostics again.
227       Pos->second.clear();
228     }
229 
230     // C++ [basic.start.main]p3:
231     //   The function 'main' shall not be used within a program.
232     if (cast<FunctionDecl>(D)->isMain())
233       Diag(Loc, diag::ext_main_used);
234 
235     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
236   }
237 
238   // See if this is an auto-typed variable whose initializer we are parsing.
239   if (ParsingInitForAutoVars.count(D)) {
240     if (isa<BindingDecl>(D)) {
241       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
242         << D->getDeclName();
243     } else {
244       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
245         << D->getDeclName() << cast<VarDecl>(D)->getType();
246     }
247     return true;
248   }
249 
250   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
251     // See if this is a deleted function.
252     if (FD->isDeleted()) {
253       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
254       if (Ctor && Ctor->isInheritingConstructor())
255         Diag(Loc, diag::err_deleted_inherited_ctor_use)
256             << Ctor->getParent()
257             << Ctor->getInheritedConstructor().getConstructor()->getParent();
258       else
259         Diag(Loc, diag::err_deleted_function_use);
260       NoteDeletedFunction(FD);
261       return true;
262     }
263 
264     // [expr.prim.id]p4
265     //   A program that refers explicitly or implicitly to a function with a
266     //   trailing requires-clause whose constraint-expression is not satisfied,
267     //   other than to declare it, is ill-formed. [...]
268     //
269     // See if this is a function with constraints that need to be satisfied.
270     // Check this before deducing the return type, as it might instantiate the
271     // definition.
272     if (FD->getTrailingRequiresClause()) {
273       ConstraintSatisfaction Satisfaction;
274       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
275         // A diagnostic will have already been generated (non-constant
276         // constraint expression, for example)
277         return true;
278       if (!Satisfaction.IsSatisfied) {
279         Diag(Loc,
280              diag::err_reference_to_function_with_unsatisfied_constraints)
281             << D;
282         DiagnoseUnsatisfiedConstraint(Satisfaction);
283         return true;
284       }
285     }
286 
287     // If the function has a deduced return type, and we can't deduce it,
288     // then we can't use it either.
289     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
290         DeduceReturnType(FD, Loc))
291       return true;
292 
293     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
294       return true;
295   }
296 
297   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
298     // Lambdas are only default-constructible or assignable in C++2a onwards.
299     if (MD->getParent()->isLambda() &&
300         ((isa<CXXConstructorDecl>(MD) &&
301           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
302          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
303       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
304         << !isa<CXXConstructorDecl>(MD);
305     }
306   }
307 
308   auto getReferencedObjCProp = [](const NamedDecl *D) ->
309                                       const ObjCPropertyDecl * {
310     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
311       return MD->findPropertyDecl();
312     return nullptr;
313   };
314   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
315     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
316       return true;
317   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
318       return true;
319   }
320 
321   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
322   // Only the variables omp_in and omp_out are allowed in the combiner.
323   // Only the variables omp_priv and omp_orig are allowed in the
324   // initializer-clause.
325   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
326   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
327       isa<VarDecl>(D)) {
328     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
329         << getCurFunction()->HasOMPDeclareReductionCombiner;
330     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
331     return true;
332   }
333 
334   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
335   //  List-items in map clauses on this construct may only refer to the declared
336   //  variable var and entities that could be referenced by a procedure defined
337   //  at the same location
338   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
339   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
340       isa<VarDecl>(D)) {
341     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
342         << DMD->getVarName().getAsString();
343     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
344     return true;
345   }
346 
347   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
348                              AvoidPartialAvailabilityChecks, ClassReceiver);
349 
350   DiagnoseUnusedOfDecl(*this, D, Loc);
351 
352   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
353 
354   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
355       !isUnevaluatedContext()) {
356     // C++ [expr.prim.req.nested] p3
357     //   A local parameter shall only appear as an unevaluated operand
358     //   (Clause 8) within the constraint-expression.
359     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
360         << D;
361     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362     return true;
363   }
364 
365   return false;
366 }
367 
368 /// DiagnoseSentinelCalls - This routine checks whether a call or
369 /// message-send is to a declaration with the sentinel attribute, and
370 /// if so, it checks that the requirements of the sentinel are
371 /// satisfied.
372 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
373                                  ArrayRef<Expr *> Args) {
374   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
375   if (!attr)
376     return;
377 
378   // The number of formal parameters of the declaration.
379   unsigned numFormalParams;
380 
381   // The kind of declaration.  This is also an index into a %select in
382   // the diagnostic.
383   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
384 
385   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
386     numFormalParams = MD->param_size();
387     calleeType = CT_Method;
388   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
389     numFormalParams = FD->param_size();
390     calleeType = CT_Function;
391   } else if (isa<VarDecl>(D)) {
392     QualType type = cast<ValueDecl>(D)->getType();
393     const FunctionType *fn = nullptr;
394     if (const PointerType *ptr = type->getAs<PointerType>()) {
395       fn = ptr->getPointeeType()->getAs<FunctionType>();
396       if (!fn) return;
397       calleeType = CT_Function;
398     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
399       fn = ptr->getPointeeType()->castAs<FunctionType>();
400       calleeType = CT_Block;
401     } else {
402       return;
403     }
404 
405     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
406       numFormalParams = proto->getNumParams();
407     } else {
408       numFormalParams = 0;
409     }
410   } else {
411     return;
412   }
413 
414   // "nullPos" is the number of formal parameters at the end which
415   // effectively count as part of the variadic arguments.  This is
416   // useful if you would prefer to not have *any* formal parameters,
417   // but the language forces you to have at least one.
418   unsigned nullPos = attr->getNullPos();
419   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
420   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
421 
422   // The number of arguments which should follow the sentinel.
423   unsigned numArgsAfterSentinel = attr->getSentinel();
424 
425   // If there aren't enough arguments for all the formal parameters,
426   // the sentinel, and the args after the sentinel, complain.
427   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
428     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
429     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
430     return;
431   }
432 
433   // Otherwise, find the sentinel expression.
434   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
435   if (!sentinelExpr) return;
436   if (sentinelExpr->isValueDependent()) return;
437   if (Context.isSentinelNullExpr(sentinelExpr)) return;
438 
439   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
440   // or 'NULL' if those are actually defined in the context.  Only use
441   // 'nil' for ObjC methods, where it's much more likely that the
442   // variadic arguments form a list of object pointers.
443   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
444   std::string NullValue;
445   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
446     NullValue = "nil";
447   else if (getLangOpts().CPlusPlus11)
448     NullValue = "nullptr";
449   else if (PP.isMacroDefined("NULL"))
450     NullValue = "NULL";
451   else
452     NullValue = "(void*) 0";
453 
454   if (MissingNilLoc.isInvalid())
455     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
456   else
457     Diag(MissingNilLoc, diag::warn_missing_sentinel)
458       << int(calleeType)
459       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
460   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461 }
462 
463 SourceRange Sema::getExprRange(Expr *E) const {
464   return E ? E->getSourceRange() : SourceRange();
465 }
466 
467 //===----------------------------------------------------------------------===//
468 //  Standard Promotions and Conversions
469 //===----------------------------------------------------------------------===//
470 
471 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
472 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
473   // Handle any placeholder expressions which made it here.
474   if (E->getType()->isPlaceholderType()) {
475     ExprResult result = CheckPlaceholderExpr(E);
476     if (result.isInvalid()) return ExprError();
477     E = result.get();
478   }
479 
480   QualType Ty = E->getType();
481   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
482 
483   if (Ty->isFunctionType()) {
484     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
485       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
486         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
487           return ExprError();
488 
489     E = ImpCastExprToType(E, Context.getPointerType(Ty),
490                           CK_FunctionToPointerDecay).get();
491   } else if (Ty->isArrayType()) {
492     // In C90 mode, arrays only promote to pointers if the array expression is
493     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
494     // type 'array of type' is converted to an expression that has type 'pointer
495     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
496     // that has type 'array of type' ...".  The relevant change is "an lvalue"
497     // (C90) to "an expression" (C99).
498     //
499     // C++ 4.2p1:
500     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
501     // T" can be converted to an rvalue of type "pointer to T".
502     //
503     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
504       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
505                             CK_ArrayToPointerDecay).get();
506   }
507   return E;
508 }
509 
510 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
511   // Check to see if we are dereferencing a null pointer.  If so,
512   // and if not volatile-qualified, this is undefined behavior that the
513   // optimizer will delete, so warn about it.  People sometimes try to use this
514   // to get a deterministic trap and are surprised by clang's behavior.  This
515   // only handles the pattern "*null", which is a very syntactic check.
516   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
517   if (UO && UO->getOpcode() == UO_Deref &&
518       UO->getSubExpr()->getType()->isPointerType()) {
519     const LangAS AS =
520         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
521     if ((!isTargetAddressSpace(AS) ||
522          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
523         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
524             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
525         !UO->getType().isVolatileQualified()) {
526       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
527                             S.PDiag(diag::warn_indirection_through_null)
528                                 << UO->getSubExpr()->getSourceRange());
529       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
530                             S.PDiag(diag::note_indirection_through_null));
531     }
532   }
533 }
534 
535 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
536                                     SourceLocation AssignLoc,
537                                     const Expr* RHS) {
538   const ObjCIvarDecl *IV = OIRE->getDecl();
539   if (!IV)
540     return;
541 
542   DeclarationName MemberName = IV->getDeclName();
543   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
544   if (!Member || !Member->isStr("isa"))
545     return;
546 
547   const Expr *Base = OIRE->getBase();
548   QualType BaseType = Base->getType();
549   if (OIRE->isArrow())
550     BaseType = BaseType->getPointeeType();
551   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
552     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
553       ObjCInterfaceDecl *ClassDeclared = nullptr;
554       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
555       if (!ClassDeclared->getSuperClass()
556           && (*ClassDeclared->ivar_begin()) == IV) {
557         if (RHS) {
558           NamedDecl *ObjectSetClass =
559             S.LookupSingleName(S.TUScope,
560                                &S.Context.Idents.get("object_setClass"),
561                                SourceLocation(), S.LookupOrdinaryName);
562           if (ObjectSetClass) {
563             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
564             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
565                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
566                                               "object_setClass(")
567                 << FixItHint::CreateReplacement(
568                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
569                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
570           }
571           else
572             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
573         } else {
574           NamedDecl *ObjectGetClass =
575             S.LookupSingleName(S.TUScope,
576                                &S.Context.Idents.get("object_getClass"),
577                                SourceLocation(), S.LookupOrdinaryName);
578           if (ObjectGetClass)
579             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
580                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
581                                               "object_getClass(")
582                 << FixItHint::CreateReplacement(
583                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
584           else
585             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
586         }
587         S.Diag(IV->getLocation(), diag::note_ivar_decl);
588       }
589     }
590 }
591 
592 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
593   // Handle any placeholder expressions which made it here.
594   if (E->getType()->isPlaceholderType()) {
595     ExprResult result = CheckPlaceholderExpr(E);
596     if (result.isInvalid()) return ExprError();
597     E = result.get();
598   }
599 
600   // C++ [conv.lval]p1:
601   //   A glvalue of a non-function, non-array type T can be
602   //   converted to a prvalue.
603   if (!E->isGLValue()) return E;
604 
605   QualType T = E->getType();
606   assert(!T.isNull() && "r-value conversion on typeless expression?");
607 
608   // We don't want to throw lvalue-to-rvalue casts on top of
609   // expressions of certain types in C++.
610   if (getLangOpts().CPlusPlus &&
611       (E->getType() == Context.OverloadTy ||
612        T->isDependentType() ||
613        T->isRecordType()))
614     return E;
615 
616   // The C standard is actually really unclear on this point, and
617   // DR106 tells us what the result should be but not why.  It's
618   // generally best to say that void types just doesn't undergo
619   // lvalue-to-rvalue at all.  Note that expressions of unqualified
620   // 'void' type are never l-values, but qualified void can be.
621   if (T->isVoidType())
622     return E;
623 
624   // OpenCL usually rejects direct accesses to values of 'half' type.
625   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
626       T->isHalfType()) {
627     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
628       << 0 << T;
629     return ExprError();
630   }
631 
632   CheckForNullPointerDereference(*this, E);
633   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
634     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
635                                      &Context.Idents.get("object_getClass"),
636                                      SourceLocation(), LookupOrdinaryName);
637     if (ObjectGetClass)
638       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
639           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
640           << FixItHint::CreateReplacement(
641                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
642     else
643       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
644   }
645   else if (const ObjCIvarRefExpr *OIRE =
646             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
647     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
648 
649   // C++ [conv.lval]p1:
650   //   [...] If T is a non-class type, the type of the prvalue is the
651   //   cv-unqualified version of T. Otherwise, the type of the
652   //   rvalue is T.
653   //
654   // C99 6.3.2.1p2:
655   //   If the lvalue has qualified type, the value has the unqualified
656   //   version of the type of the lvalue; otherwise, the value has the
657   //   type of the lvalue.
658   if (T.hasQualifiers())
659     T = T.getUnqualifiedType();
660 
661   // Under the MS ABI, lock down the inheritance model now.
662   if (T->isMemberPointerType() &&
663       Context.getTargetInfo().getCXXABI().isMicrosoft())
664     (void)isCompleteType(E->getExprLoc(), T);
665 
666   ExprResult Res = CheckLValueToRValueConversionOperand(E);
667   if (Res.isInvalid())
668     return Res;
669   E = Res.get();
670 
671   // Loading a __weak object implicitly retains the value, so we need a cleanup to
672   // balance that.
673   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
674     Cleanup.setExprNeedsCleanups(true);
675 
676   // C++ [conv.lval]p3:
677   //   If T is cv std::nullptr_t, the result is a null pointer constant.
678   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
679   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
680 
681   // C11 6.3.2.1p2:
682   //   ... if the lvalue has atomic type, the value has the non-atomic version
683   //   of the type of the lvalue ...
684   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
685     T = Atomic->getValueType().getUnqualifiedType();
686     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
687                                    nullptr, VK_RValue);
688   }
689 
690   return Res;
691 }
692 
693 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
694   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
695   if (Res.isInvalid())
696     return ExprError();
697   Res = DefaultLvalueConversion(Res.get());
698   if (Res.isInvalid())
699     return ExprError();
700   return Res;
701 }
702 
703 /// CallExprUnaryConversions - a special case of an unary conversion
704 /// performed on a function designator of a call expression.
705 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
706   QualType Ty = E->getType();
707   ExprResult Res = E;
708   // Only do implicit cast for a function type, but not for a pointer
709   // to function type.
710   if (Ty->isFunctionType()) {
711     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
712                             CK_FunctionToPointerDecay).get();
713     if (Res.isInvalid())
714       return ExprError();
715   }
716   Res = DefaultLvalueConversion(Res.get());
717   if (Res.isInvalid())
718     return ExprError();
719   return Res.get();
720 }
721 
722 /// UsualUnaryConversions - Performs various conversions that are common to most
723 /// operators (C99 6.3). The conversions of array and function types are
724 /// sometimes suppressed. For example, the array->pointer conversion doesn't
725 /// apply if the array is an argument to the sizeof or address (&) operators.
726 /// In these instances, this routine should *not* be called.
727 ExprResult Sema::UsualUnaryConversions(Expr *E) {
728   // First, convert to an r-value.
729   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
730   if (Res.isInvalid())
731     return ExprError();
732   E = Res.get();
733 
734   QualType Ty = E->getType();
735   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
736 
737   // Half FP have to be promoted to float unless it is natively supported
738   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
739     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
740 
741   // Try to perform integral promotions if the object has a theoretically
742   // promotable type.
743   if (Ty->isIntegralOrUnscopedEnumerationType()) {
744     // C99 6.3.1.1p2:
745     //
746     //   The following may be used in an expression wherever an int or
747     //   unsigned int may be used:
748     //     - an object or expression with an integer type whose integer
749     //       conversion rank is less than or equal to the rank of int
750     //       and unsigned int.
751     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
752     //
753     //   If an int can represent all values of the original type, the
754     //   value is converted to an int; otherwise, it is converted to an
755     //   unsigned int. These are called the integer promotions. All
756     //   other types are unchanged by the integer promotions.
757 
758     QualType PTy = Context.isPromotableBitField(E);
759     if (!PTy.isNull()) {
760       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
761       return E;
762     }
763     if (Ty->isPromotableIntegerType()) {
764       QualType PT = Context.getPromotedIntegerType(Ty);
765       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
766       return E;
767     }
768   }
769   return E;
770 }
771 
772 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
773 /// do not have a prototype. Arguments that have type float or __fp16
774 /// are promoted to double. All other argument types are converted by
775 /// UsualUnaryConversions().
776 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
777   QualType Ty = E->getType();
778   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
779 
780   ExprResult Res = UsualUnaryConversions(E);
781   if (Res.isInvalid())
782     return ExprError();
783   E = Res.get();
784 
785   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
786   // promote to double.
787   // Note that default argument promotion applies only to float (and
788   // half/fp16); it does not apply to _Float16.
789   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
790   if (BTy && (BTy->getKind() == BuiltinType::Half ||
791               BTy->getKind() == BuiltinType::Float)) {
792     if (getLangOpts().OpenCL &&
793         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
794         if (BTy->getKind() == BuiltinType::Half) {
795             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
796         }
797     } else {
798       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
799     }
800   }
801 
802   // C++ performs lvalue-to-rvalue conversion as a default argument
803   // promotion, even on class types, but note:
804   //   C++11 [conv.lval]p2:
805   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
806   //     operand or a subexpression thereof the value contained in the
807   //     referenced object is not accessed. Otherwise, if the glvalue
808   //     has a class type, the conversion copy-initializes a temporary
809   //     of type T from the glvalue and the result of the conversion
810   //     is a prvalue for the temporary.
811   // FIXME: add some way to gate this entire thing for correctness in
812   // potentially potentially evaluated contexts.
813   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
814     ExprResult Temp = PerformCopyInitialization(
815                        InitializedEntity::InitializeTemporary(E->getType()),
816                                                 E->getExprLoc(), E);
817     if (Temp.isInvalid())
818       return ExprError();
819     E = Temp.get();
820   }
821 
822   return E;
823 }
824 
825 /// Determine the degree of POD-ness for an expression.
826 /// Incomplete types are considered POD, since this check can be performed
827 /// when we're in an unevaluated context.
828 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
829   if (Ty->isIncompleteType()) {
830     // C++11 [expr.call]p7:
831     //   After these conversions, if the argument does not have arithmetic,
832     //   enumeration, pointer, pointer to member, or class type, the program
833     //   is ill-formed.
834     //
835     // Since we've already performed array-to-pointer and function-to-pointer
836     // decay, the only such type in C++ is cv void. This also handles
837     // initializer lists as variadic arguments.
838     if (Ty->isVoidType())
839       return VAK_Invalid;
840 
841     if (Ty->isObjCObjectType())
842       return VAK_Invalid;
843     return VAK_Valid;
844   }
845 
846   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
847     return VAK_Invalid;
848 
849   if (Ty.isCXX98PODType(Context))
850     return VAK_Valid;
851 
852   // C++11 [expr.call]p7:
853   //   Passing a potentially-evaluated argument of class type (Clause 9)
854   //   having a non-trivial copy constructor, a non-trivial move constructor,
855   //   or a non-trivial destructor, with no corresponding parameter,
856   //   is conditionally-supported with implementation-defined semantics.
857   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
858     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
859       if (!Record->hasNonTrivialCopyConstructor() &&
860           !Record->hasNonTrivialMoveConstructor() &&
861           !Record->hasNonTrivialDestructor())
862         return VAK_ValidInCXX11;
863 
864   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
865     return VAK_Valid;
866 
867   if (Ty->isObjCObjectType())
868     return VAK_Invalid;
869 
870   if (getLangOpts().MSVCCompat)
871     return VAK_MSVCUndefined;
872 
873   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
874   // permitted to reject them. We should consider doing so.
875   return VAK_Undefined;
876 }
877 
878 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
879   // Don't allow one to pass an Objective-C interface to a vararg.
880   const QualType &Ty = E->getType();
881   VarArgKind VAK = isValidVarArgType(Ty);
882 
883   // Complain about passing non-POD types through varargs.
884   switch (VAK) {
885   case VAK_ValidInCXX11:
886     DiagRuntimeBehavior(
887         E->getBeginLoc(), nullptr,
888         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
889     LLVM_FALLTHROUGH;
890   case VAK_Valid:
891     if (Ty->isRecordType()) {
892       // This is unlikely to be what the user intended. If the class has a
893       // 'c_str' member function, the user probably meant to call that.
894       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
895                           PDiag(diag::warn_pass_class_arg_to_vararg)
896                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
897     }
898     break;
899 
900   case VAK_Undefined:
901   case VAK_MSVCUndefined:
902     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
903                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
904                             << getLangOpts().CPlusPlus11 << Ty << CT);
905     break;
906 
907   case VAK_Invalid:
908     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
909       Diag(E->getBeginLoc(),
910            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
911           << Ty << CT;
912     else if (Ty->isObjCObjectType())
913       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
914                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
915                               << Ty << CT);
916     else
917       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
918           << isa<InitListExpr>(E) << Ty << CT;
919     break;
920   }
921 }
922 
923 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
924 /// will create a trap if the resulting type is not a POD type.
925 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
926                                                   FunctionDecl *FDecl) {
927   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
928     // Strip the unbridged-cast placeholder expression off, if applicable.
929     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
930         (CT == VariadicMethod ||
931          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
932       E = stripARCUnbridgedCast(E);
933 
934     // Otherwise, do normal placeholder checking.
935     } else {
936       ExprResult ExprRes = CheckPlaceholderExpr(E);
937       if (ExprRes.isInvalid())
938         return ExprError();
939       E = ExprRes.get();
940     }
941   }
942 
943   ExprResult ExprRes = DefaultArgumentPromotion(E);
944   if (ExprRes.isInvalid())
945     return ExprError();
946   E = ExprRes.get();
947 
948   // Diagnostics regarding non-POD argument types are
949   // emitted along with format string checking in Sema::CheckFunctionCall().
950   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
951     // Turn this into a trap.
952     CXXScopeSpec SS;
953     SourceLocation TemplateKWLoc;
954     UnqualifiedId Name;
955     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
956                        E->getBeginLoc());
957     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
958                                           /*HasTrailingLParen=*/true,
959                                           /*IsAddressOfOperand=*/false);
960     if (TrapFn.isInvalid())
961       return ExprError();
962 
963     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
964                                     None, E->getEndLoc());
965     if (Call.isInvalid())
966       return ExprError();
967 
968     ExprResult Comma =
969         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
970     if (Comma.isInvalid())
971       return ExprError();
972     return Comma.get();
973   }
974 
975   if (!getLangOpts().CPlusPlus &&
976       RequireCompleteType(E->getExprLoc(), E->getType(),
977                           diag::err_call_incomplete_argument))
978     return ExprError();
979 
980   return E;
981 }
982 
983 /// Converts an integer to complex float type.  Helper function of
984 /// UsualArithmeticConversions()
985 ///
986 /// \return false if the integer expression is an integer type and is
987 /// successfully converted to the complex type.
988 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
989                                                   ExprResult &ComplexExpr,
990                                                   QualType IntTy,
991                                                   QualType ComplexTy,
992                                                   bool SkipCast) {
993   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
994   if (SkipCast) return false;
995   if (IntTy->isIntegerType()) {
996     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
997     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
998     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
999                                   CK_FloatingRealToComplex);
1000   } else {
1001     assert(IntTy->isComplexIntegerType());
1002     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1003                                   CK_IntegralComplexToFloatingComplex);
1004   }
1005   return false;
1006 }
1007 
1008 /// Handle arithmetic conversion with complex types.  Helper function of
1009 /// UsualArithmeticConversions()
1010 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1011                                              ExprResult &RHS, QualType LHSType,
1012                                              QualType RHSType,
1013                                              bool IsCompAssign) {
1014   // if we have an integer operand, the result is the complex type.
1015   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1016                                              /*skipCast*/false))
1017     return LHSType;
1018   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1019                                              /*skipCast*/IsCompAssign))
1020     return RHSType;
1021 
1022   // This handles complex/complex, complex/float, or float/complex.
1023   // When both operands are complex, the shorter operand is converted to the
1024   // type of the longer, and that is the type of the result. This corresponds
1025   // to what is done when combining two real floating-point operands.
1026   // The fun begins when size promotion occur across type domains.
1027   // From H&S 6.3.4: When one operand is complex and the other is a real
1028   // floating-point type, the less precise type is converted, within it's
1029   // real or complex domain, to the precision of the other type. For example,
1030   // when combining a "long double" with a "double _Complex", the
1031   // "double _Complex" is promoted to "long double _Complex".
1032 
1033   // Compute the rank of the two types, regardless of whether they are complex.
1034   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1035 
1036   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1037   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1038   QualType LHSElementType =
1039       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1040   QualType RHSElementType =
1041       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1042 
1043   QualType ResultType = S.Context.getComplexType(LHSElementType);
1044   if (Order < 0) {
1045     // Promote the precision of the LHS if not an assignment.
1046     ResultType = S.Context.getComplexType(RHSElementType);
1047     if (!IsCompAssign) {
1048       if (LHSComplexType)
1049         LHS =
1050             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1051       else
1052         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1053     }
1054   } else if (Order > 0) {
1055     // Promote the precision of the RHS.
1056     if (RHSComplexType)
1057       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1058     else
1059       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1060   }
1061   return ResultType;
1062 }
1063 
1064 /// Handle arithmetic conversion from integer to float.  Helper function
1065 /// of UsualArithmeticConversions()
1066 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1067                                            ExprResult &IntExpr,
1068                                            QualType FloatTy, QualType IntTy,
1069                                            bool ConvertFloat, bool ConvertInt) {
1070   if (IntTy->isIntegerType()) {
1071     if (ConvertInt)
1072       // Convert intExpr to the lhs floating point type.
1073       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1074                                     CK_IntegralToFloating);
1075     return FloatTy;
1076   }
1077 
1078   // Convert both sides to the appropriate complex float.
1079   assert(IntTy->isComplexIntegerType());
1080   QualType result = S.Context.getComplexType(FloatTy);
1081 
1082   // _Complex int -> _Complex float
1083   if (ConvertInt)
1084     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1085                                   CK_IntegralComplexToFloatingComplex);
1086 
1087   // float -> _Complex float
1088   if (ConvertFloat)
1089     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1090                                     CK_FloatingRealToComplex);
1091 
1092   return result;
1093 }
1094 
1095 /// Handle arithmethic conversion with floating point types.  Helper
1096 /// function of UsualArithmeticConversions()
1097 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1098                                       ExprResult &RHS, QualType LHSType,
1099                                       QualType RHSType, bool IsCompAssign) {
1100   bool LHSFloat = LHSType->isRealFloatingType();
1101   bool RHSFloat = RHSType->isRealFloatingType();
1102 
1103   // If we have two real floating types, convert the smaller operand
1104   // to the bigger result.
1105   if (LHSFloat && RHSFloat) {
1106     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1107     if (order > 0) {
1108       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1109       return LHSType;
1110     }
1111 
1112     assert(order < 0 && "illegal float comparison");
1113     if (!IsCompAssign)
1114       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1115     return RHSType;
1116   }
1117 
1118   if (LHSFloat) {
1119     // Half FP has to be promoted to float unless it is natively supported
1120     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1121       LHSType = S.Context.FloatTy;
1122 
1123     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1124                                       /*ConvertFloat=*/!IsCompAssign,
1125                                       /*ConvertInt=*/ true);
1126   }
1127   assert(RHSFloat);
1128   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1129                                     /*convertInt=*/ true,
1130                                     /*convertFloat=*/!IsCompAssign);
1131 }
1132 
1133 /// Diagnose attempts to convert between __float128 and long double if
1134 /// there is no support for such conversion. Helper function of
1135 /// UsualArithmeticConversions().
1136 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1137                                       QualType RHSType) {
1138   /*  No issue converting if at least one of the types is not a floating point
1139       type or the two types have the same rank.
1140   */
1141   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1142       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1143     return false;
1144 
1145   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1146          "The remaining types must be floating point types.");
1147 
1148   auto *LHSComplex = LHSType->getAs<ComplexType>();
1149   auto *RHSComplex = RHSType->getAs<ComplexType>();
1150 
1151   QualType LHSElemType = LHSComplex ?
1152     LHSComplex->getElementType() : LHSType;
1153   QualType RHSElemType = RHSComplex ?
1154     RHSComplex->getElementType() : RHSType;
1155 
1156   // No issue if the two types have the same representation
1157   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1158       &S.Context.getFloatTypeSemantics(RHSElemType))
1159     return false;
1160 
1161   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1162                                 RHSElemType == S.Context.LongDoubleTy);
1163   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1164                             RHSElemType == S.Context.Float128Ty);
1165 
1166   // We've handled the situation where __float128 and long double have the same
1167   // representation. We allow all conversions for all possible long double types
1168   // except PPC's double double.
1169   return Float128AndLongDouble &&
1170     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1171      &llvm::APFloat::PPCDoubleDouble());
1172 }
1173 
1174 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1175 
1176 namespace {
1177 /// These helper callbacks are placed in an anonymous namespace to
1178 /// permit their use as function template parameters.
1179 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1180   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1181 }
1182 
1183 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1184   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1185                              CK_IntegralComplexCast);
1186 }
1187 }
1188 
1189 /// Handle integer arithmetic conversions.  Helper function of
1190 /// UsualArithmeticConversions()
1191 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1192 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1193                                         ExprResult &RHS, QualType LHSType,
1194                                         QualType RHSType, bool IsCompAssign) {
1195   // The rules for this case are in C99 6.3.1.8
1196   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1197   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1198   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1199   if (LHSSigned == RHSSigned) {
1200     // Same signedness; use the higher-ranked type
1201     if (order >= 0) {
1202       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1203       return LHSType;
1204     } else if (!IsCompAssign)
1205       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1206     return RHSType;
1207   } else if (order != (LHSSigned ? 1 : -1)) {
1208     // The unsigned type has greater than or equal rank to the
1209     // signed type, so use the unsigned type
1210     if (RHSSigned) {
1211       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1212       return LHSType;
1213     } else if (!IsCompAssign)
1214       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1215     return RHSType;
1216   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1217     // The two types are different widths; if we are here, that
1218     // means the signed type is larger than the unsigned type, so
1219     // use the signed type.
1220     if (LHSSigned) {
1221       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1222       return LHSType;
1223     } else if (!IsCompAssign)
1224       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1225     return RHSType;
1226   } else {
1227     // The signed type is higher-ranked than the unsigned type,
1228     // but isn't actually any bigger (like unsigned int and long
1229     // on most 32-bit systems).  Use the unsigned type corresponding
1230     // to the signed type.
1231     QualType result =
1232       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1233     RHS = (*doRHSCast)(S, RHS.get(), result);
1234     if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), result);
1236     return result;
1237   }
1238 }
1239 
1240 /// Handle conversions with GCC complex int extension.  Helper function
1241 /// of UsualArithmeticConversions()
1242 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1243                                            ExprResult &RHS, QualType LHSType,
1244                                            QualType RHSType,
1245                                            bool IsCompAssign) {
1246   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1247   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1248 
1249   if (LHSComplexInt && RHSComplexInt) {
1250     QualType LHSEltType = LHSComplexInt->getElementType();
1251     QualType RHSEltType = RHSComplexInt->getElementType();
1252     QualType ScalarType =
1253       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1254         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1255 
1256     return S.Context.getComplexType(ScalarType);
1257   }
1258 
1259   if (LHSComplexInt) {
1260     QualType LHSEltType = LHSComplexInt->getElementType();
1261     QualType ScalarType =
1262       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1263         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1264     QualType ComplexType = S.Context.getComplexType(ScalarType);
1265     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1266                               CK_IntegralRealToComplex);
1267 
1268     return ComplexType;
1269   }
1270 
1271   assert(RHSComplexInt);
1272 
1273   QualType RHSEltType = RHSComplexInt->getElementType();
1274   QualType ScalarType =
1275     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1276       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1277   QualType ComplexType = S.Context.getComplexType(ScalarType);
1278 
1279   if (!IsCompAssign)
1280     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1281                               CK_IntegralRealToComplex);
1282   return ComplexType;
1283 }
1284 
1285 /// Return the rank of a given fixed point or integer type. The value itself
1286 /// doesn't matter, but the values must be increasing with proper increasing
1287 /// rank as described in N1169 4.1.1.
1288 static unsigned GetFixedPointRank(QualType Ty) {
1289   const auto *BTy = Ty->getAs<BuiltinType>();
1290   assert(BTy && "Expected a builtin type.");
1291 
1292   switch (BTy->getKind()) {
1293   case BuiltinType::ShortFract:
1294   case BuiltinType::UShortFract:
1295   case BuiltinType::SatShortFract:
1296   case BuiltinType::SatUShortFract:
1297     return 1;
1298   case BuiltinType::Fract:
1299   case BuiltinType::UFract:
1300   case BuiltinType::SatFract:
1301   case BuiltinType::SatUFract:
1302     return 2;
1303   case BuiltinType::LongFract:
1304   case BuiltinType::ULongFract:
1305   case BuiltinType::SatLongFract:
1306   case BuiltinType::SatULongFract:
1307     return 3;
1308   case BuiltinType::ShortAccum:
1309   case BuiltinType::UShortAccum:
1310   case BuiltinType::SatShortAccum:
1311   case BuiltinType::SatUShortAccum:
1312     return 4;
1313   case BuiltinType::Accum:
1314   case BuiltinType::UAccum:
1315   case BuiltinType::SatAccum:
1316   case BuiltinType::SatUAccum:
1317     return 5;
1318   case BuiltinType::LongAccum:
1319   case BuiltinType::ULongAccum:
1320   case BuiltinType::SatLongAccum:
1321   case BuiltinType::SatULongAccum:
1322     return 6;
1323   default:
1324     if (BTy->isInteger())
1325       return 0;
1326     llvm_unreachable("Unexpected fixed point or integer type");
1327   }
1328 }
1329 
1330 /// handleFixedPointConversion - Fixed point operations between fixed
1331 /// point types and integers or other fixed point types do not fall under
1332 /// usual arithmetic conversion since these conversions could result in loss
1333 /// of precsision (N1169 4.1.4). These operations should be calculated with
1334 /// the full precision of their result type (N1169 4.1.6.2.1).
1335 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1336                                            QualType RHSTy) {
1337   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1338          "Expected at least one of the operands to be a fixed point type");
1339   assert((LHSTy->isFixedPointOrIntegerType() ||
1340           RHSTy->isFixedPointOrIntegerType()) &&
1341          "Special fixed point arithmetic operation conversions are only "
1342          "applied to ints or other fixed point types");
1343 
1344   // If one operand has signed fixed-point type and the other operand has
1345   // unsigned fixed-point type, then the unsigned fixed-point operand is
1346   // converted to its corresponding signed fixed-point type and the resulting
1347   // type is the type of the converted operand.
1348   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1349     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1350   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1351     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1352 
1353   // The result type is the type with the highest rank, whereby a fixed-point
1354   // conversion rank is always greater than an integer conversion rank; if the
1355   // type of either of the operands is a saturating fixedpoint type, the result
1356   // type shall be the saturating fixed-point type corresponding to the type
1357   // with the highest rank; the resulting value is converted (taking into
1358   // account rounding and overflow) to the precision of the resulting type.
1359   // Same ranks between signed and unsigned types are resolved earlier, so both
1360   // types are either signed or both unsigned at this point.
1361   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1362   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1363 
1364   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1365 
1366   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1367     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1368 
1369   return ResultTy;
1370 }
1371 
1372 /// Check that the usual arithmetic conversions can be performed on this pair of
1373 /// expressions that might be of enumeration type.
1374 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1375                                            SourceLocation Loc,
1376                                            Sema::ArithConvKind ACK) {
1377   // C++2a [expr.arith.conv]p1:
1378   //   If one operand is of enumeration type and the other operand is of a
1379   //   different enumeration type or a floating-point type, this behavior is
1380   //   deprecated ([depr.arith.conv.enum]).
1381   //
1382   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1383   // Eventually we will presumably reject these cases (in C++23 onwards?).
1384   QualType L = LHS->getType(), R = RHS->getType();
1385   bool LEnum = L->isUnscopedEnumerationType(),
1386        REnum = R->isUnscopedEnumerationType();
1387   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1388   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1389       (REnum && L->isFloatingType())) {
1390     S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1391                     ? diag::warn_arith_conv_enum_float_cxx2a
1392                     : diag::warn_arith_conv_enum_float)
1393         << LHS->getSourceRange() << RHS->getSourceRange()
1394         << (int)ACK << LEnum << L << R;
1395   } else if (!IsCompAssign && LEnum && REnum &&
1396              !S.Context.hasSameUnqualifiedType(L, R)) {
1397     unsigned DiagID;
1398     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1399         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1400       // If either enumeration type is unnamed, it's less likely that the
1401       // user cares about this, but this situation is still deprecated in
1402       // C++2a. Use a different warning group.
1403       DiagID = S.getLangOpts().CPlusPlus2a
1404                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1405                     : diag::warn_arith_conv_mixed_anon_enum_types;
1406     } else if (ACK == Sema::ACK_Conditional) {
1407       // Conditional expressions are separated out because they have
1408       // historically had a different warning flag.
1409       DiagID = S.getLangOpts().CPlusPlus2a
1410                    ? diag::warn_conditional_mixed_enum_types_cxx2a
1411                    : diag::warn_conditional_mixed_enum_types;
1412     } else if (ACK == Sema::ACK_Comparison) {
1413       // Comparison expressions are separated out because they have
1414       // historically had a different warning flag.
1415       DiagID = S.getLangOpts().CPlusPlus2a
1416                    ? diag::warn_comparison_mixed_enum_types_cxx2a
1417                    : diag::warn_comparison_mixed_enum_types;
1418     } else {
1419       DiagID = S.getLangOpts().CPlusPlus2a
1420                    ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1421                    : diag::warn_arith_conv_mixed_enum_types;
1422     }
1423     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1424                         << (int)ACK << L << R;
1425   }
1426 }
1427 
1428 /// UsualArithmeticConversions - Performs various conversions that are common to
1429 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1430 /// routine returns the first non-arithmetic type found. The client is
1431 /// responsible for emitting appropriate error diagnostics.
1432 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1433                                           SourceLocation Loc,
1434                                           ArithConvKind ACK) {
1435   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1436 
1437   if (ACK != ACK_CompAssign) {
1438     LHS = UsualUnaryConversions(LHS.get());
1439     if (LHS.isInvalid())
1440       return QualType();
1441   }
1442 
1443   RHS = UsualUnaryConversions(RHS.get());
1444   if (RHS.isInvalid())
1445     return QualType();
1446 
1447   // For conversion purposes, we ignore any qualifiers.
1448   // For example, "const float" and "float" are equivalent.
1449   QualType LHSType =
1450     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1451   QualType RHSType =
1452     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1453 
1454   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1455   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1456     LHSType = AtomicLHS->getValueType();
1457 
1458   // If both types are identical, no conversion is needed.
1459   if (LHSType == RHSType)
1460     return LHSType;
1461 
1462   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1463   // The caller can deal with this (e.g. pointer + int).
1464   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1465     return QualType();
1466 
1467   // Apply unary and bitfield promotions to the LHS's type.
1468   QualType LHSUnpromotedType = LHSType;
1469   if (LHSType->isPromotableIntegerType())
1470     LHSType = Context.getPromotedIntegerType(LHSType);
1471   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1472   if (!LHSBitfieldPromoteTy.isNull())
1473     LHSType = LHSBitfieldPromoteTy;
1474   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1475     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1476 
1477   // If both types are identical, no conversion is needed.
1478   if (LHSType == RHSType)
1479     return LHSType;
1480 
1481   // At this point, we have two different arithmetic types.
1482 
1483   // Diagnose attempts to convert between __float128 and long double where
1484   // such conversions currently can't be handled.
1485   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1486     return QualType();
1487 
1488   // Handle complex types first (C99 6.3.1.8p1).
1489   if (LHSType->isComplexType() || RHSType->isComplexType())
1490     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1491                                         ACK == ACK_CompAssign);
1492 
1493   // Now handle "real" floating types (i.e. float, double, long double).
1494   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1495     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1496                                  ACK == ACK_CompAssign);
1497 
1498   // Handle GCC complex int extension.
1499   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1500     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1501                                       ACK == ACK_CompAssign);
1502 
1503   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1504     return handleFixedPointConversion(*this, LHSType, RHSType);
1505 
1506   // Finally, we have two differing integer types.
1507   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1508            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1509 }
1510 
1511 //===----------------------------------------------------------------------===//
1512 //  Semantic Analysis for various Expression Types
1513 //===----------------------------------------------------------------------===//
1514 
1515 
1516 ExprResult
1517 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1518                                 SourceLocation DefaultLoc,
1519                                 SourceLocation RParenLoc,
1520                                 Expr *ControllingExpr,
1521                                 ArrayRef<ParsedType> ArgTypes,
1522                                 ArrayRef<Expr *> ArgExprs) {
1523   unsigned NumAssocs = ArgTypes.size();
1524   assert(NumAssocs == ArgExprs.size());
1525 
1526   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1527   for (unsigned i = 0; i < NumAssocs; ++i) {
1528     if (ArgTypes[i])
1529       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1530     else
1531       Types[i] = nullptr;
1532   }
1533 
1534   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1535                                              ControllingExpr,
1536                                              llvm::makeArrayRef(Types, NumAssocs),
1537                                              ArgExprs);
1538   delete [] Types;
1539   return ER;
1540 }
1541 
1542 ExprResult
1543 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1544                                  SourceLocation DefaultLoc,
1545                                  SourceLocation RParenLoc,
1546                                  Expr *ControllingExpr,
1547                                  ArrayRef<TypeSourceInfo *> Types,
1548                                  ArrayRef<Expr *> Exprs) {
1549   unsigned NumAssocs = Types.size();
1550   assert(NumAssocs == Exprs.size());
1551 
1552   // Decay and strip qualifiers for the controlling expression type, and handle
1553   // placeholder type replacement. See committee discussion from WG14 DR423.
1554   {
1555     EnterExpressionEvaluationContext Unevaluated(
1556         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1557     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1558     if (R.isInvalid())
1559       return ExprError();
1560     ControllingExpr = R.get();
1561   }
1562 
1563   // The controlling expression is an unevaluated operand, so side effects are
1564   // likely unintended.
1565   if (!inTemplateInstantiation() &&
1566       ControllingExpr->HasSideEffects(Context, false))
1567     Diag(ControllingExpr->getExprLoc(),
1568          diag::warn_side_effects_unevaluated_context);
1569 
1570   bool TypeErrorFound = false,
1571        IsResultDependent = ControllingExpr->isTypeDependent(),
1572        ContainsUnexpandedParameterPack
1573          = ControllingExpr->containsUnexpandedParameterPack();
1574 
1575   for (unsigned i = 0; i < NumAssocs; ++i) {
1576     if (Exprs[i]->containsUnexpandedParameterPack())
1577       ContainsUnexpandedParameterPack = true;
1578 
1579     if (Types[i]) {
1580       if (Types[i]->getType()->containsUnexpandedParameterPack())
1581         ContainsUnexpandedParameterPack = true;
1582 
1583       if (Types[i]->getType()->isDependentType()) {
1584         IsResultDependent = true;
1585       } else {
1586         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1587         // complete object type other than a variably modified type."
1588         unsigned D = 0;
1589         if (Types[i]->getType()->isIncompleteType())
1590           D = diag::err_assoc_type_incomplete;
1591         else if (!Types[i]->getType()->isObjectType())
1592           D = diag::err_assoc_type_nonobject;
1593         else if (Types[i]->getType()->isVariablyModifiedType())
1594           D = diag::err_assoc_type_variably_modified;
1595 
1596         if (D != 0) {
1597           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1598             << Types[i]->getTypeLoc().getSourceRange()
1599             << Types[i]->getType();
1600           TypeErrorFound = true;
1601         }
1602 
1603         // C11 6.5.1.1p2 "No two generic associations in the same generic
1604         // selection shall specify compatible types."
1605         for (unsigned j = i+1; j < NumAssocs; ++j)
1606           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1607               Context.typesAreCompatible(Types[i]->getType(),
1608                                          Types[j]->getType())) {
1609             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1610                  diag::err_assoc_compatible_types)
1611               << Types[j]->getTypeLoc().getSourceRange()
1612               << Types[j]->getType()
1613               << Types[i]->getType();
1614             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1615                  diag::note_compat_assoc)
1616               << Types[i]->getTypeLoc().getSourceRange()
1617               << Types[i]->getType();
1618             TypeErrorFound = true;
1619           }
1620       }
1621     }
1622   }
1623   if (TypeErrorFound)
1624     return ExprError();
1625 
1626   // If we determined that the generic selection is result-dependent, don't
1627   // try to compute the result expression.
1628   if (IsResultDependent)
1629     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1630                                         Exprs, DefaultLoc, RParenLoc,
1631                                         ContainsUnexpandedParameterPack);
1632 
1633   SmallVector<unsigned, 1> CompatIndices;
1634   unsigned DefaultIndex = -1U;
1635   for (unsigned i = 0; i < NumAssocs; ++i) {
1636     if (!Types[i])
1637       DefaultIndex = i;
1638     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1639                                         Types[i]->getType()))
1640       CompatIndices.push_back(i);
1641   }
1642 
1643   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1644   // type compatible with at most one of the types named in its generic
1645   // association list."
1646   if (CompatIndices.size() > 1) {
1647     // We strip parens here because the controlling expression is typically
1648     // parenthesized in macro definitions.
1649     ControllingExpr = ControllingExpr->IgnoreParens();
1650     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1651         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1652         << (unsigned)CompatIndices.size();
1653     for (unsigned I : CompatIndices) {
1654       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1655            diag::note_compat_assoc)
1656         << Types[I]->getTypeLoc().getSourceRange()
1657         << Types[I]->getType();
1658     }
1659     return ExprError();
1660   }
1661 
1662   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1663   // its controlling expression shall have type compatible with exactly one of
1664   // the types named in its generic association list."
1665   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1666     // We strip parens here because the controlling expression is typically
1667     // parenthesized in macro definitions.
1668     ControllingExpr = ControllingExpr->IgnoreParens();
1669     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1670         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1671     return ExprError();
1672   }
1673 
1674   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1675   // type name that is compatible with the type of the controlling expression,
1676   // then the result expression of the generic selection is the expression
1677   // in that generic association. Otherwise, the result expression of the
1678   // generic selection is the expression in the default generic association."
1679   unsigned ResultIndex =
1680     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1681 
1682   return GenericSelectionExpr::Create(
1683       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1684       ContainsUnexpandedParameterPack, ResultIndex);
1685 }
1686 
1687 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1688 /// location of the token and the offset of the ud-suffix within it.
1689 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1690                                      unsigned Offset) {
1691   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1692                                         S.getLangOpts());
1693 }
1694 
1695 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1696 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1697 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1698                                                  IdentifierInfo *UDSuffix,
1699                                                  SourceLocation UDSuffixLoc,
1700                                                  ArrayRef<Expr*> Args,
1701                                                  SourceLocation LitEndLoc) {
1702   assert(Args.size() <= 2 && "too many arguments for literal operator");
1703 
1704   QualType ArgTy[2];
1705   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1706     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1707     if (ArgTy[ArgIdx]->isArrayType())
1708       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1709   }
1710 
1711   DeclarationName OpName =
1712     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1713   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1714   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1715 
1716   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1717   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1718                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1719                               /*AllowStringTemplate*/ false,
1720                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1721     return ExprError();
1722 
1723   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1724 }
1725 
1726 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1727 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1728 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1729 /// multiple tokens.  However, the common case is that StringToks points to one
1730 /// string.
1731 ///
1732 ExprResult
1733 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1734   assert(!StringToks.empty() && "Must have at least one string!");
1735 
1736   StringLiteralParser Literal(StringToks, PP);
1737   if (Literal.hadError)
1738     return ExprError();
1739 
1740   SmallVector<SourceLocation, 4> StringTokLocs;
1741   for (const Token &Tok : StringToks)
1742     StringTokLocs.push_back(Tok.getLocation());
1743 
1744   QualType CharTy = Context.CharTy;
1745   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1746   if (Literal.isWide()) {
1747     CharTy = Context.getWideCharType();
1748     Kind = StringLiteral::Wide;
1749   } else if (Literal.isUTF8()) {
1750     if (getLangOpts().Char8)
1751       CharTy = Context.Char8Ty;
1752     Kind = StringLiteral::UTF8;
1753   } else if (Literal.isUTF16()) {
1754     CharTy = Context.Char16Ty;
1755     Kind = StringLiteral::UTF16;
1756   } else if (Literal.isUTF32()) {
1757     CharTy = Context.Char32Ty;
1758     Kind = StringLiteral::UTF32;
1759   } else if (Literal.isPascal()) {
1760     CharTy = Context.UnsignedCharTy;
1761   }
1762 
1763   // Warn on initializing an array of char from a u8 string literal; this
1764   // becomes ill-formed in C++2a.
1765   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1766       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1767     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1768 
1769     // Create removals for all 'u8' prefixes in the string literal(s). This
1770     // ensures C++2a compatibility (but may change the program behavior when
1771     // built by non-Clang compilers for which the execution character set is
1772     // not always UTF-8).
1773     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1774     SourceLocation RemovalDiagLoc;
1775     for (const Token &Tok : StringToks) {
1776       if (Tok.getKind() == tok::utf8_string_literal) {
1777         if (RemovalDiagLoc.isInvalid())
1778           RemovalDiagLoc = Tok.getLocation();
1779         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1780             Tok.getLocation(),
1781             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1782                                            getSourceManager(), getLangOpts())));
1783       }
1784     }
1785     Diag(RemovalDiagLoc, RemovalDiag);
1786   }
1787 
1788   QualType StrTy =
1789       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1790 
1791   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1792   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1793                                              Kind, Literal.Pascal, StrTy,
1794                                              &StringTokLocs[0],
1795                                              StringTokLocs.size());
1796   if (Literal.getUDSuffix().empty())
1797     return Lit;
1798 
1799   // We're building a user-defined literal.
1800   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1801   SourceLocation UDSuffixLoc =
1802     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1803                    Literal.getUDSuffixOffset());
1804 
1805   // Make sure we're allowed user-defined literals here.
1806   if (!UDLScope)
1807     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1808 
1809   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1810   //   operator "" X (str, len)
1811   QualType SizeType = Context.getSizeType();
1812 
1813   DeclarationName OpName =
1814     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1815   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1816   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1817 
1818   QualType ArgTy[] = {
1819     Context.getArrayDecayedType(StrTy), SizeType
1820   };
1821 
1822   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1823   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1824                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1825                                 /*AllowStringTemplate*/ true,
1826                                 /*DiagnoseMissing*/ true)) {
1827 
1828   case LOLR_Cooked: {
1829     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1830     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1831                                                     StringTokLocs[0]);
1832     Expr *Args[] = { Lit, LenArg };
1833 
1834     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1835   }
1836 
1837   case LOLR_StringTemplate: {
1838     TemplateArgumentListInfo ExplicitArgs;
1839 
1840     unsigned CharBits = Context.getIntWidth(CharTy);
1841     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1842     llvm::APSInt Value(CharBits, CharIsUnsigned);
1843 
1844     TemplateArgument TypeArg(CharTy);
1845     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1846     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1847 
1848     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1849       Value = Lit->getCodeUnit(I);
1850       TemplateArgument Arg(Context, Value, CharTy);
1851       TemplateArgumentLocInfo ArgInfo;
1852       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1853     }
1854     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1855                                     &ExplicitArgs);
1856   }
1857   case LOLR_Raw:
1858   case LOLR_Template:
1859   case LOLR_ErrorNoDiagnostic:
1860     llvm_unreachable("unexpected literal operator lookup result");
1861   case LOLR_Error:
1862     return ExprError();
1863   }
1864   llvm_unreachable("unexpected literal operator lookup result");
1865 }
1866 
1867 DeclRefExpr *
1868 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1869                        SourceLocation Loc,
1870                        const CXXScopeSpec *SS) {
1871   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1872   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1873 }
1874 
1875 DeclRefExpr *
1876 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1877                        const DeclarationNameInfo &NameInfo,
1878                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1879                        SourceLocation TemplateKWLoc,
1880                        const TemplateArgumentListInfo *TemplateArgs) {
1881   NestedNameSpecifierLoc NNS =
1882       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1883   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1884                           TemplateArgs);
1885 }
1886 
1887 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1888   // A declaration named in an unevaluated operand never constitutes an odr-use.
1889   if (isUnevaluatedContext())
1890     return NOUR_Unevaluated;
1891 
1892   // C++2a [basic.def.odr]p4:
1893   //   A variable x whose name appears as a potentially-evaluated expression e
1894   //   is odr-used by e unless [...] x is a reference that is usable in
1895   //   constant expressions.
1896   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1897     if (VD->getType()->isReferenceType() &&
1898         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1899         VD->isUsableInConstantExpressions(Context))
1900       return NOUR_Constant;
1901   }
1902 
1903   // All remaining non-variable cases constitute an odr-use. For variables, we
1904   // need to wait and see how the expression is used.
1905   return NOUR_None;
1906 }
1907 
1908 /// BuildDeclRefExpr - Build an expression that references a
1909 /// declaration that does not require a closure capture.
1910 DeclRefExpr *
1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1912                        const DeclarationNameInfo &NameInfo,
1913                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1914                        SourceLocation TemplateKWLoc,
1915                        const TemplateArgumentListInfo *TemplateArgs) {
1916   bool RefersToCapturedVariable =
1917       isa<VarDecl>(D) &&
1918       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1919 
1920   DeclRefExpr *E = DeclRefExpr::Create(
1921       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1922       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1923   MarkDeclRefReferenced(E);
1924 
1925   // C++ [except.spec]p17:
1926   //   An exception-specification is considered to be needed when:
1927   //   - in an expression, the function is the unique lookup result or
1928   //     the selected member of a set of overloaded functions.
1929   //
1930   // We delay doing this until after we've built the function reference and
1931   // marked it as used so that:
1932   //  a) if the function is defaulted, we get errors from defining it before /
1933   //     instead of errors from computing its exception specification, and
1934   //  b) if the function is a defaulted comparison, we can use the body we
1935   //     build when defining it as input to the exception specification
1936   //     computation rather than computing a new body.
1937   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1938     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1939       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1940         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1941     }
1942   }
1943 
1944   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1945       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1946       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1947     getCurFunction()->recordUseOfWeak(E);
1948 
1949   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1950   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1951     FD = IFD->getAnonField();
1952   if (FD) {
1953     UnusedPrivateFields.remove(FD);
1954     // Just in case we're building an illegal pointer-to-member.
1955     if (FD->isBitField())
1956       E->setObjectKind(OK_BitField);
1957   }
1958 
1959   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1960   // designates a bit-field.
1961   if (auto *BD = dyn_cast<BindingDecl>(D))
1962     if (auto *BE = BD->getBinding())
1963       E->setObjectKind(BE->getObjectKind());
1964 
1965   return E;
1966 }
1967 
1968 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1969 /// possibly a list of template arguments.
1970 ///
1971 /// If this produces template arguments, it is permitted to call
1972 /// DecomposeTemplateName.
1973 ///
1974 /// This actually loses a lot of source location information for
1975 /// non-standard name kinds; we should consider preserving that in
1976 /// some way.
1977 void
1978 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1979                              TemplateArgumentListInfo &Buffer,
1980                              DeclarationNameInfo &NameInfo,
1981                              const TemplateArgumentListInfo *&TemplateArgs) {
1982   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1983     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1984     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1985 
1986     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1987                                        Id.TemplateId->NumArgs);
1988     translateTemplateArguments(TemplateArgsPtr, Buffer);
1989 
1990     TemplateName TName = Id.TemplateId->Template.get();
1991     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1992     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1993     TemplateArgs = &Buffer;
1994   } else {
1995     NameInfo = GetNameFromUnqualifiedId(Id);
1996     TemplateArgs = nullptr;
1997   }
1998 }
1999 
2000 static void emitEmptyLookupTypoDiagnostic(
2001     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2002     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2003     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2004   DeclContext *Ctx =
2005       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2006   if (!TC) {
2007     // Emit a special diagnostic for failed member lookups.
2008     // FIXME: computing the declaration context might fail here (?)
2009     if (Ctx)
2010       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2011                                                  << SS.getRange();
2012     else
2013       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2014     return;
2015   }
2016 
2017   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2018   bool DroppedSpecifier =
2019       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2020   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2021                         ? diag::note_implicit_param_decl
2022                         : diag::note_previous_decl;
2023   if (!Ctx)
2024     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2025                          SemaRef.PDiag(NoteID));
2026   else
2027     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2028                                  << Typo << Ctx << DroppedSpecifier
2029                                  << SS.getRange(),
2030                          SemaRef.PDiag(NoteID));
2031 }
2032 
2033 /// Diagnose an empty lookup.
2034 ///
2035 /// \return false if new lookup candidates were found
2036 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2037                                CorrectionCandidateCallback &CCC,
2038                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2039                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2040   DeclarationName Name = R.getLookupName();
2041 
2042   unsigned diagnostic = diag::err_undeclared_var_use;
2043   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2044   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2045       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2046       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2047     diagnostic = diag::err_undeclared_use;
2048     diagnostic_suggest = diag::err_undeclared_use_suggest;
2049   }
2050 
2051   // If the original lookup was an unqualified lookup, fake an
2052   // unqualified lookup.  This is useful when (for example) the
2053   // original lookup would not have found something because it was a
2054   // dependent name.
2055   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2056   while (DC) {
2057     if (isa<CXXRecordDecl>(DC)) {
2058       LookupQualifiedName(R, DC);
2059 
2060       if (!R.empty()) {
2061         // Don't give errors about ambiguities in this lookup.
2062         R.suppressDiagnostics();
2063 
2064         // During a default argument instantiation the CurContext points
2065         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2066         // function parameter list, hence add an explicit check.
2067         bool isDefaultArgument =
2068             !CodeSynthesisContexts.empty() &&
2069             CodeSynthesisContexts.back().Kind ==
2070                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2071         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2072         bool isInstance = CurMethod &&
2073                           CurMethod->isInstance() &&
2074                           DC == CurMethod->getParent() && !isDefaultArgument;
2075 
2076         // Give a code modification hint to insert 'this->'.
2077         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2078         // Actually quite difficult!
2079         if (getLangOpts().MSVCCompat)
2080           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2081         if (isInstance) {
2082           Diag(R.getNameLoc(), diagnostic) << Name
2083             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2084           CheckCXXThisCapture(R.getNameLoc());
2085         } else {
2086           Diag(R.getNameLoc(), diagnostic) << Name;
2087         }
2088 
2089         // Do we really want to note all of these?
2090         for (NamedDecl *D : R)
2091           Diag(D->getLocation(), diag::note_dependent_var_use);
2092 
2093         // Return true if we are inside a default argument instantiation
2094         // and the found name refers to an instance member function, otherwise
2095         // the function calling DiagnoseEmptyLookup will try to create an
2096         // implicit member call and this is wrong for default argument.
2097         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2098           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2099           return true;
2100         }
2101 
2102         // Tell the callee to try to recover.
2103         return false;
2104       }
2105 
2106       R.clear();
2107     }
2108 
2109     DC = DC->getLookupParent();
2110   }
2111 
2112   // We didn't find anything, so try to correct for a typo.
2113   TypoCorrection Corrected;
2114   if (S && Out) {
2115     SourceLocation TypoLoc = R.getNameLoc();
2116     assert(!ExplicitTemplateArgs &&
2117            "Diagnosing an empty lookup with explicit template args!");
2118     *Out = CorrectTypoDelayed(
2119         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2120         [=](const TypoCorrection &TC) {
2121           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2122                                         diagnostic, diagnostic_suggest);
2123         },
2124         nullptr, CTK_ErrorRecovery);
2125     if (*Out)
2126       return true;
2127   } else if (S &&
2128              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2129                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2130     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2131     bool DroppedSpecifier =
2132         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2133     R.setLookupName(Corrected.getCorrection());
2134 
2135     bool AcceptableWithRecovery = false;
2136     bool AcceptableWithoutRecovery = false;
2137     NamedDecl *ND = Corrected.getFoundDecl();
2138     if (ND) {
2139       if (Corrected.isOverloaded()) {
2140         OverloadCandidateSet OCS(R.getNameLoc(),
2141                                  OverloadCandidateSet::CSK_Normal);
2142         OverloadCandidateSet::iterator Best;
2143         for (NamedDecl *CD : Corrected) {
2144           if (FunctionTemplateDecl *FTD =
2145                    dyn_cast<FunctionTemplateDecl>(CD))
2146             AddTemplateOverloadCandidate(
2147                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2148                 Args, OCS);
2149           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2150             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2151               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2152                                    Args, OCS);
2153         }
2154         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2155         case OR_Success:
2156           ND = Best->FoundDecl;
2157           Corrected.setCorrectionDecl(ND);
2158           break;
2159         default:
2160           // FIXME: Arbitrarily pick the first declaration for the note.
2161           Corrected.setCorrectionDecl(ND);
2162           break;
2163         }
2164       }
2165       R.addDecl(ND);
2166       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2167         CXXRecordDecl *Record = nullptr;
2168         if (Corrected.getCorrectionSpecifier()) {
2169           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2170           Record = Ty->getAsCXXRecordDecl();
2171         }
2172         if (!Record)
2173           Record = cast<CXXRecordDecl>(
2174               ND->getDeclContext()->getRedeclContext());
2175         R.setNamingClass(Record);
2176       }
2177 
2178       auto *UnderlyingND = ND->getUnderlyingDecl();
2179       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2180                                isa<FunctionTemplateDecl>(UnderlyingND);
2181       // FIXME: If we ended up with a typo for a type name or
2182       // Objective-C class name, we're in trouble because the parser
2183       // is in the wrong place to recover. Suggest the typo
2184       // correction, but don't make it a fix-it since we're not going
2185       // to recover well anyway.
2186       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2187                                   getAsTypeTemplateDecl(UnderlyingND) ||
2188                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2189     } else {
2190       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2191       // because we aren't able to recover.
2192       AcceptableWithoutRecovery = true;
2193     }
2194 
2195     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2196       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2197                             ? diag::note_implicit_param_decl
2198                             : diag::note_previous_decl;
2199       if (SS.isEmpty())
2200         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2201                      PDiag(NoteID), AcceptableWithRecovery);
2202       else
2203         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2204                                   << Name << computeDeclContext(SS, false)
2205                                   << DroppedSpecifier << SS.getRange(),
2206                      PDiag(NoteID), AcceptableWithRecovery);
2207 
2208       // Tell the callee whether to try to recover.
2209       return !AcceptableWithRecovery;
2210     }
2211   }
2212   R.clear();
2213 
2214   // Emit a special diagnostic for failed member lookups.
2215   // FIXME: computing the declaration context might fail here (?)
2216   if (!SS.isEmpty()) {
2217     Diag(R.getNameLoc(), diag::err_no_member)
2218       << Name << computeDeclContext(SS, false)
2219       << SS.getRange();
2220     return true;
2221   }
2222 
2223   // Give up, we can't recover.
2224   Diag(R.getNameLoc(), diagnostic) << Name;
2225   return true;
2226 }
2227 
2228 /// In Microsoft mode, if we are inside a template class whose parent class has
2229 /// dependent base classes, and we can't resolve an unqualified identifier, then
2230 /// assume the identifier is a member of a dependent base class.  We can only
2231 /// recover successfully in static methods, instance methods, and other contexts
2232 /// where 'this' is available.  This doesn't precisely match MSVC's
2233 /// instantiation model, but it's close enough.
2234 static Expr *
2235 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2236                                DeclarationNameInfo &NameInfo,
2237                                SourceLocation TemplateKWLoc,
2238                                const TemplateArgumentListInfo *TemplateArgs) {
2239   // Only try to recover from lookup into dependent bases in static methods or
2240   // contexts where 'this' is available.
2241   QualType ThisType = S.getCurrentThisType();
2242   const CXXRecordDecl *RD = nullptr;
2243   if (!ThisType.isNull())
2244     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2245   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2246     RD = MD->getParent();
2247   if (!RD || !RD->hasAnyDependentBases())
2248     return nullptr;
2249 
2250   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2251   // is available, suggest inserting 'this->' as a fixit.
2252   SourceLocation Loc = NameInfo.getLoc();
2253   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2254   DB << NameInfo.getName() << RD;
2255 
2256   if (!ThisType.isNull()) {
2257     DB << FixItHint::CreateInsertion(Loc, "this->");
2258     return CXXDependentScopeMemberExpr::Create(
2259         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2260         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2261         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2262   }
2263 
2264   // Synthesize a fake NNS that points to the derived class.  This will
2265   // perform name lookup during template instantiation.
2266   CXXScopeSpec SS;
2267   auto *NNS =
2268       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2269   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2270   return DependentScopeDeclRefExpr::Create(
2271       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2272       TemplateArgs);
2273 }
2274 
2275 ExprResult
2276 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2277                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2278                         bool HasTrailingLParen, bool IsAddressOfOperand,
2279                         CorrectionCandidateCallback *CCC,
2280                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2281   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2282          "cannot be direct & operand and have a trailing lparen");
2283   if (SS.isInvalid())
2284     return ExprError();
2285 
2286   TemplateArgumentListInfo TemplateArgsBuffer;
2287 
2288   // Decompose the UnqualifiedId into the following data.
2289   DeclarationNameInfo NameInfo;
2290   const TemplateArgumentListInfo *TemplateArgs;
2291   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2292 
2293   DeclarationName Name = NameInfo.getName();
2294   IdentifierInfo *II = Name.getAsIdentifierInfo();
2295   SourceLocation NameLoc = NameInfo.getLoc();
2296 
2297   if (II && II->isEditorPlaceholder()) {
2298     // FIXME: When typed placeholders are supported we can create a typed
2299     // placeholder expression node.
2300     return ExprError();
2301   }
2302 
2303   // C++ [temp.dep.expr]p3:
2304   //   An id-expression is type-dependent if it contains:
2305   //     -- an identifier that was declared with a dependent type,
2306   //        (note: handled after lookup)
2307   //     -- a template-id that is dependent,
2308   //        (note: handled in BuildTemplateIdExpr)
2309   //     -- a conversion-function-id that specifies a dependent type,
2310   //     -- a nested-name-specifier that contains a class-name that
2311   //        names a dependent type.
2312   // Determine whether this is a member of an unknown specialization;
2313   // we need to handle these differently.
2314   bool DependentID = false;
2315   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2316       Name.getCXXNameType()->isDependentType()) {
2317     DependentID = true;
2318   } else if (SS.isSet()) {
2319     if (DeclContext *DC = computeDeclContext(SS, false)) {
2320       if (RequireCompleteDeclContext(SS, DC))
2321         return ExprError();
2322     } else {
2323       DependentID = true;
2324     }
2325   }
2326 
2327   if (DependentID)
2328     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2329                                       IsAddressOfOperand, TemplateArgs);
2330 
2331   // Perform the required lookup.
2332   LookupResult R(*this, NameInfo,
2333                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2334                      ? LookupObjCImplicitSelfParam
2335                      : LookupOrdinaryName);
2336   if (TemplateKWLoc.isValid() || TemplateArgs) {
2337     // Lookup the template name again to correctly establish the context in
2338     // which it was found. This is really unfortunate as we already did the
2339     // lookup to determine that it was a template name in the first place. If
2340     // this becomes a performance hit, we can work harder to preserve those
2341     // results until we get here but it's likely not worth it.
2342     bool MemberOfUnknownSpecialization;
2343     AssumedTemplateKind AssumedTemplate;
2344     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2345                            MemberOfUnknownSpecialization, TemplateKWLoc,
2346                            &AssumedTemplate))
2347       return ExprError();
2348 
2349     if (MemberOfUnknownSpecialization ||
2350         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2351       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2352                                         IsAddressOfOperand, TemplateArgs);
2353   } else {
2354     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2355     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2356 
2357     // If the result might be in a dependent base class, this is a dependent
2358     // id-expression.
2359     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2360       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2361                                         IsAddressOfOperand, TemplateArgs);
2362 
2363     // If this reference is in an Objective-C method, then we need to do
2364     // some special Objective-C lookup, too.
2365     if (IvarLookupFollowUp) {
2366       ExprResult E(LookupInObjCMethod(R, S, II, true));
2367       if (E.isInvalid())
2368         return ExprError();
2369 
2370       if (Expr *Ex = E.getAs<Expr>())
2371         return Ex;
2372     }
2373   }
2374 
2375   if (R.isAmbiguous())
2376     return ExprError();
2377 
2378   // This could be an implicitly declared function reference (legal in C90,
2379   // extension in C99, forbidden in C++).
2380   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2381     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2382     if (D) R.addDecl(D);
2383   }
2384 
2385   // Determine whether this name might be a candidate for
2386   // argument-dependent lookup.
2387   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2388 
2389   if (R.empty() && !ADL) {
2390     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2391       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2392                                                    TemplateKWLoc, TemplateArgs))
2393         return E;
2394     }
2395 
2396     // Don't diagnose an empty lookup for inline assembly.
2397     if (IsInlineAsmIdentifier)
2398       return ExprError();
2399 
2400     // If this name wasn't predeclared and if this is not a function
2401     // call, diagnose the problem.
2402     TypoExpr *TE = nullptr;
2403     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2404                                                        : nullptr);
2405     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2406     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2407            "Typo correction callback misconfigured");
2408     if (CCC) {
2409       // Make sure the callback knows what the typo being diagnosed is.
2410       CCC->setTypoName(II);
2411       if (SS.isValid())
2412         CCC->setTypoNNS(SS.getScopeRep());
2413     }
2414     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2415     // a template name, but we happen to have always already looked up the name
2416     // before we get here if it must be a template name.
2417     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2418                             None, &TE)) {
2419       if (TE && KeywordReplacement) {
2420         auto &State = getTypoExprState(TE);
2421         auto BestTC = State.Consumer->getNextCorrection();
2422         if (BestTC.isKeyword()) {
2423           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2424           if (State.DiagHandler)
2425             State.DiagHandler(BestTC);
2426           KeywordReplacement->startToken();
2427           KeywordReplacement->setKind(II->getTokenID());
2428           KeywordReplacement->setIdentifierInfo(II);
2429           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2430           // Clean up the state associated with the TypoExpr, since it has
2431           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2432           clearDelayedTypo(TE);
2433           // Signal that a correction to a keyword was performed by returning a
2434           // valid-but-null ExprResult.
2435           return (Expr*)nullptr;
2436         }
2437         State.Consumer->resetCorrectionStream();
2438       }
2439       return TE ? TE : ExprError();
2440     }
2441 
2442     assert(!R.empty() &&
2443            "DiagnoseEmptyLookup returned false but added no results");
2444 
2445     // If we found an Objective-C instance variable, let
2446     // LookupInObjCMethod build the appropriate expression to
2447     // reference the ivar.
2448     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2449       R.clear();
2450       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2451       // In a hopelessly buggy code, Objective-C instance variable
2452       // lookup fails and no expression will be built to reference it.
2453       if (!E.isInvalid() && !E.get())
2454         return ExprError();
2455       return E;
2456     }
2457   }
2458 
2459   // This is guaranteed from this point on.
2460   assert(!R.empty() || ADL);
2461 
2462   // Check whether this might be a C++ implicit instance member access.
2463   // C++ [class.mfct.non-static]p3:
2464   //   When an id-expression that is not part of a class member access
2465   //   syntax and not used to form a pointer to member is used in the
2466   //   body of a non-static member function of class X, if name lookup
2467   //   resolves the name in the id-expression to a non-static non-type
2468   //   member of some class C, the id-expression is transformed into a
2469   //   class member access expression using (*this) as the
2470   //   postfix-expression to the left of the . operator.
2471   //
2472   // But we don't actually need to do this for '&' operands if R
2473   // resolved to a function or overloaded function set, because the
2474   // expression is ill-formed if it actually works out to be a
2475   // non-static member function:
2476   //
2477   // C++ [expr.ref]p4:
2478   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2479   //   [t]he expression can be used only as the left-hand operand of a
2480   //   member function call.
2481   //
2482   // There are other safeguards against such uses, but it's important
2483   // to get this right here so that we don't end up making a
2484   // spuriously dependent expression if we're inside a dependent
2485   // instance method.
2486   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2487     bool MightBeImplicitMember;
2488     if (!IsAddressOfOperand)
2489       MightBeImplicitMember = true;
2490     else if (!SS.isEmpty())
2491       MightBeImplicitMember = false;
2492     else if (R.isOverloadedResult())
2493       MightBeImplicitMember = false;
2494     else if (R.isUnresolvableResult())
2495       MightBeImplicitMember = true;
2496     else
2497       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2498                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2499                               isa<MSPropertyDecl>(R.getFoundDecl());
2500 
2501     if (MightBeImplicitMember)
2502       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2503                                              R, TemplateArgs, S);
2504   }
2505 
2506   if (TemplateArgs || TemplateKWLoc.isValid()) {
2507 
2508     // In C++1y, if this is a variable template id, then check it
2509     // in BuildTemplateIdExpr().
2510     // The single lookup result must be a variable template declaration.
2511     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2512         Id.TemplateId->Kind == TNK_Var_template) {
2513       assert(R.getAsSingle<VarTemplateDecl>() &&
2514              "There should only be one declaration found.");
2515     }
2516 
2517     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2518   }
2519 
2520   return BuildDeclarationNameExpr(SS, R, ADL);
2521 }
2522 
2523 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2524 /// declaration name, generally during template instantiation.
2525 /// There's a large number of things which don't need to be done along
2526 /// this path.
2527 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2528     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2529     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2530   DeclContext *DC = computeDeclContext(SS, false);
2531   if (!DC)
2532     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2533                                      NameInfo, /*TemplateArgs=*/nullptr);
2534 
2535   if (RequireCompleteDeclContext(SS, DC))
2536     return ExprError();
2537 
2538   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2539   LookupQualifiedName(R, DC);
2540 
2541   if (R.isAmbiguous())
2542     return ExprError();
2543 
2544   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2545     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2546                                      NameInfo, /*TemplateArgs=*/nullptr);
2547 
2548   if (R.empty()) {
2549     Diag(NameInfo.getLoc(), diag::err_no_member)
2550       << NameInfo.getName() << DC << SS.getRange();
2551     return ExprError();
2552   }
2553 
2554   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2555     // Diagnose a missing typename if this resolved unambiguously to a type in
2556     // a dependent context.  If we can recover with a type, downgrade this to
2557     // a warning in Microsoft compatibility mode.
2558     unsigned DiagID = diag::err_typename_missing;
2559     if (RecoveryTSI && getLangOpts().MSVCCompat)
2560       DiagID = diag::ext_typename_missing;
2561     SourceLocation Loc = SS.getBeginLoc();
2562     auto D = Diag(Loc, DiagID);
2563     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2564       << SourceRange(Loc, NameInfo.getEndLoc());
2565 
2566     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2567     // context.
2568     if (!RecoveryTSI)
2569       return ExprError();
2570 
2571     // Only issue the fixit if we're prepared to recover.
2572     D << FixItHint::CreateInsertion(Loc, "typename ");
2573 
2574     // Recover by pretending this was an elaborated type.
2575     QualType Ty = Context.getTypeDeclType(TD);
2576     TypeLocBuilder TLB;
2577     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2578 
2579     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2580     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2581     QTL.setElaboratedKeywordLoc(SourceLocation());
2582     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2583 
2584     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2585 
2586     return ExprEmpty();
2587   }
2588 
2589   // Defend against this resolving to an implicit member access. We usually
2590   // won't get here if this might be a legitimate a class member (we end up in
2591   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2592   // a pointer-to-member or in an unevaluated context in C++11.
2593   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2594     return BuildPossibleImplicitMemberExpr(SS,
2595                                            /*TemplateKWLoc=*/SourceLocation(),
2596                                            R, /*TemplateArgs=*/nullptr, S);
2597 
2598   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2599 }
2600 
2601 /// The parser has read a name in, and Sema has detected that we're currently
2602 /// inside an ObjC method. Perform some additional checks and determine if we
2603 /// should form a reference to an ivar.
2604 ///
2605 /// Ideally, most of this would be done by lookup, but there's
2606 /// actually quite a lot of extra work involved.
2607 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2608                                         IdentifierInfo *II) {
2609   SourceLocation Loc = Lookup.getNameLoc();
2610   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2611 
2612   // Check for error condition which is already reported.
2613   if (!CurMethod)
2614     return DeclResult(true);
2615 
2616   // There are two cases to handle here.  1) scoped lookup could have failed,
2617   // in which case we should look for an ivar.  2) scoped lookup could have
2618   // found a decl, but that decl is outside the current instance method (i.e.
2619   // a global variable).  In these two cases, we do a lookup for an ivar with
2620   // this name, if the lookup sucedes, we replace it our current decl.
2621 
2622   // If we're in a class method, we don't normally want to look for
2623   // ivars.  But if we don't find anything else, and there's an
2624   // ivar, that's an error.
2625   bool IsClassMethod = CurMethod->isClassMethod();
2626 
2627   bool LookForIvars;
2628   if (Lookup.empty())
2629     LookForIvars = true;
2630   else if (IsClassMethod)
2631     LookForIvars = false;
2632   else
2633     LookForIvars = (Lookup.isSingleResult() &&
2634                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2635   ObjCInterfaceDecl *IFace = nullptr;
2636   if (LookForIvars) {
2637     IFace = CurMethod->getClassInterface();
2638     ObjCInterfaceDecl *ClassDeclared;
2639     ObjCIvarDecl *IV = nullptr;
2640     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2641       // Diagnose using an ivar in a class method.
2642       if (IsClassMethod) {
2643         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2644         return DeclResult(true);
2645       }
2646 
2647       // Diagnose the use of an ivar outside of the declaring class.
2648       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2649           !declaresSameEntity(ClassDeclared, IFace) &&
2650           !getLangOpts().DebuggerSupport)
2651         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2652 
2653       // Success.
2654       return IV;
2655     }
2656   } else if (CurMethod->isInstanceMethod()) {
2657     // We should warn if a local variable hides an ivar.
2658     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2659       ObjCInterfaceDecl *ClassDeclared;
2660       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2661         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2662             declaresSameEntity(IFace, ClassDeclared))
2663           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2664       }
2665     }
2666   } else if (Lookup.isSingleResult() &&
2667              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2668     // If accessing a stand-alone ivar in a class method, this is an error.
2669     if (const ObjCIvarDecl *IV =
2670             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2671       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2672       return DeclResult(true);
2673     }
2674   }
2675 
2676   // Didn't encounter an error, didn't find an ivar.
2677   return DeclResult(false);
2678 }
2679 
2680 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2681                                   ObjCIvarDecl *IV) {
2682   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2683   assert(CurMethod && CurMethod->isInstanceMethod() &&
2684          "should not reference ivar from this context");
2685 
2686   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2687   assert(IFace && "should not reference ivar from this context");
2688 
2689   // If we're referencing an invalid decl, just return this as a silent
2690   // error node.  The error diagnostic was already emitted on the decl.
2691   if (IV->isInvalidDecl())
2692     return ExprError();
2693 
2694   // Check if referencing a field with __attribute__((deprecated)).
2695   if (DiagnoseUseOfDecl(IV, Loc))
2696     return ExprError();
2697 
2698   // FIXME: This should use a new expr for a direct reference, don't
2699   // turn this into Self->ivar, just return a BareIVarExpr or something.
2700   IdentifierInfo &II = Context.Idents.get("self");
2701   UnqualifiedId SelfName;
2702   SelfName.setIdentifier(&II, SourceLocation());
2703   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2704   CXXScopeSpec SelfScopeSpec;
2705   SourceLocation TemplateKWLoc;
2706   ExprResult SelfExpr =
2707       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2708                         /*HasTrailingLParen=*/false,
2709                         /*IsAddressOfOperand=*/false);
2710   if (SelfExpr.isInvalid())
2711     return ExprError();
2712 
2713   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2714   if (SelfExpr.isInvalid())
2715     return ExprError();
2716 
2717   MarkAnyDeclReferenced(Loc, IV, true);
2718 
2719   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2720   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2721       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2722     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2723 
2724   ObjCIvarRefExpr *Result = new (Context)
2725       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2726                       IV->getLocation(), SelfExpr.get(), true, true);
2727 
2728   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2729     if (!isUnevaluatedContext() &&
2730         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2731       getCurFunction()->recordUseOfWeak(Result);
2732   }
2733   if (getLangOpts().ObjCAutoRefCount)
2734     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2735       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2736 
2737   return Result;
2738 }
2739 
2740 /// The parser has read a name in, and Sema has detected that we're currently
2741 /// inside an ObjC method. Perform some additional checks and determine if we
2742 /// should form a reference to an ivar. If so, build an expression referencing
2743 /// that ivar.
2744 ExprResult
2745 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2746                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2747   // FIXME: Integrate this lookup step into LookupParsedName.
2748   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2749   if (Ivar.isInvalid())
2750     return ExprError();
2751   if (Ivar.isUsable())
2752     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2753                             cast<ObjCIvarDecl>(Ivar.get()));
2754 
2755   if (Lookup.empty() && II && AllowBuiltinCreation)
2756     LookupBuiltin(Lookup);
2757 
2758   // Sentinel value saying that we didn't do anything special.
2759   return ExprResult(false);
2760 }
2761 
2762 /// Cast a base object to a member's actual type.
2763 ///
2764 /// Logically this happens in three phases:
2765 ///
2766 /// * First we cast from the base type to the naming class.
2767 ///   The naming class is the class into which we were looking
2768 ///   when we found the member;  it's the qualifier type if a
2769 ///   qualifier was provided, and otherwise it's the base type.
2770 ///
2771 /// * Next we cast from the naming class to the declaring class.
2772 ///   If the member we found was brought into a class's scope by
2773 ///   a using declaration, this is that class;  otherwise it's
2774 ///   the class declaring the member.
2775 ///
2776 /// * Finally we cast from the declaring class to the "true"
2777 ///   declaring class of the member.  This conversion does not
2778 ///   obey access control.
2779 ExprResult
2780 Sema::PerformObjectMemberConversion(Expr *From,
2781                                     NestedNameSpecifier *Qualifier,
2782                                     NamedDecl *FoundDecl,
2783                                     NamedDecl *Member) {
2784   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2785   if (!RD)
2786     return From;
2787 
2788   QualType DestRecordType;
2789   QualType DestType;
2790   QualType FromRecordType;
2791   QualType FromType = From->getType();
2792   bool PointerConversions = false;
2793   if (isa<FieldDecl>(Member)) {
2794     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2795     auto FromPtrType = FromType->getAs<PointerType>();
2796     DestRecordType = Context.getAddrSpaceQualType(
2797         DestRecordType, FromPtrType
2798                             ? FromType->getPointeeType().getAddressSpace()
2799                             : FromType.getAddressSpace());
2800 
2801     if (FromPtrType) {
2802       DestType = Context.getPointerType(DestRecordType);
2803       FromRecordType = FromPtrType->getPointeeType();
2804       PointerConversions = true;
2805     } else {
2806       DestType = DestRecordType;
2807       FromRecordType = FromType;
2808     }
2809   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2810     if (Method->isStatic())
2811       return From;
2812 
2813     DestType = Method->getThisType();
2814     DestRecordType = DestType->getPointeeType();
2815 
2816     if (FromType->getAs<PointerType>()) {
2817       FromRecordType = FromType->getPointeeType();
2818       PointerConversions = true;
2819     } else {
2820       FromRecordType = FromType;
2821       DestType = DestRecordType;
2822     }
2823 
2824     LangAS FromAS = FromRecordType.getAddressSpace();
2825     LangAS DestAS = DestRecordType.getAddressSpace();
2826     if (FromAS != DestAS) {
2827       QualType FromRecordTypeWithoutAS =
2828           Context.removeAddrSpaceQualType(FromRecordType);
2829       QualType FromTypeWithDestAS =
2830           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2831       if (PointerConversions)
2832         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2833       From = ImpCastExprToType(From, FromTypeWithDestAS,
2834                                CK_AddressSpaceConversion, From->getValueKind())
2835                  .get();
2836     }
2837   } else {
2838     // No conversion necessary.
2839     return From;
2840   }
2841 
2842   if (DestType->isDependentType() || FromType->isDependentType())
2843     return From;
2844 
2845   // If the unqualified types are the same, no conversion is necessary.
2846   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2847     return From;
2848 
2849   SourceRange FromRange = From->getSourceRange();
2850   SourceLocation FromLoc = FromRange.getBegin();
2851 
2852   ExprValueKind VK = From->getValueKind();
2853 
2854   // C++ [class.member.lookup]p8:
2855   //   [...] Ambiguities can often be resolved by qualifying a name with its
2856   //   class name.
2857   //
2858   // If the member was a qualified name and the qualified referred to a
2859   // specific base subobject type, we'll cast to that intermediate type
2860   // first and then to the object in which the member is declared. That allows
2861   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2862   //
2863   //   class Base { public: int x; };
2864   //   class Derived1 : public Base { };
2865   //   class Derived2 : public Base { };
2866   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2867   //
2868   //   void VeryDerived::f() {
2869   //     x = 17; // error: ambiguous base subobjects
2870   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2871   //   }
2872   if (Qualifier && Qualifier->getAsType()) {
2873     QualType QType = QualType(Qualifier->getAsType(), 0);
2874     assert(QType->isRecordType() && "lookup done with non-record type");
2875 
2876     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2877 
2878     // In C++98, the qualifier type doesn't actually have to be a base
2879     // type of the object type, in which case we just ignore it.
2880     // Otherwise build the appropriate casts.
2881     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2882       CXXCastPath BasePath;
2883       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2884                                        FromLoc, FromRange, &BasePath))
2885         return ExprError();
2886 
2887       if (PointerConversions)
2888         QType = Context.getPointerType(QType);
2889       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2890                                VK, &BasePath).get();
2891 
2892       FromType = QType;
2893       FromRecordType = QRecordType;
2894 
2895       // If the qualifier type was the same as the destination type,
2896       // we're done.
2897       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2898         return From;
2899     }
2900   }
2901 
2902   bool IgnoreAccess = false;
2903 
2904   // If we actually found the member through a using declaration, cast
2905   // down to the using declaration's type.
2906   //
2907   // Pointer equality is fine here because only one declaration of a
2908   // class ever has member declarations.
2909   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2910     assert(isa<UsingShadowDecl>(FoundDecl));
2911     QualType URecordType = Context.getTypeDeclType(
2912                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2913 
2914     // We only need to do this if the naming-class to declaring-class
2915     // conversion is non-trivial.
2916     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2917       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2918       CXXCastPath BasePath;
2919       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2920                                        FromLoc, FromRange, &BasePath))
2921         return ExprError();
2922 
2923       QualType UType = URecordType;
2924       if (PointerConversions)
2925         UType = Context.getPointerType(UType);
2926       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2927                                VK, &BasePath).get();
2928       FromType = UType;
2929       FromRecordType = URecordType;
2930     }
2931 
2932     // We don't do access control for the conversion from the
2933     // declaring class to the true declaring class.
2934     IgnoreAccess = true;
2935   }
2936 
2937   CXXCastPath BasePath;
2938   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2939                                    FromLoc, FromRange, &BasePath,
2940                                    IgnoreAccess))
2941     return ExprError();
2942 
2943   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2944                            VK, &BasePath);
2945 }
2946 
2947 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2948                                       const LookupResult &R,
2949                                       bool HasTrailingLParen) {
2950   // Only when used directly as the postfix-expression of a call.
2951   if (!HasTrailingLParen)
2952     return false;
2953 
2954   // Never if a scope specifier was provided.
2955   if (SS.isSet())
2956     return false;
2957 
2958   // Only in C++ or ObjC++.
2959   if (!getLangOpts().CPlusPlus)
2960     return false;
2961 
2962   // Turn off ADL when we find certain kinds of declarations during
2963   // normal lookup:
2964   for (NamedDecl *D : R) {
2965     // C++0x [basic.lookup.argdep]p3:
2966     //     -- a declaration of a class member
2967     // Since using decls preserve this property, we check this on the
2968     // original decl.
2969     if (D->isCXXClassMember())
2970       return false;
2971 
2972     // C++0x [basic.lookup.argdep]p3:
2973     //     -- a block-scope function declaration that is not a
2974     //        using-declaration
2975     // NOTE: we also trigger this for function templates (in fact, we
2976     // don't check the decl type at all, since all other decl types
2977     // turn off ADL anyway).
2978     if (isa<UsingShadowDecl>(D))
2979       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2980     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2981       return false;
2982 
2983     // C++0x [basic.lookup.argdep]p3:
2984     //     -- a declaration that is neither a function or a function
2985     //        template
2986     // And also for builtin functions.
2987     if (isa<FunctionDecl>(D)) {
2988       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2989 
2990       // But also builtin functions.
2991       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2992         return false;
2993     } else if (!isa<FunctionTemplateDecl>(D))
2994       return false;
2995   }
2996 
2997   return true;
2998 }
2999 
3000 
3001 /// Diagnoses obvious problems with the use of the given declaration
3002 /// as an expression.  This is only actually called for lookups that
3003 /// were not overloaded, and it doesn't promise that the declaration
3004 /// will in fact be used.
3005 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3006   if (D->isInvalidDecl())
3007     return true;
3008 
3009   if (isa<TypedefNameDecl>(D)) {
3010     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3011     return true;
3012   }
3013 
3014   if (isa<ObjCInterfaceDecl>(D)) {
3015     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3016     return true;
3017   }
3018 
3019   if (isa<NamespaceDecl>(D)) {
3020     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3021     return true;
3022   }
3023 
3024   return false;
3025 }
3026 
3027 // Certain multiversion types should be treated as overloaded even when there is
3028 // only one result.
3029 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3030   assert(R.isSingleResult() && "Expected only a single result");
3031   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3032   return FD &&
3033          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3034 }
3035 
3036 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3037                                           LookupResult &R, bool NeedsADL,
3038                                           bool AcceptInvalidDecl) {
3039   // If this is a single, fully-resolved result and we don't need ADL,
3040   // just build an ordinary singleton decl ref.
3041   if (!NeedsADL && R.isSingleResult() &&
3042       !R.getAsSingle<FunctionTemplateDecl>() &&
3043       !ShouldLookupResultBeMultiVersionOverload(R))
3044     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3045                                     R.getRepresentativeDecl(), nullptr,
3046                                     AcceptInvalidDecl);
3047 
3048   // We only need to check the declaration if there's exactly one
3049   // result, because in the overloaded case the results can only be
3050   // functions and function templates.
3051   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3052       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3053     return ExprError();
3054 
3055   // Otherwise, just build an unresolved lookup expression.  Suppress
3056   // any lookup-related diagnostics; we'll hash these out later, when
3057   // we've picked a target.
3058   R.suppressDiagnostics();
3059 
3060   UnresolvedLookupExpr *ULE
3061     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3062                                    SS.getWithLocInContext(Context),
3063                                    R.getLookupNameInfo(),
3064                                    NeedsADL, R.isOverloadedResult(),
3065                                    R.begin(), R.end());
3066 
3067   return ULE;
3068 }
3069 
3070 static void
3071 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3072                                    ValueDecl *var, DeclContext *DC);
3073 
3074 /// Complete semantic analysis for a reference to the given declaration.
3075 ExprResult Sema::BuildDeclarationNameExpr(
3076     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3077     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3078     bool AcceptInvalidDecl) {
3079   assert(D && "Cannot refer to a NULL declaration");
3080   assert(!isa<FunctionTemplateDecl>(D) &&
3081          "Cannot refer unambiguously to a function template");
3082 
3083   SourceLocation Loc = NameInfo.getLoc();
3084   if (CheckDeclInExpr(*this, Loc, D))
3085     return ExprError();
3086 
3087   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3088     // Specifically diagnose references to class templates that are missing
3089     // a template argument list.
3090     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3091     return ExprError();
3092   }
3093 
3094   // Make sure that we're referring to a value.
3095   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3096   if (!VD) {
3097     Diag(Loc, diag::err_ref_non_value)
3098       << D << SS.getRange();
3099     Diag(D->getLocation(), diag::note_declared_at);
3100     return ExprError();
3101   }
3102 
3103   // Check whether this declaration can be used. Note that we suppress
3104   // this check when we're going to perform argument-dependent lookup
3105   // on this function name, because this might not be the function
3106   // that overload resolution actually selects.
3107   if (DiagnoseUseOfDecl(VD, Loc))
3108     return ExprError();
3109 
3110   // Only create DeclRefExpr's for valid Decl's.
3111   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3112     return ExprError();
3113 
3114   // Handle members of anonymous structs and unions.  If we got here,
3115   // and the reference is to a class member indirect field, then this
3116   // must be the subject of a pointer-to-member expression.
3117   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3118     if (!indirectField->isCXXClassMember())
3119       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3120                                                       indirectField);
3121 
3122   {
3123     QualType type = VD->getType();
3124     if (type.isNull())
3125       return ExprError();
3126     ExprValueKind valueKind = VK_RValue;
3127 
3128     switch (D->getKind()) {
3129     // Ignore all the non-ValueDecl kinds.
3130 #define ABSTRACT_DECL(kind)
3131 #define VALUE(type, base)
3132 #define DECL(type, base) \
3133     case Decl::type:
3134 #include "clang/AST/DeclNodes.inc"
3135       llvm_unreachable("invalid value decl kind");
3136 
3137     // These shouldn't make it here.
3138     case Decl::ObjCAtDefsField:
3139       llvm_unreachable("forming non-member reference to ivar?");
3140 
3141     // Enum constants are always r-values and never references.
3142     // Unresolved using declarations are dependent.
3143     case Decl::EnumConstant:
3144     case Decl::UnresolvedUsingValue:
3145     case Decl::OMPDeclareReduction:
3146     case Decl::OMPDeclareMapper:
3147       valueKind = VK_RValue;
3148       break;
3149 
3150     // Fields and indirect fields that got here must be for
3151     // pointer-to-member expressions; we just call them l-values for
3152     // internal consistency, because this subexpression doesn't really
3153     // exist in the high-level semantics.
3154     case Decl::Field:
3155     case Decl::IndirectField:
3156     case Decl::ObjCIvar:
3157       assert(getLangOpts().CPlusPlus &&
3158              "building reference to field in C?");
3159 
3160       // These can't have reference type in well-formed programs, but
3161       // for internal consistency we do this anyway.
3162       type = type.getNonReferenceType();
3163       valueKind = VK_LValue;
3164       break;
3165 
3166     // Non-type template parameters are either l-values or r-values
3167     // depending on the type.
3168     case Decl::NonTypeTemplateParm: {
3169       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3170         type = reftype->getPointeeType();
3171         valueKind = VK_LValue; // even if the parameter is an r-value reference
3172         break;
3173       }
3174 
3175       // For non-references, we need to strip qualifiers just in case
3176       // the template parameter was declared as 'const int' or whatever.
3177       valueKind = VK_RValue;
3178       type = type.getUnqualifiedType();
3179       break;
3180     }
3181 
3182     case Decl::Var:
3183     case Decl::VarTemplateSpecialization:
3184     case Decl::VarTemplatePartialSpecialization:
3185     case Decl::Decomposition:
3186     case Decl::OMPCapturedExpr:
3187       // In C, "extern void blah;" is valid and is an r-value.
3188       if (!getLangOpts().CPlusPlus &&
3189           !type.hasQualifiers() &&
3190           type->isVoidType()) {
3191         valueKind = VK_RValue;
3192         break;
3193       }
3194       LLVM_FALLTHROUGH;
3195 
3196     case Decl::ImplicitParam:
3197     case Decl::ParmVar: {
3198       // These are always l-values.
3199       valueKind = VK_LValue;
3200       type = type.getNonReferenceType();
3201 
3202       // FIXME: Does the addition of const really only apply in
3203       // potentially-evaluated contexts? Since the variable isn't actually
3204       // captured in an unevaluated context, it seems that the answer is no.
3205       if (!isUnevaluatedContext()) {
3206         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3207         if (!CapturedType.isNull())
3208           type = CapturedType;
3209       }
3210 
3211       break;
3212     }
3213 
3214     case Decl::Binding: {
3215       // These are always lvalues.
3216       valueKind = VK_LValue;
3217       type = type.getNonReferenceType();
3218       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3219       // decides how that's supposed to work.
3220       auto *BD = cast<BindingDecl>(VD);
3221       if (BD->getDeclContext() != CurContext) {
3222         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3223         if (DD && DD->hasLocalStorage())
3224           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3225       }
3226       break;
3227     }
3228 
3229     case Decl::Function: {
3230       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3231         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3232           type = Context.BuiltinFnTy;
3233           valueKind = VK_RValue;
3234           break;
3235         }
3236       }
3237 
3238       const FunctionType *fty = type->castAs<FunctionType>();
3239 
3240       // If we're referring to a function with an __unknown_anytype
3241       // result type, make the entire expression __unknown_anytype.
3242       if (fty->getReturnType() == Context.UnknownAnyTy) {
3243         type = Context.UnknownAnyTy;
3244         valueKind = VK_RValue;
3245         break;
3246       }
3247 
3248       // Functions are l-values in C++.
3249       if (getLangOpts().CPlusPlus) {
3250         valueKind = VK_LValue;
3251         break;
3252       }
3253 
3254       // C99 DR 316 says that, if a function type comes from a
3255       // function definition (without a prototype), that type is only
3256       // used for checking compatibility. Therefore, when referencing
3257       // the function, we pretend that we don't have the full function
3258       // type.
3259       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3260           isa<FunctionProtoType>(fty))
3261         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3262                                               fty->getExtInfo());
3263 
3264       // Functions are r-values in C.
3265       valueKind = VK_RValue;
3266       break;
3267     }
3268 
3269     case Decl::CXXDeductionGuide:
3270       llvm_unreachable("building reference to deduction guide");
3271 
3272     case Decl::MSProperty:
3273       valueKind = VK_LValue;
3274       break;
3275 
3276     case Decl::CXXMethod:
3277       // If we're referring to a method with an __unknown_anytype
3278       // result type, make the entire expression __unknown_anytype.
3279       // This should only be possible with a type written directly.
3280       if (const FunctionProtoType *proto
3281             = dyn_cast<FunctionProtoType>(VD->getType()))
3282         if (proto->getReturnType() == Context.UnknownAnyTy) {
3283           type = Context.UnknownAnyTy;
3284           valueKind = VK_RValue;
3285           break;
3286         }
3287 
3288       // C++ methods are l-values if static, r-values if non-static.
3289       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3290         valueKind = VK_LValue;
3291         break;
3292       }
3293       LLVM_FALLTHROUGH;
3294 
3295     case Decl::CXXConversion:
3296     case Decl::CXXDestructor:
3297     case Decl::CXXConstructor:
3298       valueKind = VK_RValue;
3299       break;
3300     }
3301 
3302     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3303                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3304                             TemplateArgs);
3305   }
3306 }
3307 
3308 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3309                                     SmallString<32> &Target) {
3310   Target.resize(CharByteWidth * (Source.size() + 1));
3311   char *ResultPtr = &Target[0];
3312   const llvm::UTF8 *ErrorPtr;
3313   bool success =
3314       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3315   (void)success;
3316   assert(success);
3317   Target.resize(ResultPtr - &Target[0]);
3318 }
3319 
3320 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3321                                      PredefinedExpr::IdentKind IK) {
3322   // Pick the current block, lambda, captured statement or function.
3323   Decl *currentDecl = nullptr;
3324   if (const BlockScopeInfo *BSI = getCurBlock())
3325     currentDecl = BSI->TheDecl;
3326   else if (const LambdaScopeInfo *LSI = getCurLambda())
3327     currentDecl = LSI->CallOperator;
3328   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3329     currentDecl = CSI->TheCapturedDecl;
3330   else
3331     currentDecl = getCurFunctionOrMethodDecl();
3332 
3333   if (!currentDecl) {
3334     Diag(Loc, diag::ext_predef_outside_function);
3335     currentDecl = Context.getTranslationUnitDecl();
3336   }
3337 
3338   QualType ResTy;
3339   StringLiteral *SL = nullptr;
3340   if (cast<DeclContext>(currentDecl)->isDependentContext())
3341     ResTy = Context.DependentTy;
3342   else {
3343     // Pre-defined identifiers are of type char[x], where x is the length of
3344     // the string.
3345     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3346     unsigned Length = Str.length();
3347 
3348     llvm::APInt LengthI(32, Length + 1);
3349     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3350       ResTy =
3351           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3352       SmallString<32> RawChars;
3353       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3354                               Str, RawChars);
3355       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3356                                            ArrayType::Normal,
3357                                            /*IndexTypeQuals*/ 0);
3358       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3359                                  /*Pascal*/ false, ResTy, Loc);
3360     } else {
3361       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3362       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3363                                            ArrayType::Normal,
3364                                            /*IndexTypeQuals*/ 0);
3365       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3366                                  /*Pascal*/ false, ResTy, Loc);
3367     }
3368   }
3369 
3370   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3371 }
3372 
3373 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3374   PredefinedExpr::IdentKind IK;
3375 
3376   switch (Kind) {
3377   default: llvm_unreachable("Unknown simple primary expr!");
3378   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3379   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3380   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3381   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3382   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3383   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3384   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3385   }
3386 
3387   return BuildPredefinedExpr(Loc, IK);
3388 }
3389 
3390 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3391   SmallString<16> CharBuffer;
3392   bool Invalid = false;
3393   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3394   if (Invalid)
3395     return ExprError();
3396 
3397   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3398                             PP, Tok.getKind());
3399   if (Literal.hadError())
3400     return ExprError();
3401 
3402   QualType Ty;
3403   if (Literal.isWide())
3404     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3405   else if (Literal.isUTF8() && getLangOpts().Char8)
3406     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3407   else if (Literal.isUTF16())
3408     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3409   else if (Literal.isUTF32())
3410     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3411   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3412     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3413   else
3414     Ty = Context.CharTy;  // 'x' -> char in C++
3415 
3416   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3417   if (Literal.isWide())
3418     Kind = CharacterLiteral::Wide;
3419   else if (Literal.isUTF16())
3420     Kind = CharacterLiteral::UTF16;
3421   else if (Literal.isUTF32())
3422     Kind = CharacterLiteral::UTF32;
3423   else if (Literal.isUTF8())
3424     Kind = CharacterLiteral::UTF8;
3425 
3426   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3427                                              Tok.getLocation());
3428 
3429   if (Literal.getUDSuffix().empty())
3430     return Lit;
3431 
3432   // We're building a user-defined literal.
3433   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3434   SourceLocation UDSuffixLoc =
3435     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3436 
3437   // Make sure we're allowed user-defined literals here.
3438   if (!UDLScope)
3439     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3440 
3441   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3442   //   operator "" X (ch)
3443   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3444                                         Lit, Tok.getLocation());
3445 }
3446 
3447 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3448   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3449   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3450                                 Context.IntTy, Loc);
3451 }
3452 
3453 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3454                                   QualType Ty, SourceLocation Loc) {
3455   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3456 
3457   using llvm::APFloat;
3458   APFloat Val(Format);
3459 
3460   APFloat::opStatus result = Literal.GetFloatValue(Val);
3461 
3462   // Overflow is always an error, but underflow is only an error if
3463   // we underflowed to zero (APFloat reports denormals as underflow).
3464   if ((result & APFloat::opOverflow) ||
3465       ((result & APFloat::opUnderflow) && Val.isZero())) {
3466     unsigned diagnostic;
3467     SmallString<20> buffer;
3468     if (result & APFloat::opOverflow) {
3469       diagnostic = diag::warn_float_overflow;
3470       APFloat::getLargest(Format).toString(buffer);
3471     } else {
3472       diagnostic = diag::warn_float_underflow;
3473       APFloat::getSmallest(Format).toString(buffer);
3474     }
3475 
3476     S.Diag(Loc, diagnostic)
3477       << Ty
3478       << StringRef(buffer.data(), buffer.size());
3479   }
3480 
3481   bool isExact = (result == APFloat::opOK);
3482   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3483 }
3484 
3485 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3486   assert(E && "Invalid expression");
3487 
3488   if (E->isValueDependent())
3489     return false;
3490 
3491   QualType QT = E->getType();
3492   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3493     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3494     return true;
3495   }
3496 
3497   llvm::APSInt ValueAPS;
3498   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3499 
3500   if (R.isInvalid())
3501     return true;
3502 
3503   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3504   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3505     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3506         << ValueAPS.toString(10) << ValueIsPositive;
3507     return true;
3508   }
3509 
3510   return false;
3511 }
3512 
3513 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3514   // Fast path for a single digit (which is quite common).  A single digit
3515   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3516   if (Tok.getLength() == 1) {
3517     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3518     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3519   }
3520 
3521   SmallString<128> SpellingBuffer;
3522   // NumericLiteralParser wants to overread by one character.  Add padding to
3523   // the buffer in case the token is copied to the buffer.  If getSpelling()
3524   // returns a StringRef to the memory buffer, it should have a null char at
3525   // the EOF, so it is also safe.
3526   SpellingBuffer.resize(Tok.getLength() + 1);
3527 
3528   // Get the spelling of the token, which eliminates trigraphs, etc.
3529   bool Invalid = false;
3530   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3531   if (Invalid)
3532     return ExprError();
3533 
3534   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3535   if (Literal.hadError)
3536     return ExprError();
3537 
3538   if (Literal.hasUDSuffix()) {
3539     // We're building a user-defined literal.
3540     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3541     SourceLocation UDSuffixLoc =
3542       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3543 
3544     // Make sure we're allowed user-defined literals here.
3545     if (!UDLScope)
3546       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3547 
3548     QualType CookedTy;
3549     if (Literal.isFloatingLiteral()) {
3550       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3551       // long double, the literal is treated as a call of the form
3552       //   operator "" X (f L)
3553       CookedTy = Context.LongDoubleTy;
3554     } else {
3555       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3556       // unsigned long long, the literal is treated as a call of the form
3557       //   operator "" X (n ULL)
3558       CookedTy = Context.UnsignedLongLongTy;
3559     }
3560 
3561     DeclarationName OpName =
3562       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3563     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3564     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3565 
3566     SourceLocation TokLoc = Tok.getLocation();
3567 
3568     // Perform literal operator lookup to determine if we're building a raw
3569     // literal or a cooked one.
3570     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3571     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3572                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3573                                   /*AllowStringTemplate*/ false,
3574                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3575     case LOLR_ErrorNoDiagnostic:
3576       // Lookup failure for imaginary constants isn't fatal, there's still the
3577       // GNU extension producing _Complex types.
3578       break;
3579     case LOLR_Error:
3580       return ExprError();
3581     case LOLR_Cooked: {
3582       Expr *Lit;
3583       if (Literal.isFloatingLiteral()) {
3584         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3585       } else {
3586         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3587         if (Literal.GetIntegerValue(ResultVal))
3588           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3589               << /* Unsigned */ 1;
3590         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3591                                      Tok.getLocation());
3592       }
3593       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3594     }
3595 
3596     case LOLR_Raw: {
3597       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3598       // literal is treated as a call of the form
3599       //   operator "" X ("n")
3600       unsigned Length = Literal.getUDSuffixOffset();
3601       QualType StrTy = Context.getConstantArrayType(
3602           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3603           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3604       Expr *Lit = StringLiteral::Create(
3605           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3606           /*Pascal*/false, StrTy, &TokLoc, 1);
3607       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3608     }
3609 
3610     case LOLR_Template: {
3611       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3612       // template), L is treated as a call fo the form
3613       //   operator "" X <'c1', 'c2', ... 'ck'>()
3614       // where n is the source character sequence c1 c2 ... ck.
3615       TemplateArgumentListInfo ExplicitArgs;
3616       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3617       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3618       llvm::APSInt Value(CharBits, CharIsUnsigned);
3619       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3620         Value = TokSpelling[I];
3621         TemplateArgument Arg(Context, Value, Context.CharTy);
3622         TemplateArgumentLocInfo ArgInfo;
3623         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3624       }
3625       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3626                                       &ExplicitArgs);
3627     }
3628     case LOLR_StringTemplate:
3629       llvm_unreachable("unexpected literal operator lookup result");
3630     }
3631   }
3632 
3633   Expr *Res;
3634 
3635   if (Literal.isFixedPointLiteral()) {
3636     QualType Ty;
3637 
3638     if (Literal.isAccum) {
3639       if (Literal.isHalf) {
3640         Ty = Context.ShortAccumTy;
3641       } else if (Literal.isLong) {
3642         Ty = Context.LongAccumTy;
3643       } else {
3644         Ty = Context.AccumTy;
3645       }
3646     } else if (Literal.isFract) {
3647       if (Literal.isHalf) {
3648         Ty = Context.ShortFractTy;
3649       } else if (Literal.isLong) {
3650         Ty = Context.LongFractTy;
3651       } else {
3652         Ty = Context.FractTy;
3653       }
3654     }
3655 
3656     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3657 
3658     bool isSigned = !Literal.isUnsigned;
3659     unsigned scale = Context.getFixedPointScale(Ty);
3660     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3661 
3662     llvm::APInt Val(bit_width, 0, isSigned);
3663     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3664     bool ValIsZero = Val.isNullValue() && !Overflowed;
3665 
3666     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3667     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3668       // Clause 6.4.4 - The value of a constant shall be in the range of
3669       // representable values for its type, with exception for constants of a
3670       // fract type with a value of exactly 1; such a constant shall denote
3671       // the maximal value for the type.
3672       --Val;
3673     else if (Val.ugt(MaxVal) || Overflowed)
3674       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3675 
3676     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3677                                               Tok.getLocation(), scale);
3678   } else if (Literal.isFloatingLiteral()) {
3679     QualType Ty;
3680     if (Literal.isHalf){
3681       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3682         Ty = Context.HalfTy;
3683       else {
3684         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3685         return ExprError();
3686       }
3687     } else if (Literal.isFloat)
3688       Ty = Context.FloatTy;
3689     else if (Literal.isLong)
3690       Ty = Context.LongDoubleTy;
3691     else if (Literal.isFloat16)
3692       Ty = Context.Float16Ty;
3693     else if (Literal.isFloat128)
3694       Ty = Context.Float128Ty;
3695     else
3696       Ty = Context.DoubleTy;
3697 
3698     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3699 
3700     if (Ty == Context.DoubleTy) {
3701       if (getLangOpts().SinglePrecisionConstants) {
3702         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3703         if (BTy->getKind() != BuiltinType::Float) {
3704           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3705         }
3706       } else if (getLangOpts().OpenCL &&
3707                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3708         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3709         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3710         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3711       }
3712     }
3713   } else if (!Literal.isIntegerLiteral()) {
3714     return ExprError();
3715   } else {
3716     QualType Ty;
3717 
3718     // 'long long' is a C99 or C++11 feature.
3719     if (!getLangOpts().C99 && Literal.isLongLong) {
3720       if (getLangOpts().CPlusPlus)
3721         Diag(Tok.getLocation(),
3722              getLangOpts().CPlusPlus11 ?
3723              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3724       else
3725         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3726     }
3727 
3728     // Get the value in the widest-possible width.
3729     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3730     llvm::APInt ResultVal(MaxWidth, 0);
3731 
3732     if (Literal.GetIntegerValue(ResultVal)) {
3733       // If this value didn't fit into uintmax_t, error and force to ull.
3734       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3735           << /* Unsigned */ 1;
3736       Ty = Context.UnsignedLongLongTy;
3737       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3738              "long long is not intmax_t?");
3739     } else {
3740       // If this value fits into a ULL, try to figure out what else it fits into
3741       // according to the rules of C99 6.4.4.1p5.
3742 
3743       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3744       // be an unsigned int.
3745       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3746 
3747       // Check from smallest to largest, picking the smallest type we can.
3748       unsigned Width = 0;
3749 
3750       // Microsoft specific integer suffixes are explicitly sized.
3751       if (Literal.MicrosoftInteger) {
3752         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3753           Width = 8;
3754           Ty = Context.CharTy;
3755         } else {
3756           Width = Literal.MicrosoftInteger;
3757           Ty = Context.getIntTypeForBitwidth(Width,
3758                                              /*Signed=*/!Literal.isUnsigned);
3759         }
3760       }
3761 
3762       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3763         // Are int/unsigned possibilities?
3764         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3765 
3766         // Does it fit in a unsigned int?
3767         if (ResultVal.isIntN(IntSize)) {
3768           // Does it fit in a signed int?
3769           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3770             Ty = Context.IntTy;
3771           else if (AllowUnsigned)
3772             Ty = Context.UnsignedIntTy;
3773           Width = IntSize;
3774         }
3775       }
3776 
3777       // Are long/unsigned long possibilities?
3778       if (Ty.isNull() && !Literal.isLongLong) {
3779         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3780 
3781         // Does it fit in a unsigned long?
3782         if (ResultVal.isIntN(LongSize)) {
3783           // Does it fit in a signed long?
3784           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3785             Ty = Context.LongTy;
3786           else if (AllowUnsigned)
3787             Ty = Context.UnsignedLongTy;
3788           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3789           // is compatible.
3790           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3791             const unsigned LongLongSize =
3792                 Context.getTargetInfo().getLongLongWidth();
3793             Diag(Tok.getLocation(),
3794                  getLangOpts().CPlusPlus
3795                      ? Literal.isLong
3796                            ? diag::warn_old_implicitly_unsigned_long_cxx
3797                            : /*C++98 UB*/ diag::
3798                                  ext_old_implicitly_unsigned_long_cxx
3799                      : diag::warn_old_implicitly_unsigned_long)
3800                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3801                                             : /*will be ill-formed*/ 1);
3802             Ty = Context.UnsignedLongTy;
3803           }
3804           Width = LongSize;
3805         }
3806       }
3807 
3808       // Check long long if needed.
3809       if (Ty.isNull()) {
3810         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3811 
3812         // Does it fit in a unsigned long long?
3813         if (ResultVal.isIntN(LongLongSize)) {
3814           // Does it fit in a signed long long?
3815           // To be compatible with MSVC, hex integer literals ending with the
3816           // LL or i64 suffix are always signed in Microsoft mode.
3817           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3818               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3819             Ty = Context.LongLongTy;
3820           else if (AllowUnsigned)
3821             Ty = Context.UnsignedLongLongTy;
3822           Width = LongLongSize;
3823         }
3824       }
3825 
3826       // If we still couldn't decide a type, we probably have something that
3827       // does not fit in a signed long long, but has no U suffix.
3828       if (Ty.isNull()) {
3829         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3830         Ty = Context.UnsignedLongLongTy;
3831         Width = Context.getTargetInfo().getLongLongWidth();
3832       }
3833 
3834       if (ResultVal.getBitWidth() != Width)
3835         ResultVal = ResultVal.trunc(Width);
3836     }
3837     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3838   }
3839 
3840   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3841   if (Literal.isImaginary) {
3842     Res = new (Context) ImaginaryLiteral(Res,
3843                                         Context.getComplexType(Res->getType()));
3844 
3845     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3846   }
3847   return Res;
3848 }
3849 
3850 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3851   assert(E && "ActOnParenExpr() missing expr");
3852   return new (Context) ParenExpr(L, R, E);
3853 }
3854 
3855 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3856                                          SourceLocation Loc,
3857                                          SourceRange ArgRange) {
3858   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3859   // scalar or vector data type argument..."
3860   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3861   // type (C99 6.2.5p18) or void.
3862   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3863     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3864       << T << ArgRange;
3865     return true;
3866   }
3867 
3868   assert((T->isVoidType() || !T->isIncompleteType()) &&
3869          "Scalar types should always be complete");
3870   return false;
3871 }
3872 
3873 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3874                                            SourceLocation Loc,
3875                                            SourceRange ArgRange,
3876                                            UnaryExprOrTypeTrait TraitKind) {
3877   // Invalid types must be hard errors for SFINAE in C++.
3878   if (S.LangOpts.CPlusPlus)
3879     return true;
3880 
3881   // C99 6.5.3.4p1:
3882   if (T->isFunctionType() &&
3883       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3884        TraitKind == UETT_PreferredAlignOf)) {
3885     // sizeof(function)/alignof(function) is allowed as an extension.
3886     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3887       << TraitKind << ArgRange;
3888     return false;
3889   }
3890 
3891   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3892   // this is an error (OpenCL v1.1 s6.3.k)
3893   if (T->isVoidType()) {
3894     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3895                                         : diag::ext_sizeof_alignof_void_type;
3896     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3897     return false;
3898   }
3899 
3900   return true;
3901 }
3902 
3903 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3904                                              SourceLocation Loc,
3905                                              SourceRange ArgRange,
3906                                              UnaryExprOrTypeTrait TraitKind) {
3907   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3908   // runtime doesn't allow it.
3909   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3910     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3911       << T << (TraitKind == UETT_SizeOf)
3912       << ArgRange;
3913     return true;
3914   }
3915 
3916   return false;
3917 }
3918 
3919 /// Check whether E is a pointer from a decayed array type (the decayed
3920 /// pointer type is equal to T) and emit a warning if it is.
3921 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3922                                      Expr *E) {
3923   // Don't warn if the operation changed the type.
3924   if (T != E->getType())
3925     return;
3926 
3927   // Now look for array decays.
3928   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3929   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3930     return;
3931 
3932   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3933                                              << ICE->getType()
3934                                              << ICE->getSubExpr()->getType();
3935 }
3936 
3937 /// Check the constraints on expression operands to unary type expression
3938 /// and type traits.
3939 ///
3940 /// Completes any types necessary and validates the constraints on the operand
3941 /// expression. The logic mostly mirrors the type-based overload, but may modify
3942 /// the expression as it completes the type for that expression through template
3943 /// instantiation, etc.
3944 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3945                                             UnaryExprOrTypeTrait ExprKind) {
3946   QualType ExprTy = E->getType();
3947   assert(!ExprTy->isReferenceType());
3948 
3949   bool IsUnevaluatedOperand =
3950       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3951        ExprKind == UETT_PreferredAlignOf);
3952   if (IsUnevaluatedOperand) {
3953     ExprResult Result = CheckUnevaluatedOperand(E);
3954     if (Result.isInvalid())
3955       return true;
3956     E = Result.get();
3957   }
3958 
3959   if (ExprKind == UETT_VecStep)
3960     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3961                                         E->getSourceRange());
3962 
3963   // Whitelist some types as extensions
3964   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3965                                       E->getSourceRange(), ExprKind))
3966     return false;
3967 
3968   // 'alignof' applied to an expression only requires the base element type of
3969   // the expression to be complete. 'sizeof' requires the expression's type to
3970   // be complete (and will attempt to complete it if it's an array of unknown
3971   // bound).
3972   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3973     if (RequireCompleteType(E->getExprLoc(),
3974                             Context.getBaseElementType(E->getType()),
3975                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3976                             E->getSourceRange()))
3977       return true;
3978   } else {
3979     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3980                                 ExprKind, E->getSourceRange()))
3981       return true;
3982   }
3983 
3984   // Completing the expression's type may have changed it.
3985   ExprTy = E->getType();
3986   assert(!ExprTy->isReferenceType());
3987 
3988   if (ExprTy->isFunctionType()) {
3989     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3990       << ExprKind << E->getSourceRange();
3991     return true;
3992   }
3993 
3994   // The operand for sizeof and alignof is in an unevaluated expression context,
3995   // so side effects could result in unintended consequences.
3996   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3997       E->HasSideEffects(Context, false))
3998     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3999 
4000   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4001                                        E->getSourceRange(), ExprKind))
4002     return true;
4003 
4004   if (ExprKind == UETT_SizeOf) {
4005     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4006       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4007         QualType OType = PVD->getOriginalType();
4008         QualType Type = PVD->getType();
4009         if (Type->isPointerType() && OType->isArrayType()) {
4010           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4011             << Type << OType;
4012           Diag(PVD->getLocation(), diag::note_declared_at);
4013         }
4014       }
4015     }
4016 
4017     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4018     // decays into a pointer and returns an unintended result. This is most
4019     // likely a typo for "sizeof(array) op x".
4020     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4021       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4022                                BO->getLHS());
4023       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4024                                BO->getRHS());
4025     }
4026   }
4027 
4028   return false;
4029 }
4030 
4031 /// Check the constraints on operands to unary expression and type
4032 /// traits.
4033 ///
4034 /// This will complete any types necessary, and validate the various constraints
4035 /// on those operands.
4036 ///
4037 /// The UsualUnaryConversions() function is *not* called by this routine.
4038 /// C99 6.3.2.1p[2-4] all state:
4039 ///   Except when it is the operand of the sizeof operator ...
4040 ///
4041 /// C++ [expr.sizeof]p4
4042 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4043 ///   standard conversions are not applied to the operand of sizeof.
4044 ///
4045 /// This policy is followed for all of the unary trait expressions.
4046 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4047                                             SourceLocation OpLoc,
4048                                             SourceRange ExprRange,
4049                                             UnaryExprOrTypeTrait ExprKind) {
4050   if (ExprType->isDependentType())
4051     return false;
4052 
4053   // C++ [expr.sizeof]p2:
4054   //     When applied to a reference or a reference type, the result
4055   //     is the size of the referenced type.
4056   // C++11 [expr.alignof]p3:
4057   //     When alignof is applied to a reference type, the result
4058   //     shall be the alignment of the referenced type.
4059   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4060     ExprType = Ref->getPointeeType();
4061 
4062   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4063   //   When alignof or _Alignof is applied to an array type, the result
4064   //   is the alignment of the element type.
4065   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4066       ExprKind == UETT_OpenMPRequiredSimdAlign)
4067     ExprType = Context.getBaseElementType(ExprType);
4068 
4069   if (ExprKind == UETT_VecStep)
4070     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4071 
4072   // Whitelist some types as extensions
4073   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4074                                       ExprKind))
4075     return false;
4076 
4077   if (RequireCompleteType(OpLoc, ExprType,
4078                           diag::err_sizeof_alignof_incomplete_type,
4079                           ExprKind, ExprRange))
4080     return true;
4081 
4082   if (ExprType->isFunctionType()) {
4083     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4084       << ExprKind << ExprRange;
4085     return true;
4086   }
4087 
4088   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4089                                        ExprKind))
4090     return true;
4091 
4092   return false;
4093 }
4094 
4095 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4096   // Cannot know anything else if the expression is dependent.
4097   if (E->isTypeDependent())
4098     return false;
4099 
4100   if (E->getObjectKind() == OK_BitField) {
4101     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4102        << 1 << E->getSourceRange();
4103     return true;
4104   }
4105 
4106   ValueDecl *D = nullptr;
4107   Expr *Inner = E->IgnoreParens();
4108   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4109     D = DRE->getDecl();
4110   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4111     D = ME->getMemberDecl();
4112   }
4113 
4114   // If it's a field, require the containing struct to have a
4115   // complete definition so that we can compute the layout.
4116   //
4117   // This can happen in C++11 onwards, either by naming the member
4118   // in a way that is not transformed into a member access expression
4119   // (in an unevaluated operand, for instance), or by naming the member
4120   // in a trailing-return-type.
4121   //
4122   // For the record, since __alignof__ on expressions is a GCC
4123   // extension, GCC seems to permit this but always gives the
4124   // nonsensical answer 0.
4125   //
4126   // We don't really need the layout here --- we could instead just
4127   // directly check for all the appropriate alignment-lowing
4128   // attributes --- but that would require duplicating a lot of
4129   // logic that just isn't worth duplicating for such a marginal
4130   // use-case.
4131   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4132     // Fast path this check, since we at least know the record has a
4133     // definition if we can find a member of it.
4134     if (!FD->getParent()->isCompleteDefinition()) {
4135       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4136         << E->getSourceRange();
4137       return true;
4138     }
4139 
4140     // Otherwise, if it's a field, and the field doesn't have
4141     // reference type, then it must have a complete type (or be a
4142     // flexible array member, which we explicitly want to
4143     // white-list anyway), which makes the following checks trivial.
4144     if (!FD->getType()->isReferenceType())
4145       return false;
4146   }
4147 
4148   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4149 }
4150 
4151 bool Sema::CheckVecStepExpr(Expr *E) {
4152   E = E->IgnoreParens();
4153 
4154   // Cannot know anything else if the expression is dependent.
4155   if (E->isTypeDependent())
4156     return false;
4157 
4158   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4159 }
4160 
4161 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4162                                         CapturingScopeInfo *CSI) {
4163   assert(T->isVariablyModifiedType());
4164   assert(CSI != nullptr);
4165 
4166   // We're going to walk down into the type and look for VLA expressions.
4167   do {
4168     const Type *Ty = T.getTypePtr();
4169     switch (Ty->getTypeClass()) {
4170 #define TYPE(Class, Base)
4171 #define ABSTRACT_TYPE(Class, Base)
4172 #define NON_CANONICAL_TYPE(Class, Base)
4173 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4175 #include "clang/AST/TypeNodes.inc"
4176       T = QualType();
4177       break;
4178     // These types are never variably-modified.
4179     case Type::Builtin:
4180     case Type::Complex:
4181     case Type::Vector:
4182     case Type::ExtVector:
4183     case Type::Record:
4184     case Type::Enum:
4185     case Type::Elaborated:
4186     case Type::TemplateSpecialization:
4187     case Type::ObjCObject:
4188     case Type::ObjCInterface:
4189     case Type::ObjCObjectPointer:
4190     case Type::ObjCTypeParam:
4191     case Type::Pipe:
4192       llvm_unreachable("type class is never variably-modified!");
4193     case Type::Adjusted:
4194       T = cast<AdjustedType>(Ty)->getOriginalType();
4195       break;
4196     case Type::Decayed:
4197       T = cast<DecayedType>(Ty)->getPointeeType();
4198       break;
4199     case Type::Pointer:
4200       T = cast<PointerType>(Ty)->getPointeeType();
4201       break;
4202     case Type::BlockPointer:
4203       T = cast<BlockPointerType>(Ty)->getPointeeType();
4204       break;
4205     case Type::LValueReference:
4206     case Type::RValueReference:
4207       T = cast<ReferenceType>(Ty)->getPointeeType();
4208       break;
4209     case Type::MemberPointer:
4210       T = cast<MemberPointerType>(Ty)->getPointeeType();
4211       break;
4212     case Type::ConstantArray:
4213     case Type::IncompleteArray:
4214       // Losing element qualification here is fine.
4215       T = cast<ArrayType>(Ty)->getElementType();
4216       break;
4217     case Type::VariableArray: {
4218       // Losing element qualification here is fine.
4219       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4220 
4221       // Unknown size indication requires no size computation.
4222       // Otherwise, evaluate and record it.
4223       auto Size = VAT->getSizeExpr();
4224       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4225           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4226         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4227 
4228       T = VAT->getElementType();
4229       break;
4230     }
4231     case Type::FunctionProto:
4232     case Type::FunctionNoProto:
4233       T = cast<FunctionType>(Ty)->getReturnType();
4234       break;
4235     case Type::Paren:
4236     case Type::TypeOf:
4237     case Type::UnaryTransform:
4238     case Type::Attributed:
4239     case Type::SubstTemplateTypeParm:
4240     case Type::PackExpansion:
4241     case Type::MacroQualified:
4242       // Keep walking after single level desugaring.
4243       T = T.getSingleStepDesugaredType(Context);
4244       break;
4245     case Type::Typedef:
4246       T = cast<TypedefType>(Ty)->desugar();
4247       break;
4248     case Type::Decltype:
4249       T = cast<DecltypeType>(Ty)->desugar();
4250       break;
4251     case Type::Auto:
4252     case Type::DeducedTemplateSpecialization:
4253       T = cast<DeducedType>(Ty)->getDeducedType();
4254       break;
4255     case Type::TypeOfExpr:
4256       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4257       break;
4258     case Type::Atomic:
4259       T = cast<AtomicType>(Ty)->getValueType();
4260       break;
4261     }
4262   } while (!T.isNull() && T->isVariablyModifiedType());
4263 }
4264 
4265 /// Build a sizeof or alignof expression given a type operand.
4266 ExprResult
4267 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4268                                      SourceLocation OpLoc,
4269                                      UnaryExprOrTypeTrait ExprKind,
4270                                      SourceRange R) {
4271   if (!TInfo)
4272     return ExprError();
4273 
4274   QualType T = TInfo->getType();
4275 
4276   if (!T->isDependentType() &&
4277       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4278     return ExprError();
4279 
4280   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4281     if (auto *TT = T->getAs<TypedefType>()) {
4282       for (auto I = FunctionScopes.rbegin(),
4283                 E = std::prev(FunctionScopes.rend());
4284            I != E; ++I) {
4285         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4286         if (CSI == nullptr)
4287           break;
4288         DeclContext *DC = nullptr;
4289         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4290           DC = LSI->CallOperator;
4291         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4292           DC = CRSI->TheCapturedDecl;
4293         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4294           DC = BSI->TheDecl;
4295         if (DC) {
4296           if (DC->containsDecl(TT->getDecl()))
4297             break;
4298           captureVariablyModifiedType(Context, T, CSI);
4299         }
4300       }
4301     }
4302   }
4303 
4304   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4305   return new (Context) UnaryExprOrTypeTraitExpr(
4306       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4307 }
4308 
4309 /// Build a sizeof or alignof expression given an expression
4310 /// operand.
4311 ExprResult
4312 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4313                                      UnaryExprOrTypeTrait ExprKind) {
4314   ExprResult PE = CheckPlaceholderExpr(E);
4315   if (PE.isInvalid())
4316     return ExprError();
4317 
4318   E = PE.get();
4319 
4320   // Verify that the operand is valid.
4321   bool isInvalid = false;
4322   if (E->isTypeDependent()) {
4323     // Delay type-checking for type-dependent expressions.
4324   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4325     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4326   } else if (ExprKind == UETT_VecStep) {
4327     isInvalid = CheckVecStepExpr(E);
4328   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4329       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4330       isInvalid = true;
4331   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4332     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4333     isInvalid = true;
4334   } else {
4335     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4336   }
4337 
4338   if (isInvalid)
4339     return ExprError();
4340 
4341   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4342     PE = TransformToPotentiallyEvaluated(E);
4343     if (PE.isInvalid()) return ExprError();
4344     E = PE.get();
4345   }
4346 
4347   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4348   return new (Context) UnaryExprOrTypeTraitExpr(
4349       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4350 }
4351 
4352 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4353 /// expr and the same for @c alignof and @c __alignof
4354 /// Note that the ArgRange is invalid if isType is false.
4355 ExprResult
4356 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4357                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4358                                     void *TyOrEx, SourceRange ArgRange) {
4359   // If error parsing type, ignore.
4360   if (!TyOrEx) return ExprError();
4361 
4362   if (IsType) {
4363     TypeSourceInfo *TInfo;
4364     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4365     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4366   }
4367 
4368   Expr *ArgEx = (Expr *)TyOrEx;
4369   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4370   return Result;
4371 }
4372 
4373 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4374                                      bool IsReal) {
4375   if (V.get()->isTypeDependent())
4376     return S.Context.DependentTy;
4377 
4378   // _Real and _Imag are only l-values for normal l-values.
4379   if (V.get()->getObjectKind() != OK_Ordinary) {
4380     V = S.DefaultLvalueConversion(V.get());
4381     if (V.isInvalid())
4382       return QualType();
4383   }
4384 
4385   // These operators return the element type of a complex type.
4386   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4387     return CT->getElementType();
4388 
4389   // Otherwise they pass through real integer and floating point types here.
4390   if (V.get()->getType()->isArithmeticType())
4391     return V.get()->getType();
4392 
4393   // Test for placeholders.
4394   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4395   if (PR.isInvalid()) return QualType();
4396   if (PR.get() != V.get()) {
4397     V = PR;
4398     return CheckRealImagOperand(S, V, Loc, IsReal);
4399   }
4400 
4401   // Reject anything else.
4402   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4403     << (IsReal ? "__real" : "__imag");
4404   return QualType();
4405 }
4406 
4407 
4408 
4409 ExprResult
4410 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4411                           tok::TokenKind Kind, Expr *Input) {
4412   UnaryOperatorKind Opc;
4413   switch (Kind) {
4414   default: llvm_unreachable("Unknown unary op!");
4415   case tok::plusplus:   Opc = UO_PostInc; break;
4416   case tok::minusminus: Opc = UO_PostDec; break;
4417   }
4418 
4419   // Since this might is a postfix expression, get rid of ParenListExprs.
4420   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4421   if (Result.isInvalid()) return ExprError();
4422   Input = Result.get();
4423 
4424   return BuildUnaryOp(S, OpLoc, Opc, Input);
4425 }
4426 
4427 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4428 ///
4429 /// \return true on error
4430 static bool checkArithmeticOnObjCPointer(Sema &S,
4431                                          SourceLocation opLoc,
4432                                          Expr *op) {
4433   assert(op->getType()->isObjCObjectPointerType());
4434   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4435       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4436     return false;
4437 
4438   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4439     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4440     << op->getSourceRange();
4441   return true;
4442 }
4443 
4444 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4445   auto *BaseNoParens = Base->IgnoreParens();
4446   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4447     return MSProp->getPropertyDecl()->getType()->isArrayType();
4448   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4449 }
4450 
4451 ExprResult
4452 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4453                               Expr *idx, SourceLocation rbLoc) {
4454   if (base && !base->getType().isNull() &&
4455       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4456     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4457                                     /*Length=*/nullptr, rbLoc);
4458 
4459   // Since this might be a postfix expression, get rid of ParenListExprs.
4460   if (isa<ParenListExpr>(base)) {
4461     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4462     if (result.isInvalid()) return ExprError();
4463     base = result.get();
4464   }
4465 
4466   // A comma-expression as the index is deprecated in C++2a onwards.
4467   if (getLangOpts().CPlusPlus2a &&
4468       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4469        (isa<CXXOperatorCallExpr>(idx) &&
4470         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4471     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4472       << SourceRange(base->getBeginLoc(), rbLoc);
4473   }
4474 
4475   // Handle any non-overload placeholder types in the base and index
4476   // expressions.  We can't handle overloads here because the other
4477   // operand might be an overloadable type, in which case the overload
4478   // resolution for the operator overload should get the first crack
4479   // at the overload.
4480   bool IsMSPropertySubscript = false;
4481   if (base->getType()->isNonOverloadPlaceholderType()) {
4482     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4483     if (!IsMSPropertySubscript) {
4484       ExprResult result = CheckPlaceholderExpr(base);
4485       if (result.isInvalid())
4486         return ExprError();
4487       base = result.get();
4488     }
4489   }
4490   if (idx->getType()->isNonOverloadPlaceholderType()) {
4491     ExprResult result = CheckPlaceholderExpr(idx);
4492     if (result.isInvalid()) return ExprError();
4493     idx = result.get();
4494   }
4495 
4496   // Build an unanalyzed expression if either operand is type-dependent.
4497   if (getLangOpts().CPlusPlus &&
4498       (base->isTypeDependent() || idx->isTypeDependent())) {
4499     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4500                                             VK_LValue, OK_Ordinary, rbLoc);
4501   }
4502 
4503   // MSDN, property (C++)
4504   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4505   // This attribute can also be used in the declaration of an empty array in a
4506   // class or structure definition. For example:
4507   // __declspec(property(get=GetX, put=PutX)) int x[];
4508   // The above statement indicates that x[] can be used with one or more array
4509   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4510   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4511   if (IsMSPropertySubscript) {
4512     // Build MS property subscript expression if base is MS property reference
4513     // or MS property subscript.
4514     return new (Context) MSPropertySubscriptExpr(
4515         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4516   }
4517 
4518   // Use C++ overloaded-operator rules if either operand has record
4519   // type.  The spec says to do this if either type is *overloadable*,
4520   // but enum types can't declare subscript operators or conversion
4521   // operators, so there's nothing interesting for overload resolution
4522   // to do if there aren't any record types involved.
4523   //
4524   // ObjC pointers have their own subscripting logic that is not tied
4525   // to overload resolution and so should not take this path.
4526   if (getLangOpts().CPlusPlus &&
4527       (base->getType()->isRecordType() ||
4528        (!base->getType()->isObjCObjectPointerType() &&
4529         idx->getType()->isRecordType()))) {
4530     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4531   }
4532 
4533   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4534 
4535   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4536     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4537 
4538   return Res;
4539 }
4540 
4541 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4542   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4543   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4544 
4545   // For expressions like `&(*s).b`, the base is recorded and what should be
4546   // checked.
4547   const MemberExpr *Member = nullptr;
4548   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4549     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4550 
4551   LastRecord.PossibleDerefs.erase(StrippedExpr);
4552 }
4553 
4554 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4555   QualType ResultTy = E->getType();
4556   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4557 
4558   // Bail if the element is an array since it is not memory access.
4559   if (isa<ArrayType>(ResultTy))
4560     return;
4561 
4562   if (ResultTy->hasAttr(attr::NoDeref)) {
4563     LastRecord.PossibleDerefs.insert(E);
4564     return;
4565   }
4566 
4567   // Check if the base type is a pointer to a member access of a struct
4568   // marked with noderef.
4569   const Expr *Base = E->getBase();
4570   QualType BaseTy = Base->getType();
4571   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4572     // Not a pointer access
4573     return;
4574 
4575   const MemberExpr *Member = nullptr;
4576   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4577          Member->isArrow())
4578     Base = Member->getBase();
4579 
4580   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4581     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4582       LastRecord.PossibleDerefs.insert(E);
4583   }
4584 }
4585 
4586 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4587                                           Expr *LowerBound,
4588                                           SourceLocation ColonLoc, Expr *Length,
4589                                           SourceLocation RBLoc) {
4590   if (Base->getType()->isPlaceholderType() &&
4591       !Base->getType()->isSpecificPlaceholderType(
4592           BuiltinType::OMPArraySection)) {
4593     ExprResult Result = CheckPlaceholderExpr(Base);
4594     if (Result.isInvalid())
4595       return ExprError();
4596     Base = Result.get();
4597   }
4598   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4599     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4600     if (Result.isInvalid())
4601       return ExprError();
4602     Result = DefaultLvalueConversion(Result.get());
4603     if (Result.isInvalid())
4604       return ExprError();
4605     LowerBound = Result.get();
4606   }
4607   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4608     ExprResult Result = CheckPlaceholderExpr(Length);
4609     if (Result.isInvalid())
4610       return ExprError();
4611     Result = DefaultLvalueConversion(Result.get());
4612     if (Result.isInvalid())
4613       return ExprError();
4614     Length = Result.get();
4615   }
4616 
4617   // Build an unanalyzed expression if either operand is type-dependent.
4618   if (Base->isTypeDependent() ||
4619       (LowerBound &&
4620        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4621       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4622     return new (Context)
4623         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4624                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4625   }
4626 
4627   // Perform default conversions.
4628   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4629   QualType ResultTy;
4630   if (OriginalTy->isAnyPointerType()) {
4631     ResultTy = OriginalTy->getPointeeType();
4632   } else if (OriginalTy->isArrayType()) {
4633     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4634   } else {
4635     return ExprError(
4636         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4637         << Base->getSourceRange());
4638   }
4639   // C99 6.5.2.1p1
4640   if (LowerBound) {
4641     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4642                                                       LowerBound);
4643     if (Res.isInvalid())
4644       return ExprError(Diag(LowerBound->getExprLoc(),
4645                             diag::err_omp_typecheck_section_not_integer)
4646                        << 0 << LowerBound->getSourceRange());
4647     LowerBound = Res.get();
4648 
4649     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4650         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4651       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4652           << 0 << LowerBound->getSourceRange();
4653   }
4654   if (Length) {
4655     auto Res =
4656         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4657     if (Res.isInvalid())
4658       return ExprError(Diag(Length->getExprLoc(),
4659                             diag::err_omp_typecheck_section_not_integer)
4660                        << 1 << Length->getSourceRange());
4661     Length = Res.get();
4662 
4663     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4664         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4665       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4666           << 1 << Length->getSourceRange();
4667   }
4668 
4669   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4670   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4671   // type. Note that functions are not objects, and that (in C99 parlance)
4672   // incomplete types are not object types.
4673   if (ResultTy->isFunctionType()) {
4674     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4675         << ResultTy << Base->getSourceRange();
4676     return ExprError();
4677   }
4678 
4679   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4680                           diag::err_omp_section_incomplete_type, Base))
4681     return ExprError();
4682 
4683   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4684     Expr::EvalResult Result;
4685     if (LowerBound->EvaluateAsInt(Result, Context)) {
4686       // OpenMP 4.5, [2.4 Array Sections]
4687       // The array section must be a subset of the original array.
4688       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4689       if (LowerBoundValue.isNegative()) {
4690         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4691             << LowerBound->getSourceRange();
4692         return ExprError();
4693       }
4694     }
4695   }
4696 
4697   if (Length) {
4698     Expr::EvalResult Result;
4699     if (Length->EvaluateAsInt(Result, Context)) {
4700       // OpenMP 4.5, [2.4 Array Sections]
4701       // The length must evaluate to non-negative integers.
4702       llvm::APSInt LengthValue = Result.Val.getInt();
4703       if (LengthValue.isNegative()) {
4704         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4705             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4706             << Length->getSourceRange();
4707         return ExprError();
4708       }
4709     }
4710   } else if (ColonLoc.isValid() &&
4711              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4712                                       !OriginalTy->isVariableArrayType()))) {
4713     // OpenMP 4.5, [2.4 Array Sections]
4714     // When the size of the array dimension is not known, the length must be
4715     // specified explicitly.
4716     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4717         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4718     return ExprError();
4719   }
4720 
4721   if (!Base->getType()->isSpecificPlaceholderType(
4722           BuiltinType::OMPArraySection)) {
4723     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4724     if (Result.isInvalid())
4725       return ExprError();
4726     Base = Result.get();
4727   }
4728   return new (Context)
4729       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4730                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4731 }
4732 
4733 ExprResult
4734 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4735                                       Expr *Idx, SourceLocation RLoc) {
4736   Expr *LHSExp = Base;
4737   Expr *RHSExp = Idx;
4738 
4739   ExprValueKind VK = VK_LValue;
4740   ExprObjectKind OK = OK_Ordinary;
4741 
4742   // Per C++ core issue 1213, the result is an xvalue if either operand is
4743   // a non-lvalue array, and an lvalue otherwise.
4744   if (getLangOpts().CPlusPlus11) {
4745     for (auto *Op : {LHSExp, RHSExp}) {
4746       Op = Op->IgnoreImplicit();
4747       if (Op->getType()->isArrayType() && !Op->isLValue())
4748         VK = VK_XValue;
4749     }
4750   }
4751 
4752   // Perform default conversions.
4753   if (!LHSExp->getType()->getAs<VectorType>()) {
4754     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4755     if (Result.isInvalid())
4756       return ExprError();
4757     LHSExp = Result.get();
4758   }
4759   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4760   if (Result.isInvalid())
4761     return ExprError();
4762   RHSExp = Result.get();
4763 
4764   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4765 
4766   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4767   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4768   // in the subscript position. As a result, we need to derive the array base
4769   // and index from the expression types.
4770   Expr *BaseExpr, *IndexExpr;
4771   QualType ResultType;
4772   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4773     BaseExpr = LHSExp;
4774     IndexExpr = RHSExp;
4775     ResultType = Context.DependentTy;
4776   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4777     BaseExpr = LHSExp;
4778     IndexExpr = RHSExp;
4779     ResultType = PTy->getPointeeType();
4780   } else if (const ObjCObjectPointerType *PTy =
4781                LHSTy->getAs<ObjCObjectPointerType>()) {
4782     BaseExpr = LHSExp;
4783     IndexExpr = RHSExp;
4784 
4785     // Use custom logic if this should be the pseudo-object subscript
4786     // expression.
4787     if (!LangOpts.isSubscriptPointerArithmetic())
4788       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4789                                           nullptr);
4790 
4791     ResultType = PTy->getPointeeType();
4792   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4793      // Handle the uncommon case of "123[Ptr]".
4794     BaseExpr = RHSExp;
4795     IndexExpr = LHSExp;
4796     ResultType = PTy->getPointeeType();
4797   } else if (const ObjCObjectPointerType *PTy =
4798                RHSTy->getAs<ObjCObjectPointerType>()) {
4799      // Handle the uncommon case of "123[Ptr]".
4800     BaseExpr = RHSExp;
4801     IndexExpr = LHSExp;
4802     ResultType = PTy->getPointeeType();
4803     if (!LangOpts.isSubscriptPointerArithmetic()) {
4804       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4805         << ResultType << BaseExpr->getSourceRange();
4806       return ExprError();
4807     }
4808   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4809     BaseExpr = LHSExp;    // vectors: V[123]
4810     IndexExpr = RHSExp;
4811     // We apply C++ DR1213 to vector subscripting too.
4812     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4813       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4814       if (Materialized.isInvalid())
4815         return ExprError();
4816       LHSExp = Materialized.get();
4817     }
4818     VK = LHSExp->getValueKind();
4819     if (VK != VK_RValue)
4820       OK = OK_VectorComponent;
4821 
4822     ResultType = VTy->getElementType();
4823     QualType BaseType = BaseExpr->getType();
4824     Qualifiers BaseQuals = BaseType.getQualifiers();
4825     Qualifiers MemberQuals = ResultType.getQualifiers();
4826     Qualifiers Combined = BaseQuals + MemberQuals;
4827     if (Combined != MemberQuals)
4828       ResultType = Context.getQualifiedType(ResultType, Combined);
4829   } else if (LHSTy->isArrayType()) {
4830     // If we see an array that wasn't promoted by
4831     // DefaultFunctionArrayLvalueConversion, it must be an array that
4832     // wasn't promoted because of the C90 rule that doesn't
4833     // allow promoting non-lvalue arrays.  Warn, then
4834     // force the promotion here.
4835     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4836         << LHSExp->getSourceRange();
4837     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4838                                CK_ArrayToPointerDecay).get();
4839     LHSTy = LHSExp->getType();
4840 
4841     BaseExpr = LHSExp;
4842     IndexExpr = RHSExp;
4843     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4844   } else if (RHSTy->isArrayType()) {
4845     // Same as previous, except for 123[f().a] case
4846     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4847         << RHSExp->getSourceRange();
4848     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4849                                CK_ArrayToPointerDecay).get();
4850     RHSTy = RHSExp->getType();
4851 
4852     BaseExpr = RHSExp;
4853     IndexExpr = LHSExp;
4854     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4855   } else {
4856     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4857        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4858   }
4859   // C99 6.5.2.1p1
4860   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4861     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4862                      << IndexExpr->getSourceRange());
4863 
4864   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4865        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4866          && !IndexExpr->isTypeDependent())
4867     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4868 
4869   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4870   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4871   // type. Note that Functions are not objects, and that (in C99 parlance)
4872   // incomplete types are not object types.
4873   if (ResultType->isFunctionType()) {
4874     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4875         << ResultType << BaseExpr->getSourceRange();
4876     return ExprError();
4877   }
4878 
4879   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4880     // GNU extension: subscripting on pointer to void
4881     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4882       << BaseExpr->getSourceRange();
4883 
4884     // C forbids expressions of unqualified void type from being l-values.
4885     // See IsCForbiddenLValueType.
4886     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4887   } else if (!ResultType->isDependentType() &&
4888       RequireCompleteType(LLoc, ResultType,
4889                           diag::err_subscript_incomplete_type, BaseExpr))
4890     return ExprError();
4891 
4892   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4893          !ResultType.isCForbiddenLValueType());
4894 
4895   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4896       FunctionScopes.size() > 1) {
4897     if (auto *TT =
4898             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4899       for (auto I = FunctionScopes.rbegin(),
4900                 E = std::prev(FunctionScopes.rend());
4901            I != E; ++I) {
4902         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4903         if (CSI == nullptr)
4904           break;
4905         DeclContext *DC = nullptr;
4906         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4907           DC = LSI->CallOperator;
4908         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4909           DC = CRSI->TheCapturedDecl;
4910         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4911           DC = BSI->TheDecl;
4912         if (DC) {
4913           if (DC->containsDecl(TT->getDecl()))
4914             break;
4915           captureVariablyModifiedType(
4916               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4917         }
4918       }
4919     }
4920   }
4921 
4922   return new (Context)
4923       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4924 }
4925 
4926 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4927                                   ParmVarDecl *Param) {
4928   if (Param->hasUnparsedDefaultArg()) {
4929     Diag(CallLoc,
4930          diag::err_use_of_default_argument_to_function_declared_later) <<
4931       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4932     Diag(UnparsedDefaultArgLocs[Param],
4933          diag::note_default_argument_declared_here);
4934     return true;
4935   }
4936 
4937   if (Param->hasUninstantiatedDefaultArg()) {
4938     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4939 
4940     EnterExpressionEvaluationContext EvalContext(
4941         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4942 
4943     // Instantiate the expression.
4944     //
4945     // FIXME: Pass in a correct Pattern argument, otherwise
4946     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4947     //
4948     // template<typename T>
4949     // struct A {
4950     //   static int FooImpl();
4951     //
4952     //   template<typename Tp>
4953     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4954     //   // template argument list [[T], [Tp]], should be [[Tp]].
4955     //   friend A<Tp> Foo(int a);
4956     // };
4957     //
4958     // template<typename T>
4959     // A<T> Foo(int a = A<T>::FooImpl());
4960     MultiLevelTemplateArgumentList MutiLevelArgList
4961       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4962 
4963     InstantiatingTemplate Inst(*this, CallLoc, Param,
4964                                MutiLevelArgList.getInnermost());
4965     if (Inst.isInvalid())
4966       return true;
4967     if (Inst.isAlreadyInstantiating()) {
4968       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4969       Param->setInvalidDecl();
4970       return true;
4971     }
4972 
4973     ExprResult Result;
4974     {
4975       // C++ [dcl.fct.default]p5:
4976       //   The names in the [default argument] expression are bound, and
4977       //   the semantic constraints are checked, at the point where the
4978       //   default argument expression appears.
4979       ContextRAII SavedContext(*this, FD);
4980       LocalInstantiationScope Local(*this);
4981       runWithSufficientStackSpace(CallLoc, [&] {
4982         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4983                                   /*DirectInit*/false);
4984       });
4985     }
4986     if (Result.isInvalid())
4987       return true;
4988 
4989     // Check the expression as an initializer for the parameter.
4990     InitializedEntity Entity
4991       = InitializedEntity::InitializeParameter(Context, Param);
4992     InitializationKind Kind = InitializationKind::CreateCopy(
4993         Param->getLocation(),
4994         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4995     Expr *ResultE = Result.getAs<Expr>();
4996 
4997     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4998     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4999     if (Result.isInvalid())
5000       return true;
5001 
5002     Result =
5003         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5004                             /*DiscardedValue*/ false);
5005     if (Result.isInvalid())
5006       return true;
5007 
5008     // Remember the instantiated default argument.
5009     Param->setDefaultArg(Result.getAs<Expr>());
5010     if (ASTMutationListener *L = getASTMutationListener()) {
5011       L->DefaultArgumentInstantiated(Param);
5012     }
5013   }
5014 
5015   // If the default argument expression is not set yet, we are building it now.
5016   if (!Param->hasInit()) {
5017     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5018     Param->setInvalidDecl();
5019     return true;
5020   }
5021 
5022   // If the default expression creates temporaries, we need to
5023   // push them to the current stack of expression temporaries so they'll
5024   // be properly destroyed.
5025   // FIXME: We should really be rebuilding the default argument with new
5026   // bound temporaries; see the comment in PR5810.
5027   // We don't need to do that with block decls, though, because
5028   // blocks in default argument expression can never capture anything.
5029   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5030     // Set the "needs cleanups" bit regardless of whether there are
5031     // any explicit objects.
5032     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5033 
5034     // Append all the objects to the cleanup list.  Right now, this
5035     // should always be a no-op, because blocks in default argument
5036     // expressions should never be able to capture anything.
5037     assert(!Init->getNumObjects() &&
5038            "default argument expression has capturing blocks?");
5039   }
5040 
5041   // We already type-checked the argument, so we know it works.
5042   // Just mark all of the declarations in this potentially-evaluated expression
5043   // as being "referenced".
5044   EnterExpressionEvaluationContext EvalContext(
5045       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5046   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5047                                    /*SkipLocalVariables=*/true);
5048   return false;
5049 }
5050 
5051 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5052                                         FunctionDecl *FD, ParmVarDecl *Param) {
5053   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5054     return ExprError();
5055   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5056 }
5057 
5058 Sema::VariadicCallType
5059 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5060                           Expr *Fn) {
5061   if (Proto && Proto->isVariadic()) {
5062     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5063       return VariadicConstructor;
5064     else if (Fn && Fn->getType()->isBlockPointerType())
5065       return VariadicBlock;
5066     else if (FDecl) {
5067       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5068         if (Method->isInstance())
5069           return VariadicMethod;
5070     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5071       return VariadicMethod;
5072     return VariadicFunction;
5073   }
5074   return VariadicDoesNotApply;
5075 }
5076 
5077 namespace {
5078 class FunctionCallCCC final : public FunctionCallFilterCCC {
5079 public:
5080   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5081                   unsigned NumArgs, MemberExpr *ME)
5082       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5083         FunctionName(FuncName) {}
5084 
5085   bool ValidateCandidate(const TypoCorrection &candidate) override {
5086     if (!candidate.getCorrectionSpecifier() ||
5087         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5088       return false;
5089     }
5090 
5091     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5092   }
5093 
5094   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5095     return std::make_unique<FunctionCallCCC>(*this);
5096   }
5097 
5098 private:
5099   const IdentifierInfo *const FunctionName;
5100 };
5101 }
5102 
5103 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5104                                                FunctionDecl *FDecl,
5105                                                ArrayRef<Expr *> Args) {
5106   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5107   DeclarationName FuncName = FDecl->getDeclName();
5108   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5109 
5110   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5111   if (TypoCorrection Corrected = S.CorrectTypo(
5112           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5113           S.getScopeForContext(S.CurContext), nullptr, CCC,
5114           Sema::CTK_ErrorRecovery)) {
5115     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5116       if (Corrected.isOverloaded()) {
5117         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5118         OverloadCandidateSet::iterator Best;
5119         for (NamedDecl *CD : Corrected) {
5120           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5121             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5122                                    OCS);
5123         }
5124         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5125         case OR_Success:
5126           ND = Best->FoundDecl;
5127           Corrected.setCorrectionDecl(ND);
5128           break;
5129         default:
5130           break;
5131         }
5132       }
5133       ND = ND->getUnderlyingDecl();
5134       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5135         return Corrected;
5136     }
5137   }
5138   return TypoCorrection();
5139 }
5140 
5141 /// ConvertArgumentsForCall - Converts the arguments specified in
5142 /// Args/NumArgs to the parameter types of the function FDecl with
5143 /// function prototype Proto. Call is the call expression itself, and
5144 /// Fn is the function expression. For a C++ member function, this
5145 /// routine does not attempt to convert the object argument. Returns
5146 /// true if the call is ill-formed.
5147 bool
5148 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5149                               FunctionDecl *FDecl,
5150                               const FunctionProtoType *Proto,
5151                               ArrayRef<Expr *> Args,
5152                               SourceLocation RParenLoc,
5153                               bool IsExecConfig) {
5154   // Bail out early if calling a builtin with custom typechecking.
5155   if (FDecl)
5156     if (unsigned ID = FDecl->getBuiltinID())
5157       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5158         return false;
5159 
5160   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5161   // assignment, to the types of the corresponding parameter, ...
5162   unsigned NumParams = Proto->getNumParams();
5163   bool Invalid = false;
5164   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5165   unsigned FnKind = Fn->getType()->isBlockPointerType()
5166                        ? 1 /* block */
5167                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5168                                        : 0 /* function */);
5169 
5170   // If too few arguments are available (and we don't have default
5171   // arguments for the remaining parameters), don't make the call.
5172   if (Args.size() < NumParams) {
5173     if (Args.size() < MinArgs) {
5174       TypoCorrection TC;
5175       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5176         unsigned diag_id =
5177             MinArgs == NumParams && !Proto->isVariadic()
5178                 ? diag::err_typecheck_call_too_few_args_suggest
5179                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5180         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5181                                         << static_cast<unsigned>(Args.size())
5182                                         << TC.getCorrectionRange());
5183       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5184         Diag(RParenLoc,
5185              MinArgs == NumParams && !Proto->isVariadic()
5186                  ? diag::err_typecheck_call_too_few_args_one
5187                  : diag::err_typecheck_call_too_few_args_at_least_one)
5188             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5189       else
5190         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5191                             ? diag::err_typecheck_call_too_few_args
5192                             : diag::err_typecheck_call_too_few_args_at_least)
5193             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5194             << Fn->getSourceRange();
5195 
5196       // Emit the location of the prototype.
5197       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5198         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5199 
5200       return true;
5201     }
5202     // We reserve space for the default arguments when we create
5203     // the call expression, before calling ConvertArgumentsForCall.
5204     assert((Call->getNumArgs() == NumParams) &&
5205            "We should have reserved space for the default arguments before!");
5206   }
5207 
5208   // If too many are passed and not variadic, error on the extras and drop
5209   // them.
5210   if (Args.size() > NumParams) {
5211     if (!Proto->isVariadic()) {
5212       TypoCorrection TC;
5213       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5214         unsigned diag_id =
5215             MinArgs == NumParams && !Proto->isVariadic()
5216                 ? diag::err_typecheck_call_too_many_args_suggest
5217                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5218         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5219                                         << static_cast<unsigned>(Args.size())
5220                                         << TC.getCorrectionRange());
5221       } else if (NumParams == 1 && FDecl &&
5222                  FDecl->getParamDecl(0)->getDeclName())
5223         Diag(Args[NumParams]->getBeginLoc(),
5224              MinArgs == NumParams
5225                  ? diag::err_typecheck_call_too_many_args_one
5226                  : diag::err_typecheck_call_too_many_args_at_most_one)
5227             << FnKind << FDecl->getParamDecl(0)
5228             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5229             << SourceRange(Args[NumParams]->getBeginLoc(),
5230                            Args.back()->getEndLoc());
5231       else
5232         Diag(Args[NumParams]->getBeginLoc(),
5233              MinArgs == NumParams
5234                  ? diag::err_typecheck_call_too_many_args
5235                  : diag::err_typecheck_call_too_many_args_at_most)
5236             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5237             << Fn->getSourceRange()
5238             << SourceRange(Args[NumParams]->getBeginLoc(),
5239                            Args.back()->getEndLoc());
5240 
5241       // Emit the location of the prototype.
5242       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5243         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5244 
5245       // This deletes the extra arguments.
5246       Call->shrinkNumArgs(NumParams);
5247       return true;
5248     }
5249   }
5250   SmallVector<Expr *, 8> AllArgs;
5251   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5252 
5253   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5254                                    AllArgs, CallType);
5255   if (Invalid)
5256     return true;
5257   unsigned TotalNumArgs = AllArgs.size();
5258   for (unsigned i = 0; i < TotalNumArgs; ++i)
5259     Call->setArg(i, AllArgs[i]);
5260 
5261   return false;
5262 }
5263 
5264 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5265                                   const FunctionProtoType *Proto,
5266                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5267                                   SmallVectorImpl<Expr *> &AllArgs,
5268                                   VariadicCallType CallType, bool AllowExplicit,
5269                                   bool IsListInitialization) {
5270   unsigned NumParams = Proto->getNumParams();
5271   bool Invalid = false;
5272   size_t ArgIx = 0;
5273   // Continue to check argument types (even if we have too few/many args).
5274   for (unsigned i = FirstParam; i < NumParams; i++) {
5275     QualType ProtoArgType = Proto->getParamType(i);
5276 
5277     Expr *Arg;
5278     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5279     if (ArgIx < Args.size()) {
5280       Arg = Args[ArgIx++];
5281 
5282       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5283                               diag::err_call_incomplete_argument, Arg))
5284         return true;
5285 
5286       // Strip the unbridged-cast placeholder expression off, if applicable.
5287       bool CFAudited = false;
5288       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5289           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5290           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5291         Arg = stripARCUnbridgedCast(Arg);
5292       else if (getLangOpts().ObjCAutoRefCount &&
5293                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5294                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5295         CFAudited = true;
5296 
5297       if (Proto->getExtParameterInfo(i).isNoEscape())
5298         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5299           BE->getBlockDecl()->setDoesNotEscape();
5300 
5301       InitializedEntity Entity =
5302           Param ? InitializedEntity::InitializeParameter(Context, Param,
5303                                                          ProtoArgType)
5304                 : InitializedEntity::InitializeParameter(
5305                       Context, ProtoArgType, Proto->isParamConsumed(i));
5306 
5307       // Remember that parameter belongs to a CF audited API.
5308       if (CFAudited)
5309         Entity.setParameterCFAudited();
5310 
5311       ExprResult ArgE = PerformCopyInitialization(
5312           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5313       if (ArgE.isInvalid())
5314         return true;
5315 
5316       Arg = ArgE.getAs<Expr>();
5317     } else {
5318       assert(Param && "can't use default arguments without a known callee");
5319 
5320       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5321       if (ArgExpr.isInvalid())
5322         return true;
5323 
5324       Arg = ArgExpr.getAs<Expr>();
5325     }
5326 
5327     // Check for array bounds violations for each argument to the call. This
5328     // check only triggers warnings when the argument isn't a more complex Expr
5329     // with its own checking, such as a BinaryOperator.
5330     CheckArrayAccess(Arg);
5331 
5332     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5333     CheckStaticArrayArgument(CallLoc, Param, Arg);
5334 
5335     AllArgs.push_back(Arg);
5336   }
5337 
5338   // If this is a variadic call, handle args passed through "...".
5339   if (CallType != VariadicDoesNotApply) {
5340     // Assume that extern "C" functions with variadic arguments that
5341     // return __unknown_anytype aren't *really* variadic.
5342     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5343         FDecl->isExternC()) {
5344       for (Expr *A : Args.slice(ArgIx)) {
5345         QualType paramType; // ignored
5346         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5347         Invalid |= arg.isInvalid();
5348         AllArgs.push_back(arg.get());
5349       }
5350 
5351     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5352     } else {
5353       for (Expr *A : Args.slice(ArgIx)) {
5354         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5355         Invalid |= Arg.isInvalid();
5356         // Copy blocks to the heap.
5357         if (A->getType()->isBlockPointerType())
5358           maybeExtendBlockObject(Arg);
5359         AllArgs.push_back(Arg.get());
5360       }
5361     }
5362 
5363     // Check for array bounds violations.
5364     for (Expr *A : Args.slice(ArgIx))
5365       CheckArrayAccess(A);
5366   }
5367   return Invalid;
5368 }
5369 
5370 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5371   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5372   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5373     TL = DTL.getOriginalLoc();
5374   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5375     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5376       << ATL.getLocalSourceRange();
5377 }
5378 
5379 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5380 /// array parameter, check that it is non-null, and that if it is formed by
5381 /// array-to-pointer decay, the underlying array is sufficiently large.
5382 ///
5383 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5384 /// array type derivation, then for each call to the function, the value of the
5385 /// corresponding actual argument shall provide access to the first element of
5386 /// an array with at least as many elements as specified by the size expression.
5387 void
5388 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5389                                ParmVarDecl *Param,
5390                                const Expr *ArgExpr) {
5391   // Static array parameters are not supported in C++.
5392   if (!Param || getLangOpts().CPlusPlus)
5393     return;
5394 
5395   QualType OrigTy = Param->getOriginalType();
5396 
5397   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5398   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5399     return;
5400 
5401   if (ArgExpr->isNullPointerConstant(Context,
5402                                      Expr::NPC_NeverValueDependent)) {
5403     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5404     DiagnoseCalleeStaticArrayParam(*this, Param);
5405     return;
5406   }
5407 
5408   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5409   if (!CAT)
5410     return;
5411 
5412   const ConstantArrayType *ArgCAT =
5413     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5414   if (!ArgCAT)
5415     return;
5416 
5417   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5418                                              ArgCAT->getElementType())) {
5419     if (ArgCAT->getSize().ult(CAT->getSize())) {
5420       Diag(CallLoc, diag::warn_static_array_too_small)
5421           << ArgExpr->getSourceRange()
5422           << (unsigned)ArgCAT->getSize().getZExtValue()
5423           << (unsigned)CAT->getSize().getZExtValue() << 0;
5424       DiagnoseCalleeStaticArrayParam(*this, Param);
5425     }
5426     return;
5427   }
5428 
5429   Optional<CharUnits> ArgSize =
5430       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5431   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5432   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5433     Diag(CallLoc, diag::warn_static_array_too_small)
5434         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5435         << (unsigned)ParmSize->getQuantity() << 1;
5436     DiagnoseCalleeStaticArrayParam(*this, Param);
5437   }
5438 }
5439 
5440 /// Given a function expression of unknown-any type, try to rebuild it
5441 /// to have a function type.
5442 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5443 
5444 /// Is the given type a placeholder that we need to lower out
5445 /// immediately during argument processing?
5446 static bool isPlaceholderToRemoveAsArg(QualType type) {
5447   // Placeholders are never sugared.
5448   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5449   if (!placeholder) return false;
5450 
5451   switch (placeholder->getKind()) {
5452   // Ignore all the non-placeholder types.
5453 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5454   case BuiltinType::Id:
5455 #include "clang/Basic/OpenCLImageTypes.def"
5456 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5457   case BuiltinType::Id:
5458 #include "clang/Basic/OpenCLExtensionTypes.def"
5459   // In practice we'll never use this, since all SVE types are sugared
5460   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5461 #define SVE_TYPE(Name, Id, SingletonId) \
5462   case BuiltinType::Id:
5463 #include "clang/Basic/AArch64SVEACLETypes.def"
5464 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5465 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5466 #include "clang/AST/BuiltinTypes.def"
5467     return false;
5468 
5469   // We cannot lower out overload sets; they might validly be resolved
5470   // by the call machinery.
5471   case BuiltinType::Overload:
5472     return false;
5473 
5474   // Unbridged casts in ARC can be handled in some call positions and
5475   // should be left in place.
5476   case BuiltinType::ARCUnbridgedCast:
5477     return false;
5478 
5479   // Pseudo-objects should be converted as soon as possible.
5480   case BuiltinType::PseudoObject:
5481     return true;
5482 
5483   // The debugger mode could theoretically but currently does not try
5484   // to resolve unknown-typed arguments based on known parameter types.
5485   case BuiltinType::UnknownAny:
5486     return true;
5487 
5488   // These are always invalid as call arguments and should be reported.
5489   case BuiltinType::BoundMember:
5490   case BuiltinType::BuiltinFn:
5491   case BuiltinType::OMPArraySection:
5492     return true;
5493 
5494   }
5495   llvm_unreachable("bad builtin type kind");
5496 }
5497 
5498 /// Check an argument list for placeholders that we won't try to
5499 /// handle later.
5500 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5501   // Apply this processing to all the arguments at once instead of
5502   // dying at the first failure.
5503   bool hasInvalid = false;
5504   for (size_t i = 0, e = args.size(); i != e; i++) {
5505     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5506       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5507       if (result.isInvalid()) hasInvalid = true;
5508       else args[i] = result.get();
5509     } else if (hasInvalid) {
5510       (void)S.CorrectDelayedTyposInExpr(args[i]);
5511     }
5512   }
5513   return hasInvalid;
5514 }
5515 
5516 /// If a builtin function has a pointer argument with no explicit address
5517 /// space, then it should be able to accept a pointer to any address
5518 /// space as input.  In order to do this, we need to replace the
5519 /// standard builtin declaration with one that uses the same address space
5520 /// as the call.
5521 ///
5522 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5523 ///                  it does not contain any pointer arguments without
5524 ///                  an address space qualifer.  Otherwise the rewritten
5525 ///                  FunctionDecl is returned.
5526 /// TODO: Handle pointer return types.
5527 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5528                                                 FunctionDecl *FDecl,
5529                                                 MultiExprArg ArgExprs) {
5530 
5531   QualType DeclType = FDecl->getType();
5532   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5533 
5534   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5535       ArgExprs.size() < FT->getNumParams())
5536     return nullptr;
5537 
5538   bool NeedsNewDecl = false;
5539   unsigned i = 0;
5540   SmallVector<QualType, 8> OverloadParams;
5541 
5542   for (QualType ParamType : FT->param_types()) {
5543 
5544     // Convert array arguments to pointer to simplify type lookup.
5545     ExprResult ArgRes =
5546         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5547     if (ArgRes.isInvalid())
5548       return nullptr;
5549     Expr *Arg = ArgRes.get();
5550     QualType ArgType = Arg->getType();
5551     if (!ParamType->isPointerType() ||
5552         ParamType.hasAddressSpace() ||
5553         !ArgType->isPointerType() ||
5554         !ArgType->getPointeeType().hasAddressSpace()) {
5555       OverloadParams.push_back(ParamType);
5556       continue;
5557     }
5558 
5559     QualType PointeeType = ParamType->getPointeeType();
5560     if (PointeeType.hasAddressSpace())
5561       continue;
5562 
5563     NeedsNewDecl = true;
5564     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5565 
5566     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5567     OverloadParams.push_back(Context.getPointerType(PointeeType));
5568   }
5569 
5570   if (!NeedsNewDecl)
5571     return nullptr;
5572 
5573   FunctionProtoType::ExtProtoInfo EPI;
5574   EPI.Variadic = FT->isVariadic();
5575   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5576                                                 OverloadParams, EPI);
5577   DeclContext *Parent = FDecl->getParent();
5578   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5579                                                     FDecl->getLocation(),
5580                                                     FDecl->getLocation(),
5581                                                     FDecl->getIdentifier(),
5582                                                     OverloadTy,
5583                                                     /*TInfo=*/nullptr,
5584                                                     SC_Extern, false,
5585                                                     /*hasPrototype=*/true);
5586   SmallVector<ParmVarDecl*, 16> Params;
5587   FT = cast<FunctionProtoType>(OverloadTy);
5588   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5589     QualType ParamType = FT->getParamType(i);
5590     ParmVarDecl *Parm =
5591         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5592                                 SourceLocation(), nullptr, ParamType,
5593                                 /*TInfo=*/nullptr, SC_None, nullptr);
5594     Parm->setScopeInfo(0, i);
5595     Params.push_back(Parm);
5596   }
5597   OverloadDecl->setParams(Params);
5598   return OverloadDecl;
5599 }
5600 
5601 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5602                                     FunctionDecl *Callee,
5603                                     MultiExprArg ArgExprs) {
5604   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5605   // similar attributes) really don't like it when functions are called with an
5606   // invalid number of args.
5607   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5608                          /*PartialOverloading=*/false) &&
5609       !Callee->isVariadic())
5610     return;
5611   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5612     return;
5613 
5614   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5615     S.Diag(Fn->getBeginLoc(),
5616            isa<CXXMethodDecl>(Callee)
5617                ? diag::err_ovl_no_viable_member_function_in_call
5618                : diag::err_ovl_no_viable_function_in_call)
5619         << Callee << Callee->getSourceRange();
5620     S.Diag(Callee->getLocation(),
5621            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5622         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5623     return;
5624   }
5625 }
5626 
5627 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5628     const UnresolvedMemberExpr *const UME, Sema &S) {
5629 
5630   const auto GetFunctionLevelDCIfCXXClass =
5631       [](Sema &S) -> const CXXRecordDecl * {
5632     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5633     if (!DC || !DC->getParent())
5634       return nullptr;
5635 
5636     // If the call to some member function was made from within a member
5637     // function body 'M' return return 'M's parent.
5638     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5639       return MD->getParent()->getCanonicalDecl();
5640     // else the call was made from within a default member initializer of a
5641     // class, so return the class.
5642     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5643       return RD->getCanonicalDecl();
5644     return nullptr;
5645   };
5646   // If our DeclContext is neither a member function nor a class (in the
5647   // case of a lambda in a default member initializer), we can't have an
5648   // enclosing 'this'.
5649 
5650   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5651   if (!CurParentClass)
5652     return false;
5653 
5654   // The naming class for implicit member functions call is the class in which
5655   // name lookup starts.
5656   const CXXRecordDecl *const NamingClass =
5657       UME->getNamingClass()->getCanonicalDecl();
5658   assert(NamingClass && "Must have naming class even for implicit access");
5659 
5660   // If the unresolved member functions were found in a 'naming class' that is
5661   // related (either the same or derived from) to the class that contains the
5662   // member function that itself contained the implicit member access.
5663 
5664   return CurParentClass == NamingClass ||
5665          CurParentClass->isDerivedFrom(NamingClass);
5666 }
5667 
5668 static void
5669 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5670     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5671 
5672   if (!UME)
5673     return;
5674 
5675   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5676   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5677   // already been captured, or if this is an implicit member function call (if
5678   // it isn't, an attempt to capture 'this' should already have been made).
5679   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5680       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5681     return;
5682 
5683   // Check if the naming class in which the unresolved members were found is
5684   // related (same as or is a base of) to the enclosing class.
5685 
5686   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5687     return;
5688 
5689 
5690   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5691   // If the enclosing function is not dependent, then this lambda is
5692   // capture ready, so if we can capture this, do so.
5693   if (!EnclosingFunctionCtx->isDependentContext()) {
5694     // If the current lambda and all enclosing lambdas can capture 'this' -
5695     // then go ahead and capture 'this' (since our unresolved overload set
5696     // contains at least one non-static member function).
5697     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5698       S.CheckCXXThisCapture(CallLoc);
5699   } else if (S.CurContext->isDependentContext()) {
5700     // ... since this is an implicit member reference, that might potentially
5701     // involve a 'this' capture, mark 'this' for potential capture in
5702     // enclosing lambdas.
5703     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5704       CurLSI->addPotentialThisCapture(CallLoc);
5705   }
5706 }
5707 
5708 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5709                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5710                                Expr *ExecConfig) {
5711   ExprResult Call =
5712       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5713   if (Call.isInvalid())
5714     return Call;
5715 
5716   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5717   // language modes.
5718   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5719     if (ULE->hasExplicitTemplateArgs() &&
5720         ULE->decls_begin() == ULE->decls_end()) {
5721       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5722                                  ? diag::warn_cxx17_compat_adl_only_template_id
5723                                  : diag::ext_adl_only_template_id)
5724           << ULE->getName();
5725     }
5726   }
5727 
5728   return Call;
5729 }
5730 
5731 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5732 /// This provides the location of the left/right parens and a list of comma
5733 /// locations.
5734 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5735                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5736                                Expr *ExecConfig, bool IsExecConfig) {
5737   // Since this might be a postfix expression, get rid of ParenListExprs.
5738   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5739   if (Result.isInvalid()) return ExprError();
5740   Fn = Result.get();
5741 
5742   if (checkArgsForPlaceholders(*this, ArgExprs))
5743     return ExprError();
5744 
5745   if (getLangOpts().CPlusPlus) {
5746     // If this is a pseudo-destructor expression, build the call immediately.
5747     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5748       if (!ArgExprs.empty()) {
5749         // Pseudo-destructor calls should not have any arguments.
5750         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5751             << FixItHint::CreateRemoval(
5752                    SourceRange(ArgExprs.front()->getBeginLoc(),
5753                                ArgExprs.back()->getEndLoc()));
5754       }
5755 
5756       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5757                               VK_RValue, RParenLoc);
5758     }
5759     if (Fn->getType() == Context.PseudoObjectTy) {
5760       ExprResult result = CheckPlaceholderExpr(Fn);
5761       if (result.isInvalid()) return ExprError();
5762       Fn = result.get();
5763     }
5764 
5765     // Determine whether this is a dependent call inside a C++ template,
5766     // in which case we won't do any semantic analysis now.
5767     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5768       if (ExecConfig) {
5769         return CUDAKernelCallExpr::Create(
5770             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5771             Context.DependentTy, VK_RValue, RParenLoc);
5772       } else {
5773 
5774         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5775             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5776             Fn->getBeginLoc());
5777 
5778         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5779                                 VK_RValue, RParenLoc);
5780       }
5781     }
5782 
5783     // Determine whether this is a call to an object (C++ [over.call.object]).
5784     if (Fn->getType()->isRecordType())
5785       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5786                                           RParenLoc);
5787 
5788     if (Fn->getType() == Context.UnknownAnyTy) {
5789       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5790       if (result.isInvalid()) return ExprError();
5791       Fn = result.get();
5792     }
5793 
5794     if (Fn->getType() == Context.BoundMemberTy) {
5795       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5796                                        RParenLoc);
5797     }
5798   }
5799 
5800   // Check for overloaded calls.  This can happen even in C due to extensions.
5801   if (Fn->getType() == Context.OverloadTy) {
5802     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5803 
5804     // We aren't supposed to apply this logic if there's an '&' involved.
5805     if (!find.HasFormOfMemberPointer) {
5806       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5807         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5808                                 VK_RValue, RParenLoc);
5809       OverloadExpr *ovl = find.Expression;
5810       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5811         return BuildOverloadedCallExpr(
5812             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5813             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5814       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5815                                        RParenLoc);
5816     }
5817   }
5818 
5819   // If we're directly calling a function, get the appropriate declaration.
5820   if (Fn->getType() == Context.UnknownAnyTy) {
5821     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5822     if (result.isInvalid()) return ExprError();
5823     Fn = result.get();
5824   }
5825 
5826   Expr *NakedFn = Fn->IgnoreParens();
5827 
5828   bool CallingNDeclIndirectly = false;
5829   NamedDecl *NDecl = nullptr;
5830   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5831     if (UnOp->getOpcode() == UO_AddrOf) {
5832       CallingNDeclIndirectly = true;
5833       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5834     }
5835   }
5836 
5837   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5838     NDecl = DRE->getDecl();
5839 
5840     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5841     if (FDecl && FDecl->getBuiltinID()) {
5842       // Rewrite the function decl for this builtin by replacing parameters
5843       // with no explicit address space with the address space of the arguments
5844       // in ArgExprs.
5845       if ((FDecl =
5846                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5847         NDecl = FDecl;
5848         Fn = DeclRefExpr::Create(
5849             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5850             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5851             nullptr, DRE->isNonOdrUse());
5852       }
5853     }
5854   } else if (isa<MemberExpr>(NakedFn))
5855     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5856 
5857   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5858     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5859                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5860       return ExprError();
5861 
5862     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5863       return ExprError();
5864 
5865     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5866   }
5867 
5868   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5869                                ExecConfig, IsExecConfig);
5870 }
5871 
5872 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5873 ///
5874 /// __builtin_astype( value, dst type )
5875 ///
5876 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5877                                  SourceLocation BuiltinLoc,
5878                                  SourceLocation RParenLoc) {
5879   ExprValueKind VK = VK_RValue;
5880   ExprObjectKind OK = OK_Ordinary;
5881   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5882   QualType SrcTy = E->getType();
5883   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5884     return ExprError(Diag(BuiltinLoc,
5885                           diag::err_invalid_astype_of_different_size)
5886                      << DstTy
5887                      << SrcTy
5888                      << E->getSourceRange());
5889   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5890 }
5891 
5892 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5893 /// provided arguments.
5894 ///
5895 /// __builtin_convertvector( value, dst type )
5896 ///
5897 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5898                                         SourceLocation BuiltinLoc,
5899                                         SourceLocation RParenLoc) {
5900   TypeSourceInfo *TInfo;
5901   GetTypeFromParser(ParsedDestTy, &TInfo);
5902   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5903 }
5904 
5905 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5906 /// i.e. an expression not of \p OverloadTy.  The expression should
5907 /// unary-convert to an expression of function-pointer or
5908 /// block-pointer type.
5909 ///
5910 /// \param NDecl the declaration being called, if available
5911 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5912                                        SourceLocation LParenLoc,
5913                                        ArrayRef<Expr *> Args,
5914                                        SourceLocation RParenLoc, Expr *Config,
5915                                        bool IsExecConfig, ADLCallKind UsesADL) {
5916   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5917   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5918 
5919   // Functions with 'interrupt' attribute cannot be called directly.
5920   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5921     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5922     return ExprError();
5923   }
5924 
5925   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5926   // so there's some risk when calling out to non-interrupt handler functions
5927   // that the callee might not preserve them. This is easy to diagnose here,
5928   // but can be very challenging to debug.
5929   if (auto *Caller = getCurFunctionDecl())
5930     if (Caller->hasAttr<ARMInterruptAttr>()) {
5931       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5932       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5933         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5934     }
5935 
5936   // Promote the function operand.
5937   // We special-case function promotion here because we only allow promoting
5938   // builtin functions to function pointers in the callee of a call.
5939   ExprResult Result;
5940   QualType ResultTy;
5941   if (BuiltinID &&
5942       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5943     // Extract the return type from the (builtin) function pointer type.
5944     // FIXME Several builtins still have setType in
5945     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5946     // Builtins.def to ensure they are correct before removing setType calls.
5947     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5948     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5949     ResultTy = FDecl->getCallResultType();
5950   } else {
5951     Result = CallExprUnaryConversions(Fn);
5952     ResultTy = Context.BoolTy;
5953   }
5954   if (Result.isInvalid())
5955     return ExprError();
5956   Fn = Result.get();
5957 
5958   // Check for a valid function type, but only if it is not a builtin which
5959   // requires custom type checking. These will be handled by
5960   // CheckBuiltinFunctionCall below just after creation of the call expression.
5961   const FunctionType *FuncT = nullptr;
5962   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5963   retry:
5964     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5965       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5966       // have type pointer to function".
5967       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5968       if (!FuncT)
5969         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5970                          << Fn->getType() << Fn->getSourceRange());
5971     } else if (const BlockPointerType *BPT =
5972                    Fn->getType()->getAs<BlockPointerType>()) {
5973       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5974     } else {
5975       // Handle calls to expressions of unknown-any type.
5976       if (Fn->getType() == Context.UnknownAnyTy) {
5977         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5978         if (rewrite.isInvalid())
5979           return ExprError();
5980         Fn = rewrite.get();
5981         goto retry;
5982       }
5983 
5984       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5985                        << Fn->getType() << Fn->getSourceRange());
5986     }
5987   }
5988 
5989   // Get the number of parameters in the function prototype, if any.
5990   // We will allocate space for max(Args.size(), NumParams) arguments
5991   // in the call expression.
5992   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5993   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5994 
5995   CallExpr *TheCall;
5996   if (Config) {
5997     assert(UsesADL == ADLCallKind::NotADL &&
5998            "CUDAKernelCallExpr should not use ADL");
5999     TheCall =
6000         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6001                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6002   } else {
6003     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6004                                RParenLoc, NumParams, UsesADL);
6005   }
6006 
6007   if (!getLangOpts().CPlusPlus) {
6008     // Forget about the nulled arguments since typo correction
6009     // do not handle them well.
6010     TheCall->shrinkNumArgs(Args.size());
6011     // C cannot always handle TypoExpr nodes in builtin calls and direct
6012     // function calls as their argument checking don't necessarily handle
6013     // dependent types properly, so make sure any TypoExprs have been
6014     // dealt with.
6015     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6016     if (!Result.isUsable()) return ExprError();
6017     CallExpr *TheOldCall = TheCall;
6018     TheCall = dyn_cast<CallExpr>(Result.get());
6019     bool CorrectedTypos = TheCall != TheOldCall;
6020     if (!TheCall) return Result;
6021     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6022 
6023     // A new call expression node was created if some typos were corrected.
6024     // However it may not have been constructed with enough storage. In this
6025     // case, rebuild the node with enough storage. The waste of space is
6026     // immaterial since this only happens when some typos were corrected.
6027     if (CorrectedTypos && Args.size() < NumParams) {
6028       if (Config)
6029         TheCall = CUDAKernelCallExpr::Create(
6030             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6031             RParenLoc, NumParams);
6032       else
6033         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6034                                    RParenLoc, NumParams, UsesADL);
6035     }
6036     // We can now handle the nulled arguments for the default arguments.
6037     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6038   }
6039 
6040   // Bail out early if calling a builtin with custom type checking.
6041   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6042     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6043 
6044   if (getLangOpts().CUDA) {
6045     if (Config) {
6046       // CUDA: Kernel calls must be to global functions
6047       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6048         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6049             << FDecl << Fn->getSourceRange());
6050 
6051       // CUDA: Kernel function must have 'void' return type
6052       if (!FuncT->getReturnType()->isVoidType() &&
6053           !FuncT->getReturnType()->getAs<AutoType>() &&
6054           !FuncT->getReturnType()->isInstantiationDependentType())
6055         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6056             << Fn->getType() << Fn->getSourceRange());
6057     } else {
6058       // CUDA: Calls to global functions must be configured
6059       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6060         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6061             << FDecl << Fn->getSourceRange());
6062     }
6063   }
6064 
6065   // Check for a valid return type
6066   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6067                           FDecl))
6068     return ExprError();
6069 
6070   // We know the result type of the call, set it.
6071   TheCall->setType(FuncT->getCallResultType(Context));
6072   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6073 
6074   if (Proto) {
6075     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6076                                 IsExecConfig))
6077       return ExprError();
6078   } else {
6079     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6080 
6081     if (FDecl) {
6082       // Check if we have too few/too many template arguments, based
6083       // on our knowledge of the function definition.
6084       const FunctionDecl *Def = nullptr;
6085       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6086         Proto = Def->getType()->getAs<FunctionProtoType>();
6087        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6088           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6089           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6090       }
6091 
6092       // If the function we're calling isn't a function prototype, but we have
6093       // a function prototype from a prior declaratiom, use that prototype.
6094       if (!FDecl->hasPrototype())
6095         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6096     }
6097 
6098     // Promote the arguments (C99 6.5.2.2p6).
6099     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6100       Expr *Arg = Args[i];
6101 
6102       if (Proto && i < Proto->getNumParams()) {
6103         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6104             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6105         ExprResult ArgE =
6106             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6107         if (ArgE.isInvalid())
6108           return true;
6109 
6110         Arg = ArgE.getAs<Expr>();
6111 
6112       } else {
6113         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6114 
6115         if (ArgE.isInvalid())
6116           return true;
6117 
6118         Arg = ArgE.getAs<Expr>();
6119       }
6120 
6121       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6122                               diag::err_call_incomplete_argument, Arg))
6123         return ExprError();
6124 
6125       TheCall->setArg(i, Arg);
6126     }
6127   }
6128 
6129   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6130     if (!Method->isStatic())
6131       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6132         << Fn->getSourceRange());
6133 
6134   // Check for sentinels
6135   if (NDecl)
6136     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6137 
6138   // Do special checking on direct calls to functions.
6139   if (FDecl) {
6140     if (CheckFunctionCall(FDecl, TheCall, Proto))
6141       return ExprError();
6142 
6143     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6144 
6145     if (BuiltinID)
6146       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6147   } else if (NDecl) {
6148     if (CheckPointerCall(NDecl, TheCall, Proto))
6149       return ExprError();
6150   } else {
6151     if (CheckOtherCall(TheCall, Proto))
6152       return ExprError();
6153   }
6154 
6155   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6156 }
6157 
6158 ExprResult
6159 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6160                            SourceLocation RParenLoc, Expr *InitExpr) {
6161   assert(Ty && "ActOnCompoundLiteral(): missing type");
6162   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6163 
6164   TypeSourceInfo *TInfo;
6165   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6166   if (!TInfo)
6167     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6168 
6169   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6170 }
6171 
6172 ExprResult
6173 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6174                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6175   QualType literalType = TInfo->getType();
6176 
6177   if (literalType->isArrayType()) {
6178     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6179           diag::err_illegal_decl_array_incomplete_type,
6180           SourceRange(LParenLoc,
6181                       LiteralExpr->getSourceRange().getEnd())))
6182       return ExprError();
6183     if (literalType->isVariableArrayType())
6184       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6185         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6186   } else if (!literalType->isDependentType() &&
6187              RequireCompleteType(LParenLoc, literalType,
6188                diag::err_typecheck_decl_incomplete_type,
6189                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6190     return ExprError();
6191 
6192   InitializedEntity Entity
6193     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6194   InitializationKind Kind
6195     = InitializationKind::CreateCStyleCast(LParenLoc,
6196                                            SourceRange(LParenLoc, RParenLoc),
6197                                            /*InitList=*/true);
6198   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6199   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6200                                       &literalType);
6201   if (Result.isInvalid())
6202     return ExprError();
6203   LiteralExpr = Result.get();
6204 
6205   bool isFileScope = !CurContext->isFunctionOrMethod();
6206 
6207   // In C, compound literals are l-values for some reason.
6208   // For GCC compatibility, in C++, file-scope array compound literals with
6209   // constant initializers are also l-values, and compound literals are
6210   // otherwise prvalues.
6211   //
6212   // (GCC also treats C++ list-initialized file-scope array prvalues with
6213   // constant initializers as l-values, but that's non-conforming, so we don't
6214   // follow it there.)
6215   //
6216   // FIXME: It would be better to handle the lvalue cases as materializing and
6217   // lifetime-extending a temporary object, but our materialized temporaries
6218   // representation only supports lifetime extension from a variable, not "out
6219   // of thin air".
6220   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6221   // is bound to the result of applying array-to-pointer decay to the compound
6222   // literal.
6223   // FIXME: GCC supports compound literals of reference type, which should
6224   // obviously have a value kind derived from the kind of reference involved.
6225   ExprValueKind VK =
6226       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6227           ? VK_RValue
6228           : VK_LValue;
6229 
6230   if (isFileScope)
6231     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6232       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6233         Expr *Init = ILE->getInit(i);
6234         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6235       }
6236 
6237   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6238                                               VK, LiteralExpr, isFileScope);
6239   if (isFileScope) {
6240     if (!LiteralExpr->isTypeDependent() &&
6241         !LiteralExpr->isValueDependent() &&
6242         !literalType->isDependentType()) // C99 6.5.2.5p3
6243       if (CheckForConstantInitializer(LiteralExpr, literalType))
6244         return ExprError();
6245   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6246              literalType.getAddressSpace() != LangAS::Default) {
6247     // Embedded-C extensions to C99 6.5.2.5:
6248     //   "If the compound literal occurs inside the body of a function, the
6249     //   type name shall not be qualified by an address-space qualifier."
6250     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6251       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6252     return ExprError();
6253   }
6254 
6255   // Compound literals that have automatic storage duration are destroyed at
6256   // the end of the scope. Emit diagnostics if it is or contains a C union type
6257   // that is non-trivial to destruct.
6258   if (!isFileScope)
6259     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6260       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6261                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6262 
6263   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6264       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6265     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6266                                        E->getInitializer()->getExprLoc());
6267 
6268   return MaybeBindToTemporary(E);
6269 }
6270 
6271 ExprResult
6272 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6273                     SourceLocation RBraceLoc) {
6274   // Only produce each kind of designated initialization diagnostic once.
6275   SourceLocation FirstDesignator;
6276   bool DiagnosedArrayDesignator = false;
6277   bool DiagnosedNestedDesignator = false;
6278   bool DiagnosedMixedDesignator = false;
6279 
6280   // Check that any designated initializers are syntactically valid in the
6281   // current language mode.
6282   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6283     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6284       if (FirstDesignator.isInvalid())
6285         FirstDesignator = DIE->getBeginLoc();
6286 
6287       if (!getLangOpts().CPlusPlus)
6288         break;
6289 
6290       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6291         DiagnosedNestedDesignator = true;
6292         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6293           << DIE->getDesignatorsSourceRange();
6294       }
6295 
6296       for (auto &Desig : DIE->designators()) {
6297         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6298           DiagnosedArrayDesignator = true;
6299           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6300             << Desig.getSourceRange();
6301         }
6302       }
6303 
6304       if (!DiagnosedMixedDesignator &&
6305           !isa<DesignatedInitExpr>(InitArgList[0])) {
6306         DiagnosedMixedDesignator = true;
6307         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6308           << DIE->getSourceRange();
6309         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6310           << InitArgList[0]->getSourceRange();
6311       }
6312     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6313                isa<DesignatedInitExpr>(InitArgList[0])) {
6314       DiagnosedMixedDesignator = true;
6315       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6316       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6317         << DIE->getSourceRange();
6318       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6319         << InitArgList[I]->getSourceRange();
6320     }
6321   }
6322 
6323   if (FirstDesignator.isValid()) {
6324     // Only diagnose designated initiaization as a C++20 extension if we didn't
6325     // already diagnose use of (non-C++20) C99 designator syntax.
6326     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6327         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6328       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6329                                 ? diag::warn_cxx17_compat_designated_init
6330                                 : diag::ext_cxx_designated_init);
6331     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6332       Diag(FirstDesignator, diag::ext_designated_init);
6333     }
6334   }
6335 
6336   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6337 }
6338 
6339 ExprResult
6340 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6341                     SourceLocation RBraceLoc) {
6342   // Semantic analysis for initializers is done by ActOnDeclarator() and
6343   // CheckInitializer() - it requires knowledge of the object being initialized.
6344 
6345   // Immediately handle non-overload placeholders.  Overloads can be
6346   // resolved contextually, but everything else here can't.
6347   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6348     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6349       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6350 
6351       // Ignore failures; dropping the entire initializer list because
6352       // of one failure would be terrible for indexing/etc.
6353       if (result.isInvalid()) continue;
6354 
6355       InitArgList[I] = result.get();
6356     }
6357   }
6358 
6359   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6360                                                RBraceLoc);
6361   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6362   return E;
6363 }
6364 
6365 /// Do an explicit extend of the given block pointer if we're in ARC.
6366 void Sema::maybeExtendBlockObject(ExprResult &E) {
6367   assert(E.get()->getType()->isBlockPointerType());
6368   assert(E.get()->isRValue());
6369 
6370   // Only do this in an r-value context.
6371   if (!getLangOpts().ObjCAutoRefCount) return;
6372 
6373   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6374                                CK_ARCExtendBlockObject, E.get(),
6375                                /*base path*/ nullptr, VK_RValue);
6376   Cleanup.setExprNeedsCleanups(true);
6377 }
6378 
6379 /// Prepare a conversion of the given expression to an ObjC object
6380 /// pointer type.
6381 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6382   QualType type = E.get()->getType();
6383   if (type->isObjCObjectPointerType()) {
6384     return CK_BitCast;
6385   } else if (type->isBlockPointerType()) {
6386     maybeExtendBlockObject(E);
6387     return CK_BlockPointerToObjCPointerCast;
6388   } else {
6389     assert(type->isPointerType());
6390     return CK_CPointerToObjCPointerCast;
6391   }
6392 }
6393 
6394 /// Prepares for a scalar cast, performing all the necessary stages
6395 /// except the final cast and returning the kind required.
6396 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6397   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6398   // Also, callers should have filtered out the invalid cases with
6399   // pointers.  Everything else should be possible.
6400 
6401   QualType SrcTy = Src.get()->getType();
6402   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6403     return CK_NoOp;
6404 
6405   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6406   case Type::STK_MemberPointer:
6407     llvm_unreachable("member pointer type in C");
6408 
6409   case Type::STK_CPointer:
6410   case Type::STK_BlockPointer:
6411   case Type::STK_ObjCObjectPointer:
6412     switch (DestTy->getScalarTypeKind()) {
6413     case Type::STK_CPointer: {
6414       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6415       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6416       if (SrcAS != DestAS)
6417         return CK_AddressSpaceConversion;
6418       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6419         return CK_NoOp;
6420       return CK_BitCast;
6421     }
6422     case Type::STK_BlockPointer:
6423       return (SrcKind == Type::STK_BlockPointer
6424                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6425     case Type::STK_ObjCObjectPointer:
6426       if (SrcKind == Type::STK_ObjCObjectPointer)
6427         return CK_BitCast;
6428       if (SrcKind == Type::STK_CPointer)
6429         return CK_CPointerToObjCPointerCast;
6430       maybeExtendBlockObject(Src);
6431       return CK_BlockPointerToObjCPointerCast;
6432     case Type::STK_Bool:
6433       return CK_PointerToBoolean;
6434     case Type::STK_Integral:
6435       return CK_PointerToIntegral;
6436     case Type::STK_Floating:
6437     case Type::STK_FloatingComplex:
6438     case Type::STK_IntegralComplex:
6439     case Type::STK_MemberPointer:
6440     case Type::STK_FixedPoint:
6441       llvm_unreachable("illegal cast from pointer");
6442     }
6443     llvm_unreachable("Should have returned before this");
6444 
6445   case Type::STK_FixedPoint:
6446     switch (DestTy->getScalarTypeKind()) {
6447     case Type::STK_FixedPoint:
6448       return CK_FixedPointCast;
6449     case Type::STK_Bool:
6450       return CK_FixedPointToBoolean;
6451     case Type::STK_Integral:
6452       return CK_FixedPointToIntegral;
6453     case Type::STK_Floating:
6454     case Type::STK_IntegralComplex:
6455     case Type::STK_FloatingComplex:
6456       Diag(Src.get()->getExprLoc(),
6457            diag::err_unimplemented_conversion_with_fixed_point_type)
6458           << DestTy;
6459       return CK_IntegralCast;
6460     case Type::STK_CPointer:
6461     case Type::STK_ObjCObjectPointer:
6462     case Type::STK_BlockPointer:
6463     case Type::STK_MemberPointer:
6464       llvm_unreachable("illegal cast to pointer type");
6465     }
6466     llvm_unreachable("Should have returned before this");
6467 
6468   case Type::STK_Bool: // casting from bool is like casting from an integer
6469   case Type::STK_Integral:
6470     switch (DestTy->getScalarTypeKind()) {
6471     case Type::STK_CPointer:
6472     case Type::STK_ObjCObjectPointer:
6473     case Type::STK_BlockPointer:
6474       if (Src.get()->isNullPointerConstant(Context,
6475                                            Expr::NPC_ValueDependentIsNull))
6476         return CK_NullToPointer;
6477       return CK_IntegralToPointer;
6478     case Type::STK_Bool:
6479       return CK_IntegralToBoolean;
6480     case Type::STK_Integral:
6481       return CK_IntegralCast;
6482     case Type::STK_Floating:
6483       return CK_IntegralToFloating;
6484     case Type::STK_IntegralComplex:
6485       Src = ImpCastExprToType(Src.get(),
6486                       DestTy->castAs<ComplexType>()->getElementType(),
6487                       CK_IntegralCast);
6488       return CK_IntegralRealToComplex;
6489     case Type::STK_FloatingComplex:
6490       Src = ImpCastExprToType(Src.get(),
6491                       DestTy->castAs<ComplexType>()->getElementType(),
6492                       CK_IntegralToFloating);
6493       return CK_FloatingRealToComplex;
6494     case Type::STK_MemberPointer:
6495       llvm_unreachable("member pointer type in C");
6496     case Type::STK_FixedPoint:
6497       return CK_IntegralToFixedPoint;
6498     }
6499     llvm_unreachable("Should have returned before this");
6500 
6501   case Type::STK_Floating:
6502     switch (DestTy->getScalarTypeKind()) {
6503     case Type::STK_Floating:
6504       return CK_FloatingCast;
6505     case Type::STK_Bool:
6506       return CK_FloatingToBoolean;
6507     case Type::STK_Integral:
6508       return CK_FloatingToIntegral;
6509     case Type::STK_FloatingComplex:
6510       Src = ImpCastExprToType(Src.get(),
6511                               DestTy->castAs<ComplexType>()->getElementType(),
6512                               CK_FloatingCast);
6513       return CK_FloatingRealToComplex;
6514     case Type::STK_IntegralComplex:
6515       Src = ImpCastExprToType(Src.get(),
6516                               DestTy->castAs<ComplexType>()->getElementType(),
6517                               CK_FloatingToIntegral);
6518       return CK_IntegralRealToComplex;
6519     case Type::STK_CPointer:
6520     case Type::STK_ObjCObjectPointer:
6521     case Type::STK_BlockPointer:
6522       llvm_unreachable("valid float->pointer cast?");
6523     case Type::STK_MemberPointer:
6524       llvm_unreachable("member pointer type in C");
6525     case Type::STK_FixedPoint:
6526       Diag(Src.get()->getExprLoc(),
6527            diag::err_unimplemented_conversion_with_fixed_point_type)
6528           << SrcTy;
6529       return CK_IntegralCast;
6530     }
6531     llvm_unreachable("Should have returned before this");
6532 
6533   case Type::STK_FloatingComplex:
6534     switch (DestTy->getScalarTypeKind()) {
6535     case Type::STK_FloatingComplex:
6536       return CK_FloatingComplexCast;
6537     case Type::STK_IntegralComplex:
6538       return CK_FloatingComplexToIntegralComplex;
6539     case Type::STK_Floating: {
6540       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6541       if (Context.hasSameType(ET, DestTy))
6542         return CK_FloatingComplexToReal;
6543       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6544       return CK_FloatingCast;
6545     }
6546     case Type::STK_Bool:
6547       return CK_FloatingComplexToBoolean;
6548     case Type::STK_Integral:
6549       Src = ImpCastExprToType(Src.get(),
6550                               SrcTy->castAs<ComplexType>()->getElementType(),
6551                               CK_FloatingComplexToReal);
6552       return CK_FloatingToIntegral;
6553     case Type::STK_CPointer:
6554     case Type::STK_ObjCObjectPointer:
6555     case Type::STK_BlockPointer:
6556       llvm_unreachable("valid complex float->pointer cast?");
6557     case Type::STK_MemberPointer:
6558       llvm_unreachable("member pointer type in C");
6559     case Type::STK_FixedPoint:
6560       Diag(Src.get()->getExprLoc(),
6561            diag::err_unimplemented_conversion_with_fixed_point_type)
6562           << SrcTy;
6563       return CK_IntegralCast;
6564     }
6565     llvm_unreachable("Should have returned before this");
6566 
6567   case Type::STK_IntegralComplex:
6568     switch (DestTy->getScalarTypeKind()) {
6569     case Type::STK_FloatingComplex:
6570       return CK_IntegralComplexToFloatingComplex;
6571     case Type::STK_IntegralComplex:
6572       return CK_IntegralComplexCast;
6573     case Type::STK_Integral: {
6574       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6575       if (Context.hasSameType(ET, DestTy))
6576         return CK_IntegralComplexToReal;
6577       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6578       return CK_IntegralCast;
6579     }
6580     case Type::STK_Bool:
6581       return CK_IntegralComplexToBoolean;
6582     case Type::STK_Floating:
6583       Src = ImpCastExprToType(Src.get(),
6584                               SrcTy->castAs<ComplexType>()->getElementType(),
6585                               CK_IntegralComplexToReal);
6586       return CK_IntegralToFloating;
6587     case Type::STK_CPointer:
6588     case Type::STK_ObjCObjectPointer:
6589     case Type::STK_BlockPointer:
6590       llvm_unreachable("valid complex int->pointer cast?");
6591     case Type::STK_MemberPointer:
6592       llvm_unreachable("member pointer type in C");
6593     case Type::STK_FixedPoint:
6594       Diag(Src.get()->getExprLoc(),
6595            diag::err_unimplemented_conversion_with_fixed_point_type)
6596           << SrcTy;
6597       return CK_IntegralCast;
6598     }
6599     llvm_unreachable("Should have returned before this");
6600   }
6601 
6602   llvm_unreachable("Unhandled scalar cast");
6603 }
6604 
6605 static bool breakDownVectorType(QualType type, uint64_t &len,
6606                                 QualType &eltType) {
6607   // Vectors are simple.
6608   if (const VectorType *vecType = type->getAs<VectorType>()) {
6609     len = vecType->getNumElements();
6610     eltType = vecType->getElementType();
6611     assert(eltType->isScalarType());
6612     return true;
6613   }
6614 
6615   // We allow lax conversion to and from non-vector types, but only if
6616   // they're real types (i.e. non-complex, non-pointer scalar types).
6617   if (!type->isRealType()) return false;
6618 
6619   len = 1;
6620   eltType = type;
6621   return true;
6622 }
6623 
6624 /// Are the two types lax-compatible vector types?  That is, given
6625 /// that one of them is a vector, do they have equal storage sizes,
6626 /// where the storage size is the number of elements times the element
6627 /// size?
6628 ///
6629 /// This will also return false if either of the types is neither a
6630 /// vector nor a real type.
6631 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6632   assert(destTy->isVectorType() || srcTy->isVectorType());
6633 
6634   // Disallow lax conversions between scalars and ExtVectors (these
6635   // conversions are allowed for other vector types because common headers
6636   // depend on them).  Most scalar OP ExtVector cases are handled by the
6637   // splat path anyway, which does what we want (convert, not bitcast).
6638   // What this rules out for ExtVectors is crazy things like char4*float.
6639   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6640   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6641 
6642   uint64_t srcLen, destLen;
6643   QualType srcEltTy, destEltTy;
6644   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6645   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6646 
6647   // ASTContext::getTypeSize will return the size rounded up to a
6648   // power of 2, so instead of using that, we need to use the raw
6649   // element size multiplied by the element count.
6650   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6651   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6652 
6653   return (srcLen * srcEltSize == destLen * destEltSize);
6654 }
6655 
6656 /// Is this a legal conversion between two types, one of which is
6657 /// known to be a vector type?
6658 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6659   assert(destTy->isVectorType() || srcTy->isVectorType());
6660 
6661   switch (Context.getLangOpts().getLaxVectorConversions()) {
6662   case LangOptions::LaxVectorConversionKind::None:
6663     return false;
6664 
6665   case LangOptions::LaxVectorConversionKind::Integer:
6666     if (!srcTy->isIntegralOrEnumerationType()) {
6667       auto *Vec = srcTy->getAs<VectorType>();
6668       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6669         return false;
6670     }
6671     if (!destTy->isIntegralOrEnumerationType()) {
6672       auto *Vec = destTy->getAs<VectorType>();
6673       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6674         return false;
6675     }
6676     // OK, integer (vector) -> integer (vector) bitcast.
6677     break;
6678 
6679     case LangOptions::LaxVectorConversionKind::All:
6680     break;
6681   }
6682 
6683   return areLaxCompatibleVectorTypes(srcTy, destTy);
6684 }
6685 
6686 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6687                            CastKind &Kind) {
6688   assert(VectorTy->isVectorType() && "Not a vector type!");
6689 
6690   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6691     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6692       return Diag(R.getBegin(),
6693                   Ty->isVectorType() ?
6694                   diag::err_invalid_conversion_between_vectors :
6695                   diag::err_invalid_conversion_between_vector_and_integer)
6696         << VectorTy << Ty << R;
6697   } else
6698     return Diag(R.getBegin(),
6699                 diag::err_invalid_conversion_between_vector_and_scalar)
6700       << VectorTy << Ty << R;
6701 
6702   Kind = CK_BitCast;
6703   return false;
6704 }
6705 
6706 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6707   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6708 
6709   if (DestElemTy == SplattedExpr->getType())
6710     return SplattedExpr;
6711 
6712   assert(DestElemTy->isFloatingType() ||
6713          DestElemTy->isIntegralOrEnumerationType());
6714 
6715   CastKind CK;
6716   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6717     // OpenCL requires that we convert `true` boolean expressions to -1, but
6718     // only when splatting vectors.
6719     if (DestElemTy->isFloatingType()) {
6720       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6721       // in two steps: boolean to signed integral, then to floating.
6722       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6723                                                  CK_BooleanToSignedIntegral);
6724       SplattedExpr = CastExprRes.get();
6725       CK = CK_IntegralToFloating;
6726     } else {
6727       CK = CK_BooleanToSignedIntegral;
6728     }
6729   } else {
6730     ExprResult CastExprRes = SplattedExpr;
6731     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6732     if (CastExprRes.isInvalid())
6733       return ExprError();
6734     SplattedExpr = CastExprRes.get();
6735   }
6736   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6737 }
6738 
6739 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6740                                     Expr *CastExpr, CastKind &Kind) {
6741   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6742 
6743   QualType SrcTy = CastExpr->getType();
6744 
6745   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6746   // an ExtVectorType.
6747   // In OpenCL, casts between vectors of different types are not allowed.
6748   // (See OpenCL 6.2).
6749   if (SrcTy->isVectorType()) {
6750     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6751         (getLangOpts().OpenCL &&
6752          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6753       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6754         << DestTy << SrcTy << R;
6755       return ExprError();
6756     }
6757     Kind = CK_BitCast;
6758     return CastExpr;
6759   }
6760 
6761   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6762   // conversion will take place first from scalar to elt type, and then
6763   // splat from elt type to vector.
6764   if (SrcTy->isPointerType())
6765     return Diag(R.getBegin(),
6766                 diag::err_invalid_conversion_between_vector_and_scalar)
6767       << DestTy << SrcTy << R;
6768 
6769   Kind = CK_VectorSplat;
6770   return prepareVectorSplat(DestTy, CastExpr);
6771 }
6772 
6773 ExprResult
6774 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6775                     Declarator &D, ParsedType &Ty,
6776                     SourceLocation RParenLoc, Expr *CastExpr) {
6777   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6778          "ActOnCastExpr(): missing type or expr");
6779 
6780   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6781   if (D.isInvalidType())
6782     return ExprError();
6783 
6784   if (getLangOpts().CPlusPlus) {
6785     // Check that there are no default arguments (C++ only).
6786     CheckExtraCXXDefaultArguments(D);
6787   } else {
6788     // Make sure any TypoExprs have been dealt with.
6789     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6790     if (!Res.isUsable())
6791       return ExprError();
6792     CastExpr = Res.get();
6793   }
6794 
6795   checkUnusedDeclAttributes(D);
6796 
6797   QualType castType = castTInfo->getType();
6798   Ty = CreateParsedType(castType, castTInfo);
6799 
6800   bool isVectorLiteral = false;
6801 
6802   // Check for an altivec or OpenCL literal,
6803   // i.e. all the elements are integer constants.
6804   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6805   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6806   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6807        && castType->isVectorType() && (PE || PLE)) {
6808     if (PLE && PLE->getNumExprs() == 0) {
6809       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6810       return ExprError();
6811     }
6812     if (PE || PLE->getNumExprs() == 1) {
6813       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6814       if (!E->getType()->isVectorType())
6815         isVectorLiteral = true;
6816     }
6817     else
6818       isVectorLiteral = true;
6819   }
6820 
6821   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6822   // then handle it as such.
6823   if (isVectorLiteral)
6824     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6825 
6826   // If the Expr being casted is a ParenListExpr, handle it specially.
6827   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6828   // sequence of BinOp comma operators.
6829   if (isa<ParenListExpr>(CastExpr)) {
6830     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6831     if (Result.isInvalid()) return ExprError();
6832     CastExpr = Result.get();
6833   }
6834 
6835   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6836       !getSourceManager().isInSystemMacro(LParenLoc))
6837     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6838 
6839   CheckTollFreeBridgeCast(castType, CastExpr);
6840 
6841   CheckObjCBridgeRelatedCast(castType, CastExpr);
6842 
6843   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6844 
6845   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6846 }
6847 
6848 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6849                                     SourceLocation RParenLoc, Expr *E,
6850                                     TypeSourceInfo *TInfo) {
6851   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6852          "Expected paren or paren list expression");
6853 
6854   Expr **exprs;
6855   unsigned numExprs;
6856   Expr *subExpr;
6857   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6858   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6859     LiteralLParenLoc = PE->getLParenLoc();
6860     LiteralRParenLoc = PE->getRParenLoc();
6861     exprs = PE->getExprs();
6862     numExprs = PE->getNumExprs();
6863   } else { // isa<ParenExpr> by assertion at function entrance
6864     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6865     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6866     subExpr = cast<ParenExpr>(E)->getSubExpr();
6867     exprs = &subExpr;
6868     numExprs = 1;
6869   }
6870 
6871   QualType Ty = TInfo->getType();
6872   assert(Ty->isVectorType() && "Expected vector type");
6873 
6874   SmallVector<Expr *, 8> initExprs;
6875   const VectorType *VTy = Ty->castAs<VectorType>();
6876   unsigned numElems = VTy->getNumElements();
6877 
6878   // '(...)' form of vector initialization in AltiVec: the number of
6879   // initializers must be one or must match the size of the vector.
6880   // If a single value is specified in the initializer then it will be
6881   // replicated to all the components of the vector
6882   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6883     // The number of initializers must be one or must match the size of the
6884     // vector. If a single value is specified in the initializer then it will
6885     // be replicated to all the components of the vector
6886     if (numExprs == 1) {
6887       QualType ElemTy = VTy->getElementType();
6888       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6889       if (Literal.isInvalid())
6890         return ExprError();
6891       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6892                                   PrepareScalarCast(Literal, ElemTy));
6893       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6894     }
6895     else if (numExprs < numElems) {
6896       Diag(E->getExprLoc(),
6897            diag::err_incorrect_number_of_vector_initializers);
6898       return ExprError();
6899     }
6900     else
6901       initExprs.append(exprs, exprs + numExprs);
6902   }
6903   else {
6904     // For OpenCL, when the number of initializers is a single value,
6905     // it will be replicated to all components of the vector.
6906     if (getLangOpts().OpenCL &&
6907         VTy->getVectorKind() == VectorType::GenericVector &&
6908         numExprs == 1) {
6909         QualType ElemTy = VTy->getElementType();
6910         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6911         if (Literal.isInvalid())
6912           return ExprError();
6913         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6914                                     PrepareScalarCast(Literal, ElemTy));
6915         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6916     }
6917 
6918     initExprs.append(exprs, exprs + numExprs);
6919   }
6920   // FIXME: This means that pretty-printing the final AST will produce curly
6921   // braces instead of the original commas.
6922   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6923                                                    initExprs, LiteralRParenLoc);
6924   initE->setType(Ty);
6925   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6926 }
6927 
6928 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6929 /// the ParenListExpr into a sequence of comma binary operators.
6930 ExprResult
6931 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6932   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6933   if (!E)
6934     return OrigExpr;
6935 
6936   ExprResult Result(E->getExpr(0));
6937 
6938   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6939     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6940                         E->getExpr(i));
6941 
6942   if (Result.isInvalid()) return ExprError();
6943 
6944   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6945 }
6946 
6947 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6948                                     SourceLocation R,
6949                                     MultiExprArg Val) {
6950   return ParenListExpr::Create(Context, L, Val, R);
6951 }
6952 
6953 /// Emit a specialized diagnostic when one expression is a null pointer
6954 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6955 /// emitted.
6956 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6957                                       SourceLocation QuestionLoc) {
6958   Expr *NullExpr = LHSExpr;
6959   Expr *NonPointerExpr = RHSExpr;
6960   Expr::NullPointerConstantKind NullKind =
6961       NullExpr->isNullPointerConstant(Context,
6962                                       Expr::NPC_ValueDependentIsNotNull);
6963 
6964   if (NullKind == Expr::NPCK_NotNull) {
6965     NullExpr = RHSExpr;
6966     NonPointerExpr = LHSExpr;
6967     NullKind =
6968         NullExpr->isNullPointerConstant(Context,
6969                                         Expr::NPC_ValueDependentIsNotNull);
6970   }
6971 
6972   if (NullKind == Expr::NPCK_NotNull)
6973     return false;
6974 
6975   if (NullKind == Expr::NPCK_ZeroExpression)
6976     return false;
6977 
6978   if (NullKind == Expr::NPCK_ZeroLiteral) {
6979     // In this case, check to make sure that we got here from a "NULL"
6980     // string in the source code.
6981     NullExpr = NullExpr->IgnoreParenImpCasts();
6982     SourceLocation loc = NullExpr->getExprLoc();
6983     if (!findMacroSpelling(loc, "NULL"))
6984       return false;
6985   }
6986 
6987   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6988   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6989       << NonPointerExpr->getType() << DiagType
6990       << NonPointerExpr->getSourceRange();
6991   return true;
6992 }
6993 
6994 /// Return false if the condition expression is valid, true otherwise.
6995 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6996   QualType CondTy = Cond->getType();
6997 
6998   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6999   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7000     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7001       << CondTy << Cond->getSourceRange();
7002     return true;
7003   }
7004 
7005   // C99 6.5.15p2
7006   if (CondTy->isScalarType()) return false;
7007 
7008   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7009     << CondTy << Cond->getSourceRange();
7010   return true;
7011 }
7012 
7013 /// Handle when one or both operands are void type.
7014 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7015                                          ExprResult &RHS) {
7016     Expr *LHSExpr = LHS.get();
7017     Expr *RHSExpr = RHS.get();
7018 
7019     if (!LHSExpr->getType()->isVoidType())
7020       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7021           << RHSExpr->getSourceRange();
7022     if (!RHSExpr->getType()->isVoidType())
7023       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7024           << LHSExpr->getSourceRange();
7025     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7026     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7027     return S.Context.VoidTy;
7028 }
7029 
7030 /// Return false if the NullExpr can be promoted to PointerTy,
7031 /// true otherwise.
7032 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7033                                         QualType PointerTy) {
7034   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7035       !NullExpr.get()->isNullPointerConstant(S.Context,
7036                                             Expr::NPC_ValueDependentIsNull))
7037     return true;
7038 
7039   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7040   return false;
7041 }
7042 
7043 /// Checks compatibility between two pointers and return the resulting
7044 /// type.
7045 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7046                                                      ExprResult &RHS,
7047                                                      SourceLocation Loc) {
7048   QualType LHSTy = LHS.get()->getType();
7049   QualType RHSTy = RHS.get()->getType();
7050 
7051   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7052     // Two identical pointers types are always compatible.
7053     return LHSTy;
7054   }
7055 
7056   QualType lhptee, rhptee;
7057 
7058   // Get the pointee types.
7059   bool IsBlockPointer = false;
7060   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7061     lhptee = LHSBTy->getPointeeType();
7062     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7063     IsBlockPointer = true;
7064   } else {
7065     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7066     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7067   }
7068 
7069   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7070   // differently qualified versions of compatible types, the result type is
7071   // a pointer to an appropriately qualified version of the composite
7072   // type.
7073 
7074   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7075   // clause doesn't make sense for our extensions. E.g. address space 2 should
7076   // be incompatible with address space 3: they may live on different devices or
7077   // anything.
7078   Qualifiers lhQual = lhptee.getQualifiers();
7079   Qualifiers rhQual = rhptee.getQualifiers();
7080 
7081   LangAS ResultAddrSpace = LangAS::Default;
7082   LangAS LAddrSpace = lhQual.getAddressSpace();
7083   LangAS RAddrSpace = rhQual.getAddressSpace();
7084 
7085   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7086   // spaces is disallowed.
7087   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7088     ResultAddrSpace = LAddrSpace;
7089   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7090     ResultAddrSpace = RAddrSpace;
7091   else {
7092     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7093         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7094         << RHS.get()->getSourceRange();
7095     return QualType();
7096   }
7097 
7098   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7099   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7100   lhQual.removeCVRQualifiers();
7101   rhQual.removeCVRQualifiers();
7102 
7103   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7104   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7105   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7106   // qual types are compatible iff
7107   //  * corresponded types are compatible
7108   //  * CVR qualifiers are equal
7109   //  * address spaces are equal
7110   // Thus for conditional operator we merge CVR and address space unqualified
7111   // pointees and if there is a composite type we return a pointer to it with
7112   // merged qualifiers.
7113   LHSCastKind =
7114       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7115   RHSCastKind =
7116       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7117   lhQual.removeAddressSpace();
7118   rhQual.removeAddressSpace();
7119 
7120   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7121   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7122 
7123   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7124 
7125   if (CompositeTy.isNull()) {
7126     // In this situation, we assume void* type. No especially good
7127     // reason, but this is what gcc does, and we do have to pick
7128     // to get a consistent AST.
7129     QualType incompatTy;
7130     incompatTy = S.Context.getPointerType(
7131         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7132     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7133     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7134 
7135     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7136     // for casts between types with incompatible address space qualifiers.
7137     // For the following code the compiler produces casts between global and
7138     // local address spaces of the corresponded innermost pointees:
7139     // local int *global *a;
7140     // global int *global *b;
7141     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7142     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7143         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7144         << RHS.get()->getSourceRange();
7145 
7146     return incompatTy;
7147   }
7148 
7149   // The pointer types are compatible.
7150   // In case of OpenCL ResultTy should have the address space qualifier
7151   // which is a superset of address spaces of both the 2nd and the 3rd
7152   // operands of the conditional operator.
7153   QualType ResultTy = [&, ResultAddrSpace]() {
7154     if (S.getLangOpts().OpenCL) {
7155       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7156       CompositeQuals.setAddressSpace(ResultAddrSpace);
7157       return S.Context
7158           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7159           .withCVRQualifiers(MergedCVRQual);
7160     }
7161     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7162   }();
7163   if (IsBlockPointer)
7164     ResultTy = S.Context.getBlockPointerType(ResultTy);
7165   else
7166     ResultTy = S.Context.getPointerType(ResultTy);
7167 
7168   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7169   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7170   return ResultTy;
7171 }
7172 
7173 /// Return the resulting type when the operands are both block pointers.
7174 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7175                                                           ExprResult &LHS,
7176                                                           ExprResult &RHS,
7177                                                           SourceLocation Loc) {
7178   QualType LHSTy = LHS.get()->getType();
7179   QualType RHSTy = RHS.get()->getType();
7180 
7181   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7182     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7183       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7184       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7185       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7186       return destType;
7187     }
7188     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7189       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7190       << RHS.get()->getSourceRange();
7191     return QualType();
7192   }
7193 
7194   // We have 2 block pointer types.
7195   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7196 }
7197 
7198 /// Return the resulting type when the operands are both pointers.
7199 static QualType
7200 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7201                                             ExprResult &RHS,
7202                                             SourceLocation Loc) {
7203   // get the pointer types
7204   QualType LHSTy = LHS.get()->getType();
7205   QualType RHSTy = RHS.get()->getType();
7206 
7207   // get the "pointed to" types
7208   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7209   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7210 
7211   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7212   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7213     // Figure out necessary qualifiers (C99 6.5.15p6)
7214     QualType destPointee
7215       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7216     QualType destType = S.Context.getPointerType(destPointee);
7217     // Add qualifiers if necessary.
7218     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7219     // Promote to void*.
7220     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7221     return destType;
7222   }
7223   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7224     QualType destPointee
7225       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7226     QualType destType = S.Context.getPointerType(destPointee);
7227     // Add qualifiers if necessary.
7228     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7229     // Promote to void*.
7230     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7231     return destType;
7232   }
7233 
7234   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7235 }
7236 
7237 /// Return false if the first expression is not an integer and the second
7238 /// expression is not a pointer, true otherwise.
7239 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7240                                         Expr* PointerExpr, SourceLocation Loc,
7241                                         bool IsIntFirstExpr) {
7242   if (!PointerExpr->getType()->isPointerType() ||
7243       !Int.get()->getType()->isIntegerType())
7244     return false;
7245 
7246   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7247   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7248 
7249   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7250     << Expr1->getType() << Expr2->getType()
7251     << Expr1->getSourceRange() << Expr2->getSourceRange();
7252   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7253                             CK_IntegralToPointer);
7254   return true;
7255 }
7256 
7257 /// Simple conversion between integer and floating point types.
7258 ///
7259 /// Used when handling the OpenCL conditional operator where the
7260 /// condition is a vector while the other operands are scalar.
7261 ///
7262 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7263 /// types are either integer or floating type. Between the two
7264 /// operands, the type with the higher rank is defined as the "result
7265 /// type". The other operand needs to be promoted to the same type. No
7266 /// other type promotion is allowed. We cannot use
7267 /// UsualArithmeticConversions() for this purpose, since it always
7268 /// promotes promotable types.
7269 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7270                                             ExprResult &RHS,
7271                                             SourceLocation QuestionLoc) {
7272   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7273   if (LHS.isInvalid())
7274     return QualType();
7275   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7276   if (RHS.isInvalid())
7277     return QualType();
7278 
7279   // For conversion purposes, we ignore any qualifiers.
7280   // For example, "const float" and "float" are equivalent.
7281   QualType LHSType =
7282     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7283   QualType RHSType =
7284     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7285 
7286   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7287     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7288       << LHSType << LHS.get()->getSourceRange();
7289     return QualType();
7290   }
7291 
7292   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7293     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7294       << RHSType << RHS.get()->getSourceRange();
7295     return QualType();
7296   }
7297 
7298   // If both types are identical, no conversion is needed.
7299   if (LHSType == RHSType)
7300     return LHSType;
7301 
7302   // Now handle "real" floating types (i.e. float, double, long double).
7303   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7304     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7305                                  /*IsCompAssign = */ false);
7306 
7307   // Finally, we have two differing integer types.
7308   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7309   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7310 }
7311 
7312 /// Convert scalar operands to a vector that matches the
7313 ///        condition in length.
7314 ///
7315 /// Used when handling the OpenCL conditional operator where the
7316 /// condition is a vector while the other operands are scalar.
7317 ///
7318 /// We first compute the "result type" for the scalar operands
7319 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7320 /// into a vector of that type where the length matches the condition
7321 /// vector type. s6.11.6 requires that the element types of the result
7322 /// and the condition must have the same number of bits.
7323 static QualType
7324 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7325                               QualType CondTy, SourceLocation QuestionLoc) {
7326   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7327   if (ResTy.isNull()) return QualType();
7328 
7329   const VectorType *CV = CondTy->getAs<VectorType>();
7330   assert(CV);
7331 
7332   // Determine the vector result type
7333   unsigned NumElements = CV->getNumElements();
7334   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7335 
7336   // Ensure that all types have the same number of bits
7337   if (S.Context.getTypeSize(CV->getElementType())
7338       != S.Context.getTypeSize(ResTy)) {
7339     // Since VectorTy is created internally, it does not pretty print
7340     // with an OpenCL name. Instead, we just print a description.
7341     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7342     SmallString<64> Str;
7343     llvm::raw_svector_ostream OS(Str);
7344     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7345     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7346       << CondTy << OS.str();
7347     return QualType();
7348   }
7349 
7350   // Convert operands to the vector result type
7351   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7352   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7353 
7354   return VectorTy;
7355 }
7356 
7357 /// Return false if this is a valid OpenCL condition vector
7358 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7359                                        SourceLocation QuestionLoc) {
7360   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7361   // integral type.
7362   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7363   assert(CondTy);
7364   QualType EleTy = CondTy->getElementType();
7365   if (EleTy->isIntegerType()) return false;
7366 
7367   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7368     << Cond->getType() << Cond->getSourceRange();
7369   return true;
7370 }
7371 
7372 /// Return false if the vector condition type and the vector
7373 ///        result type are compatible.
7374 ///
7375 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7376 /// number of elements, and their element types have the same number
7377 /// of bits.
7378 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7379                               SourceLocation QuestionLoc) {
7380   const VectorType *CV = CondTy->getAs<VectorType>();
7381   const VectorType *RV = VecResTy->getAs<VectorType>();
7382   assert(CV && RV);
7383 
7384   if (CV->getNumElements() != RV->getNumElements()) {
7385     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7386       << CondTy << VecResTy;
7387     return true;
7388   }
7389 
7390   QualType CVE = CV->getElementType();
7391   QualType RVE = RV->getElementType();
7392 
7393   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7394     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7395       << CondTy << VecResTy;
7396     return true;
7397   }
7398 
7399   return false;
7400 }
7401 
7402 /// Return the resulting type for the conditional operator in
7403 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7404 ///        s6.3.i) when the condition is a vector type.
7405 static QualType
7406 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7407                              ExprResult &LHS, ExprResult &RHS,
7408                              SourceLocation QuestionLoc) {
7409   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7410   if (Cond.isInvalid())
7411     return QualType();
7412   QualType CondTy = Cond.get()->getType();
7413 
7414   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7415     return QualType();
7416 
7417   // If either operand is a vector then find the vector type of the
7418   // result as specified in OpenCL v1.1 s6.3.i.
7419   if (LHS.get()->getType()->isVectorType() ||
7420       RHS.get()->getType()->isVectorType()) {
7421     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7422                                               /*isCompAssign*/false,
7423                                               /*AllowBothBool*/true,
7424                                               /*AllowBoolConversions*/false);
7425     if (VecResTy.isNull()) return QualType();
7426     // The result type must match the condition type as specified in
7427     // OpenCL v1.1 s6.11.6.
7428     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7429       return QualType();
7430     return VecResTy;
7431   }
7432 
7433   // Both operands are scalar.
7434   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7435 }
7436 
7437 /// Return true if the Expr is block type
7438 static bool checkBlockType(Sema &S, const Expr *E) {
7439   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7440     QualType Ty = CE->getCallee()->getType();
7441     if (Ty->isBlockPointerType()) {
7442       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7443       return true;
7444     }
7445   }
7446   return false;
7447 }
7448 
7449 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7450 /// In that case, LHS = cond.
7451 /// C99 6.5.15
7452 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7453                                         ExprResult &RHS, ExprValueKind &VK,
7454                                         ExprObjectKind &OK,
7455                                         SourceLocation QuestionLoc) {
7456 
7457   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7458   if (!LHSResult.isUsable()) return QualType();
7459   LHS = LHSResult;
7460 
7461   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7462   if (!RHSResult.isUsable()) return QualType();
7463   RHS = RHSResult;
7464 
7465   // C++ is sufficiently different to merit its own checker.
7466   if (getLangOpts().CPlusPlus)
7467     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7468 
7469   VK = VK_RValue;
7470   OK = OK_Ordinary;
7471 
7472   // The OpenCL operator with a vector condition is sufficiently
7473   // different to merit its own checker.
7474   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7475     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7476 
7477   // First, check the condition.
7478   Cond = UsualUnaryConversions(Cond.get());
7479   if (Cond.isInvalid())
7480     return QualType();
7481   if (checkCondition(*this, Cond.get(), QuestionLoc))
7482     return QualType();
7483 
7484   // Now check the two expressions.
7485   if (LHS.get()->getType()->isVectorType() ||
7486       RHS.get()->getType()->isVectorType())
7487     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7488                                /*AllowBothBool*/true,
7489                                /*AllowBoolConversions*/false);
7490 
7491   QualType ResTy =
7492       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7493   if (LHS.isInvalid() || RHS.isInvalid())
7494     return QualType();
7495 
7496   QualType LHSTy = LHS.get()->getType();
7497   QualType RHSTy = RHS.get()->getType();
7498 
7499   // Diagnose attempts to convert between __float128 and long double where
7500   // such conversions currently can't be handled.
7501   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7502     Diag(QuestionLoc,
7503          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7504       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7505     return QualType();
7506   }
7507 
7508   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7509   // selection operator (?:).
7510   if (getLangOpts().OpenCL &&
7511       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7512     return QualType();
7513   }
7514 
7515   // If both operands have arithmetic type, do the usual arithmetic conversions
7516   // to find a common type: C99 6.5.15p3,5.
7517   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7518     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7519     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7520 
7521     return ResTy;
7522   }
7523 
7524   // If both operands are the same structure or union type, the result is that
7525   // type.
7526   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7527     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7528       if (LHSRT->getDecl() == RHSRT->getDecl())
7529         // "If both the operands have structure or union type, the result has
7530         // that type."  This implies that CV qualifiers are dropped.
7531         return LHSTy.getUnqualifiedType();
7532     // FIXME: Type of conditional expression must be complete in C mode.
7533   }
7534 
7535   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7536   // The following || allows only one side to be void (a GCC-ism).
7537   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7538     return checkConditionalVoidType(*this, LHS, RHS);
7539   }
7540 
7541   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7542   // the type of the other operand."
7543   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7544   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7545 
7546   // All objective-c pointer type analysis is done here.
7547   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7548                                                         QuestionLoc);
7549   if (LHS.isInvalid() || RHS.isInvalid())
7550     return QualType();
7551   if (!compositeType.isNull())
7552     return compositeType;
7553 
7554 
7555   // Handle block pointer types.
7556   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7557     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7558                                                      QuestionLoc);
7559 
7560   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7561   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7562     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7563                                                        QuestionLoc);
7564 
7565   // GCC compatibility: soften pointer/integer mismatch.  Note that
7566   // null pointers have been filtered out by this point.
7567   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7568       /*IsIntFirstExpr=*/true))
7569     return RHSTy;
7570   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7571       /*IsIntFirstExpr=*/false))
7572     return LHSTy;
7573 
7574   // Emit a better diagnostic if one of the expressions is a null pointer
7575   // constant and the other is not a pointer type. In this case, the user most
7576   // likely forgot to take the address of the other expression.
7577   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7578     return QualType();
7579 
7580   // Otherwise, the operands are not compatible.
7581   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7582     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7583     << RHS.get()->getSourceRange();
7584   return QualType();
7585 }
7586 
7587 /// FindCompositeObjCPointerType - Helper method to find composite type of
7588 /// two objective-c pointer types of the two input expressions.
7589 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7590                                             SourceLocation QuestionLoc) {
7591   QualType LHSTy = LHS.get()->getType();
7592   QualType RHSTy = RHS.get()->getType();
7593 
7594   // Handle things like Class and struct objc_class*.  Here we case the result
7595   // to the pseudo-builtin, because that will be implicitly cast back to the
7596   // redefinition type if an attempt is made to access its fields.
7597   if (LHSTy->isObjCClassType() &&
7598       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7599     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7600     return LHSTy;
7601   }
7602   if (RHSTy->isObjCClassType() &&
7603       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7604     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7605     return RHSTy;
7606   }
7607   // And the same for struct objc_object* / id
7608   if (LHSTy->isObjCIdType() &&
7609       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7610     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7611     return LHSTy;
7612   }
7613   if (RHSTy->isObjCIdType() &&
7614       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7615     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7616     return RHSTy;
7617   }
7618   // And the same for struct objc_selector* / SEL
7619   if (Context.isObjCSelType(LHSTy) &&
7620       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7621     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7622     return LHSTy;
7623   }
7624   if (Context.isObjCSelType(RHSTy) &&
7625       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7626     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7627     return RHSTy;
7628   }
7629   // Check constraints for Objective-C object pointers types.
7630   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7631 
7632     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7633       // Two identical object pointer types are always compatible.
7634       return LHSTy;
7635     }
7636     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7637     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7638     QualType compositeType = LHSTy;
7639 
7640     // If both operands are interfaces and either operand can be
7641     // assigned to the other, use that type as the composite
7642     // type. This allows
7643     //   xxx ? (A*) a : (B*) b
7644     // where B is a subclass of A.
7645     //
7646     // Additionally, as for assignment, if either type is 'id'
7647     // allow silent coercion. Finally, if the types are
7648     // incompatible then make sure to use 'id' as the composite
7649     // type so the result is acceptable for sending messages to.
7650 
7651     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7652     // It could return the composite type.
7653     if (!(compositeType =
7654           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7655       // Nothing more to do.
7656     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7657       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7658     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7659       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7660     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7661                 RHSOPT->isObjCQualifiedIdType()) &&
7662                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7663                                                          true)) {
7664       // Need to handle "id<xx>" explicitly.
7665       // GCC allows qualified id and any Objective-C type to devolve to
7666       // id. Currently localizing to here until clear this should be
7667       // part of ObjCQualifiedIdTypesAreCompatible.
7668       compositeType = Context.getObjCIdType();
7669     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7670       compositeType = Context.getObjCIdType();
7671     } else {
7672       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7673       << LHSTy << RHSTy
7674       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7675       QualType incompatTy = Context.getObjCIdType();
7676       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7677       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7678       return incompatTy;
7679     }
7680     // The object pointer types are compatible.
7681     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7682     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7683     return compositeType;
7684   }
7685   // Check Objective-C object pointer types and 'void *'
7686   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7687     if (getLangOpts().ObjCAutoRefCount) {
7688       // ARC forbids the implicit conversion of object pointers to 'void *',
7689       // so these types are not compatible.
7690       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7691           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7692       LHS = RHS = true;
7693       return QualType();
7694     }
7695     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7696     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7697     QualType destPointee
7698     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7699     QualType destType = Context.getPointerType(destPointee);
7700     // Add qualifiers if necessary.
7701     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7702     // Promote to void*.
7703     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7704     return destType;
7705   }
7706   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7707     if (getLangOpts().ObjCAutoRefCount) {
7708       // ARC forbids the implicit conversion of object pointers to 'void *',
7709       // so these types are not compatible.
7710       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7711           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7712       LHS = RHS = true;
7713       return QualType();
7714     }
7715     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7716     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7717     QualType destPointee
7718     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7719     QualType destType = Context.getPointerType(destPointee);
7720     // Add qualifiers if necessary.
7721     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7722     // Promote to void*.
7723     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7724     return destType;
7725   }
7726   return QualType();
7727 }
7728 
7729 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7730 /// ParenRange in parentheses.
7731 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7732                                const PartialDiagnostic &Note,
7733                                SourceRange ParenRange) {
7734   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7735   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7736       EndLoc.isValid()) {
7737     Self.Diag(Loc, Note)
7738       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7739       << FixItHint::CreateInsertion(EndLoc, ")");
7740   } else {
7741     // We can't display the parentheses, so just show the bare note.
7742     Self.Diag(Loc, Note) << ParenRange;
7743   }
7744 }
7745 
7746 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7747   return BinaryOperator::isAdditiveOp(Opc) ||
7748          BinaryOperator::isMultiplicativeOp(Opc) ||
7749          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7750   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7751   // not any of the logical operators.  Bitwise-xor is commonly used as a
7752   // logical-xor because there is no logical-xor operator.  The logical
7753   // operators, including uses of xor, have a high false positive rate for
7754   // precedence warnings.
7755 }
7756 
7757 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7758 /// expression, either using a built-in or overloaded operator,
7759 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7760 /// expression.
7761 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7762                                    Expr **RHSExprs) {
7763   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7764   E = E->IgnoreImpCasts();
7765   E = E->IgnoreConversionOperator();
7766   E = E->IgnoreImpCasts();
7767   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7768     E = MTE->getSubExpr();
7769     E = E->IgnoreImpCasts();
7770   }
7771 
7772   // Built-in binary operator.
7773   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7774     if (IsArithmeticOp(OP->getOpcode())) {
7775       *Opcode = OP->getOpcode();
7776       *RHSExprs = OP->getRHS();
7777       return true;
7778     }
7779   }
7780 
7781   // Overloaded operator.
7782   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7783     if (Call->getNumArgs() != 2)
7784       return false;
7785 
7786     // Make sure this is really a binary operator that is safe to pass into
7787     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7788     OverloadedOperatorKind OO = Call->getOperator();
7789     if (OO < OO_Plus || OO > OO_Arrow ||
7790         OO == OO_PlusPlus || OO == OO_MinusMinus)
7791       return false;
7792 
7793     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7794     if (IsArithmeticOp(OpKind)) {
7795       *Opcode = OpKind;
7796       *RHSExprs = Call->getArg(1);
7797       return true;
7798     }
7799   }
7800 
7801   return false;
7802 }
7803 
7804 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7805 /// or is a logical expression such as (x==y) which has int type, but is
7806 /// commonly interpreted as boolean.
7807 static bool ExprLooksBoolean(Expr *E) {
7808   E = E->IgnoreParenImpCasts();
7809 
7810   if (E->getType()->isBooleanType())
7811     return true;
7812   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7813     return OP->isComparisonOp() || OP->isLogicalOp();
7814   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7815     return OP->getOpcode() == UO_LNot;
7816   if (E->getType()->isPointerType())
7817     return true;
7818   // FIXME: What about overloaded operator calls returning "unspecified boolean
7819   // type"s (commonly pointer-to-members)?
7820 
7821   return false;
7822 }
7823 
7824 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7825 /// and binary operator are mixed in a way that suggests the programmer assumed
7826 /// the conditional operator has higher precedence, for example:
7827 /// "int x = a + someBinaryCondition ? 1 : 2".
7828 static void DiagnoseConditionalPrecedence(Sema &Self,
7829                                           SourceLocation OpLoc,
7830                                           Expr *Condition,
7831                                           Expr *LHSExpr,
7832                                           Expr *RHSExpr) {
7833   BinaryOperatorKind CondOpcode;
7834   Expr *CondRHS;
7835 
7836   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7837     return;
7838   if (!ExprLooksBoolean(CondRHS))
7839     return;
7840 
7841   // The condition is an arithmetic binary expression, with a right-
7842   // hand side that looks boolean, so warn.
7843 
7844   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7845                         ? diag::warn_precedence_bitwise_conditional
7846                         : diag::warn_precedence_conditional;
7847 
7848   Self.Diag(OpLoc, DiagID)
7849       << Condition->getSourceRange()
7850       << BinaryOperator::getOpcodeStr(CondOpcode);
7851 
7852   SuggestParentheses(
7853       Self, OpLoc,
7854       Self.PDiag(diag::note_precedence_silence)
7855           << BinaryOperator::getOpcodeStr(CondOpcode),
7856       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7857 
7858   SuggestParentheses(Self, OpLoc,
7859                      Self.PDiag(diag::note_precedence_conditional_first),
7860                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7861 }
7862 
7863 /// Compute the nullability of a conditional expression.
7864 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7865                                               QualType LHSTy, QualType RHSTy,
7866                                               ASTContext &Ctx) {
7867   if (!ResTy->isAnyPointerType())
7868     return ResTy;
7869 
7870   auto GetNullability = [&Ctx](QualType Ty) {
7871     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7872     if (Kind)
7873       return *Kind;
7874     return NullabilityKind::Unspecified;
7875   };
7876 
7877   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7878   NullabilityKind MergedKind;
7879 
7880   // Compute nullability of a binary conditional expression.
7881   if (IsBin) {
7882     if (LHSKind == NullabilityKind::NonNull)
7883       MergedKind = NullabilityKind::NonNull;
7884     else
7885       MergedKind = RHSKind;
7886   // Compute nullability of a normal conditional expression.
7887   } else {
7888     if (LHSKind == NullabilityKind::Nullable ||
7889         RHSKind == NullabilityKind::Nullable)
7890       MergedKind = NullabilityKind::Nullable;
7891     else if (LHSKind == NullabilityKind::NonNull)
7892       MergedKind = RHSKind;
7893     else if (RHSKind == NullabilityKind::NonNull)
7894       MergedKind = LHSKind;
7895     else
7896       MergedKind = NullabilityKind::Unspecified;
7897   }
7898 
7899   // Return if ResTy already has the correct nullability.
7900   if (GetNullability(ResTy) == MergedKind)
7901     return ResTy;
7902 
7903   // Strip all nullability from ResTy.
7904   while (ResTy->getNullability(Ctx))
7905     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7906 
7907   // Create a new AttributedType with the new nullability kind.
7908   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7909   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7910 }
7911 
7912 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7913 /// in the case of a the GNU conditional expr extension.
7914 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7915                                     SourceLocation ColonLoc,
7916                                     Expr *CondExpr, Expr *LHSExpr,
7917                                     Expr *RHSExpr) {
7918   if (!getLangOpts().CPlusPlus) {
7919     // C cannot handle TypoExpr nodes in the condition because it
7920     // doesn't handle dependent types properly, so make sure any TypoExprs have
7921     // been dealt with before checking the operands.
7922     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7923     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7924     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7925 
7926     if (!CondResult.isUsable())
7927       return ExprError();
7928 
7929     if (LHSExpr) {
7930       if (!LHSResult.isUsable())
7931         return ExprError();
7932     }
7933 
7934     if (!RHSResult.isUsable())
7935       return ExprError();
7936 
7937     CondExpr = CondResult.get();
7938     LHSExpr = LHSResult.get();
7939     RHSExpr = RHSResult.get();
7940   }
7941 
7942   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7943   // was the condition.
7944   OpaqueValueExpr *opaqueValue = nullptr;
7945   Expr *commonExpr = nullptr;
7946   if (!LHSExpr) {
7947     commonExpr = CondExpr;
7948     // Lower out placeholder types first.  This is important so that we don't
7949     // try to capture a placeholder. This happens in few cases in C++; such
7950     // as Objective-C++'s dictionary subscripting syntax.
7951     if (commonExpr->hasPlaceholderType()) {
7952       ExprResult result = CheckPlaceholderExpr(commonExpr);
7953       if (!result.isUsable()) return ExprError();
7954       commonExpr = result.get();
7955     }
7956     // We usually want to apply unary conversions *before* saving, except
7957     // in the special case of a C++ l-value conditional.
7958     if (!(getLangOpts().CPlusPlus
7959           && !commonExpr->isTypeDependent()
7960           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7961           && commonExpr->isGLValue()
7962           && commonExpr->isOrdinaryOrBitFieldObject()
7963           && RHSExpr->isOrdinaryOrBitFieldObject()
7964           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7965       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7966       if (commonRes.isInvalid())
7967         return ExprError();
7968       commonExpr = commonRes.get();
7969     }
7970 
7971     // If the common expression is a class or array prvalue, materialize it
7972     // so that we can safely refer to it multiple times.
7973     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7974                                    commonExpr->getType()->isArrayType())) {
7975       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7976       if (MatExpr.isInvalid())
7977         return ExprError();
7978       commonExpr = MatExpr.get();
7979     }
7980 
7981     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7982                                                 commonExpr->getType(),
7983                                                 commonExpr->getValueKind(),
7984                                                 commonExpr->getObjectKind(),
7985                                                 commonExpr);
7986     LHSExpr = CondExpr = opaqueValue;
7987   }
7988 
7989   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7990   ExprValueKind VK = VK_RValue;
7991   ExprObjectKind OK = OK_Ordinary;
7992   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7993   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7994                                              VK, OK, QuestionLoc);
7995   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7996       RHS.isInvalid())
7997     return ExprError();
7998 
7999   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8000                                 RHS.get());
8001 
8002   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8003 
8004   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8005                                          Context);
8006 
8007   if (!commonExpr)
8008     return new (Context)
8009         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8010                             RHS.get(), result, VK, OK);
8011 
8012   return new (Context) BinaryConditionalOperator(
8013       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8014       ColonLoc, result, VK, OK);
8015 }
8016 
8017 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8018 // being closely modeled after the C99 spec:-). The odd characteristic of this
8019 // routine is it effectively iqnores the qualifiers on the top level pointee.
8020 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8021 // FIXME: add a couple examples in this comment.
8022 static Sema::AssignConvertType
8023 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8024   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8025   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8026 
8027   // get the "pointed to" type (ignoring qualifiers at the top level)
8028   const Type *lhptee, *rhptee;
8029   Qualifiers lhq, rhq;
8030   std::tie(lhptee, lhq) =
8031       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8032   std::tie(rhptee, rhq) =
8033       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8034 
8035   Sema::AssignConvertType ConvTy = Sema::Compatible;
8036 
8037   // C99 6.5.16.1p1: This following citation is common to constraints
8038   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8039   // qualifiers of the type *pointed to* by the right;
8040 
8041   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8042   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8043       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8044     // Ignore lifetime for further calculation.
8045     lhq.removeObjCLifetime();
8046     rhq.removeObjCLifetime();
8047   }
8048 
8049   if (!lhq.compatiblyIncludes(rhq)) {
8050     // Treat address-space mismatches as fatal.
8051     if (!lhq.isAddressSpaceSupersetOf(rhq))
8052       return Sema::IncompatiblePointerDiscardsQualifiers;
8053 
8054     // It's okay to add or remove GC or lifetime qualifiers when converting to
8055     // and from void*.
8056     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8057                         .compatiblyIncludes(
8058                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8059              && (lhptee->isVoidType() || rhptee->isVoidType()))
8060       ; // keep old
8061 
8062     // Treat lifetime mismatches as fatal.
8063     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8064       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8065 
8066     // For GCC/MS compatibility, other qualifier mismatches are treated
8067     // as still compatible in C.
8068     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8069   }
8070 
8071   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8072   // incomplete type and the other is a pointer to a qualified or unqualified
8073   // version of void...
8074   if (lhptee->isVoidType()) {
8075     if (rhptee->isIncompleteOrObjectType())
8076       return ConvTy;
8077 
8078     // As an extension, we allow cast to/from void* to function pointer.
8079     assert(rhptee->isFunctionType());
8080     return Sema::FunctionVoidPointer;
8081   }
8082 
8083   if (rhptee->isVoidType()) {
8084     if (lhptee->isIncompleteOrObjectType())
8085       return ConvTy;
8086 
8087     // As an extension, we allow cast to/from void* to function pointer.
8088     assert(lhptee->isFunctionType());
8089     return Sema::FunctionVoidPointer;
8090   }
8091 
8092   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8093   // unqualified versions of compatible types, ...
8094   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8095   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8096     // Check if the pointee types are compatible ignoring the sign.
8097     // We explicitly check for char so that we catch "char" vs
8098     // "unsigned char" on systems where "char" is unsigned.
8099     if (lhptee->isCharType())
8100       ltrans = S.Context.UnsignedCharTy;
8101     else if (lhptee->hasSignedIntegerRepresentation())
8102       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8103 
8104     if (rhptee->isCharType())
8105       rtrans = S.Context.UnsignedCharTy;
8106     else if (rhptee->hasSignedIntegerRepresentation())
8107       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8108 
8109     if (ltrans == rtrans) {
8110       // Types are compatible ignoring the sign. Qualifier incompatibility
8111       // takes priority over sign incompatibility because the sign
8112       // warning can be disabled.
8113       if (ConvTy != Sema::Compatible)
8114         return ConvTy;
8115 
8116       return Sema::IncompatiblePointerSign;
8117     }
8118 
8119     // If we are a multi-level pointer, it's possible that our issue is simply
8120     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8121     // the eventual target type is the same and the pointers have the same
8122     // level of indirection, this must be the issue.
8123     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8124       do {
8125         std::tie(lhptee, lhq) =
8126           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8127         std::tie(rhptee, rhq) =
8128           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8129 
8130         // Inconsistent address spaces at this point is invalid, even if the
8131         // address spaces would be compatible.
8132         // FIXME: This doesn't catch address space mismatches for pointers of
8133         // different nesting levels, like:
8134         //   __local int *** a;
8135         //   int ** b = a;
8136         // It's not clear how to actually determine when such pointers are
8137         // invalidly incompatible.
8138         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8139           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8140 
8141       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8142 
8143       if (lhptee == rhptee)
8144         return Sema::IncompatibleNestedPointerQualifiers;
8145     }
8146 
8147     // General pointer incompatibility takes priority over qualifiers.
8148     return Sema::IncompatiblePointer;
8149   }
8150   if (!S.getLangOpts().CPlusPlus &&
8151       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8152     return Sema::IncompatiblePointer;
8153   return ConvTy;
8154 }
8155 
8156 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8157 /// block pointer types are compatible or whether a block and normal pointer
8158 /// are compatible. It is more restrict than comparing two function pointer
8159 // types.
8160 static Sema::AssignConvertType
8161 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8162                                     QualType RHSType) {
8163   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8164   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8165 
8166   QualType lhptee, rhptee;
8167 
8168   // get the "pointed to" type (ignoring qualifiers at the top level)
8169   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8170   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8171 
8172   // In C++, the types have to match exactly.
8173   if (S.getLangOpts().CPlusPlus)
8174     return Sema::IncompatibleBlockPointer;
8175 
8176   Sema::AssignConvertType ConvTy = Sema::Compatible;
8177 
8178   // For blocks we enforce that qualifiers are identical.
8179   Qualifiers LQuals = lhptee.getLocalQualifiers();
8180   Qualifiers RQuals = rhptee.getLocalQualifiers();
8181   if (S.getLangOpts().OpenCL) {
8182     LQuals.removeAddressSpace();
8183     RQuals.removeAddressSpace();
8184   }
8185   if (LQuals != RQuals)
8186     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8187 
8188   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8189   // assignment.
8190   // The current behavior is similar to C++ lambdas. A block might be
8191   // assigned to a variable iff its return type and parameters are compatible
8192   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8193   // an assignment. Presumably it should behave in way that a function pointer
8194   // assignment does in C, so for each parameter and return type:
8195   //  * CVR and address space of LHS should be a superset of CVR and address
8196   //  space of RHS.
8197   //  * unqualified types should be compatible.
8198   if (S.getLangOpts().OpenCL) {
8199     if (!S.Context.typesAreBlockPointerCompatible(
8200             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8201             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8202       return Sema::IncompatibleBlockPointer;
8203   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8204     return Sema::IncompatibleBlockPointer;
8205 
8206   return ConvTy;
8207 }
8208 
8209 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8210 /// for assignment compatibility.
8211 static Sema::AssignConvertType
8212 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8213                                    QualType RHSType) {
8214   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8215   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8216 
8217   if (LHSType->isObjCBuiltinType()) {
8218     // Class is not compatible with ObjC object pointers.
8219     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8220         !RHSType->isObjCQualifiedClassType())
8221       return Sema::IncompatiblePointer;
8222     return Sema::Compatible;
8223   }
8224   if (RHSType->isObjCBuiltinType()) {
8225     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8226         !LHSType->isObjCQualifiedClassType())
8227       return Sema::IncompatiblePointer;
8228     return Sema::Compatible;
8229   }
8230   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8231   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8232 
8233   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8234       // make an exception for id<P>
8235       !LHSType->isObjCQualifiedIdType())
8236     return Sema::CompatiblePointerDiscardsQualifiers;
8237 
8238   if (S.Context.typesAreCompatible(LHSType, RHSType))
8239     return Sema::Compatible;
8240   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8241     return Sema::IncompatibleObjCQualifiedId;
8242   return Sema::IncompatiblePointer;
8243 }
8244 
8245 Sema::AssignConvertType
8246 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8247                                  QualType LHSType, QualType RHSType) {
8248   // Fake up an opaque expression.  We don't actually care about what
8249   // cast operations are required, so if CheckAssignmentConstraints
8250   // adds casts to this they'll be wasted, but fortunately that doesn't
8251   // usually happen on valid code.
8252   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8253   ExprResult RHSPtr = &RHSExpr;
8254   CastKind K;
8255 
8256   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8257 }
8258 
8259 /// This helper function returns true if QT is a vector type that has element
8260 /// type ElementType.
8261 static bool isVector(QualType QT, QualType ElementType) {
8262   if (const VectorType *VT = QT->getAs<VectorType>())
8263     return VT->getElementType() == ElementType;
8264   return false;
8265 }
8266 
8267 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8268 /// has code to accommodate several GCC extensions when type checking
8269 /// pointers. Here are some objectionable examples that GCC considers warnings:
8270 ///
8271 ///  int a, *pint;
8272 ///  short *pshort;
8273 ///  struct foo *pfoo;
8274 ///
8275 ///  pint = pshort; // warning: assignment from incompatible pointer type
8276 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8277 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8278 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8279 ///
8280 /// As a result, the code for dealing with pointers is more complex than the
8281 /// C99 spec dictates.
8282 ///
8283 /// Sets 'Kind' for any result kind except Incompatible.
8284 Sema::AssignConvertType
8285 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8286                                  CastKind &Kind, bool ConvertRHS) {
8287   QualType RHSType = RHS.get()->getType();
8288   QualType OrigLHSType = LHSType;
8289 
8290   // Get canonical types.  We're not formatting these types, just comparing
8291   // them.
8292   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8293   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8294 
8295   // Common case: no conversion required.
8296   if (LHSType == RHSType) {
8297     Kind = CK_NoOp;
8298     return Compatible;
8299   }
8300 
8301   // If we have an atomic type, try a non-atomic assignment, then just add an
8302   // atomic qualification step.
8303   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8304     Sema::AssignConvertType result =
8305       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8306     if (result != Compatible)
8307       return result;
8308     if (Kind != CK_NoOp && ConvertRHS)
8309       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8310     Kind = CK_NonAtomicToAtomic;
8311     return Compatible;
8312   }
8313 
8314   // If the left-hand side is a reference type, then we are in a
8315   // (rare!) case where we've allowed the use of references in C,
8316   // e.g., as a parameter type in a built-in function. In this case,
8317   // just make sure that the type referenced is compatible with the
8318   // right-hand side type. The caller is responsible for adjusting
8319   // LHSType so that the resulting expression does not have reference
8320   // type.
8321   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8322     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8323       Kind = CK_LValueBitCast;
8324       return Compatible;
8325     }
8326     return Incompatible;
8327   }
8328 
8329   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8330   // to the same ExtVector type.
8331   if (LHSType->isExtVectorType()) {
8332     if (RHSType->isExtVectorType())
8333       return Incompatible;
8334     if (RHSType->isArithmeticType()) {
8335       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8336       if (ConvertRHS)
8337         RHS = prepareVectorSplat(LHSType, RHS.get());
8338       Kind = CK_VectorSplat;
8339       return Compatible;
8340     }
8341   }
8342 
8343   // Conversions to or from vector type.
8344   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8345     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8346       // Allow assignments of an AltiVec vector type to an equivalent GCC
8347       // vector type and vice versa
8348       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8349         Kind = CK_BitCast;
8350         return Compatible;
8351       }
8352 
8353       // If we are allowing lax vector conversions, and LHS and RHS are both
8354       // vectors, the total size only needs to be the same. This is a bitcast;
8355       // no bits are changed but the result type is different.
8356       if (isLaxVectorConversion(RHSType, LHSType)) {
8357         Kind = CK_BitCast;
8358         return IncompatibleVectors;
8359       }
8360     }
8361 
8362     // When the RHS comes from another lax conversion (e.g. binops between
8363     // scalars and vectors) the result is canonicalized as a vector. When the
8364     // LHS is also a vector, the lax is allowed by the condition above. Handle
8365     // the case where LHS is a scalar.
8366     if (LHSType->isScalarType()) {
8367       const VectorType *VecType = RHSType->getAs<VectorType>();
8368       if (VecType && VecType->getNumElements() == 1 &&
8369           isLaxVectorConversion(RHSType, LHSType)) {
8370         ExprResult *VecExpr = &RHS;
8371         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8372         Kind = CK_BitCast;
8373         return Compatible;
8374       }
8375     }
8376 
8377     return Incompatible;
8378   }
8379 
8380   // Diagnose attempts to convert between __float128 and long double where
8381   // such conversions currently can't be handled.
8382   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8383     return Incompatible;
8384 
8385   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8386   // discards the imaginary part.
8387   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8388       !LHSType->getAs<ComplexType>())
8389     return Incompatible;
8390 
8391   // Arithmetic conversions.
8392   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8393       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8394     if (ConvertRHS)
8395       Kind = PrepareScalarCast(RHS, LHSType);
8396     return Compatible;
8397   }
8398 
8399   // Conversions to normal pointers.
8400   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8401     // U* -> T*
8402     if (isa<PointerType>(RHSType)) {
8403       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8404       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8405       if (AddrSpaceL != AddrSpaceR)
8406         Kind = CK_AddressSpaceConversion;
8407       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8408         Kind = CK_NoOp;
8409       else
8410         Kind = CK_BitCast;
8411       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8412     }
8413 
8414     // int -> T*
8415     if (RHSType->isIntegerType()) {
8416       Kind = CK_IntegralToPointer; // FIXME: null?
8417       return IntToPointer;
8418     }
8419 
8420     // C pointers are not compatible with ObjC object pointers,
8421     // with two exceptions:
8422     if (isa<ObjCObjectPointerType>(RHSType)) {
8423       //  - conversions to void*
8424       if (LHSPointer->getPointeeType()->isVoidType()) {
8425         Kind = CK_BitCast;
8426         return Compatible;
8427       }
8428 
8429       //  - conversions from 'Class' to the redefinition type
8430       if (RHSType->isObjCClassType() &&
8431           Context.hasSameType(LHSType,
8432                               Context.getObjCClassRedefinitionType())) {
8433         Kind = CK_BitCast;
8434         return Compatible;
8435       }
8436 
8437       Kind = CK_BitCast;
8438       return IncompatiblePointer;
8439     }
8440 
8441     // U^ -> void*
8442     if (RHSType->getAs<BlockPointerType>()) {
8443       if (LHSPointer->getPointeeType()->isVoidType()) {
8444         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8445         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8446                                 ->getPointeeType()
8447                                 .getAddressSpace();
8448         Kind =
8449             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8450         return Compatible;
8451       }
8452     }
8453 
8454     return Incompatible;
8455   }
8456 
8457   // Conversions to block pointers.
8458   if (isa<BlockPointerType>(LHSType)) {
8459     // U^ -> T^
8460     if (RHSType->isBlockPointerType()) {
8461       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8462                               ->getPointeeType()
8463                               .getAddressSpace();
8464       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8465                               ->getPointeeType()
8466                               .getAddressSpace();
8467       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8468       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8469     }
8470 
8471     // int or null -> T^
8472     if (RHSType->isIntegerType()) {
8473       Kind = CK_IntegralToPointer; // FIXME: null
8474       return IntToBlockPointer;
8475     }
8476 
8477     // id -> T^
8478     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8479       Kind = CK_AnyPointerToBlockPointerCast;
8480       return Compatible;
8481     }
8482 
8483     // void* -> T^
8484     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8485       if (RHSPT->getPointeeType()->isVoidType()) {
8486         Kind = CK_AnyPointerToBlockPointerCast;
8487         return Compatible;
8488       }
8489 
8490     return Incompatible;
8491   }
8492 
8493   // Conversions to Objective-C pointers.
8494   if (isa<ObjCObjectPointerType>(LHSType)) {
8495     // A* -> B*
8496     if (RHSType->isObjCObjectPointerType()) {
8497       Kind = CK_BitCast;
8498       Sema::AssignConvertType result =
8499         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8500       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8501           result == Compatible &&
8502           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8503         result = IncompatibleObjCWeakRef;
8504       return result;
8505     }
8506 
8507     // int or null -> A*
8508     if (RHSType->isIntegerType()) {
8509       Kind = CK_IntegralToPointer; // FIXME: null
8510       return IntToPointer;
8511     }
8512 
8513     // In general, C pointers are not compatible with ObjC object pointers,
8514     // with two exceptions:
8515     if (isa<PointerType>(RHSType)) {
8516       Kind = CK_CPointerToObjCPointerCast;
8517 
8518       //  - conversions from 'void*'
8519       if (RHSType->isVoidPointerType()) {
8520         return Compatible;
8521       }
8522 
8523       //  - conversions to 'Class' from its redefinition type
8524       if (LHSType->isObjCClassType() &&
8525           Context.hasSameType(RHSType,
8526                               Context.getObjCClassRedefinitionType())) {
8527         return Compatible;
8528       }
8529 
8530       return IncompatiblePointer;
8531     }
8532 
8533     // Only under strict condition T^ is compatible with an Objective-C pointer.
8534     if (RHSType->isBlockPointerType() &&
8535         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8536       if (ConvertRHS)
8537         maybeExtendBlockObject(RHS);
8538       Kind = CK_BlockPointerToObjCPointerCast;
8539       return Compatible;
8540     }
8541 
8542     return Incompatible;
8543   }
8544 
8545   // Conversions from pointers that are not covered by the above.
8546   if (isa<PointerType>(RHSType)) {
8547     // T* -> _Bool
8548     if (LHSType == Context.BoolTy) {
8549       Kind = CK_PointerToBoolean;
8550       return Compatible;
8551     }
8552 
8553     // T* -> int
8554     if (LHSType->isIntegerType()) {
8555       Kind = CK_PointerToIntegral;
8556       return PointerToInt;
8557     }
8558 
8559     return Incompatible;
8560   }
8561 
8562   // Conversions from Objective-C pointers that are not covered by the above.
8563   if (isa<ObjCObjectPointerType>(RHSType)) {
8564     // T* -> _Bool
8565     if (LHSType == Context.BoolTy) {
8566       Kind = CK_PointerToBoolean;
8567       return Compatible;
8568     }
8569 
8570     // T* -> int
8571     if (LHSType->isIntegerType()) {
8572       Kind = CK_PointerToIntegral;
8573       return PointerToInt;
8574     }
8575 
8576     return Incompatible;
8577   }
8578 
8579   // struct A -> struct B
8580   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8581     if (Context.typesAreCompatible(LHSType, RHSType)) {
8582       Kind = CK_NoOp;
8583       return Compatible;
8584     }
8585   }
8586 
8587   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8588     Kind = CK_IntToOCLSampler;
8589     return Compatible;
8590   }
8591 
8592   return Incompatible;
8593 }
8594 
8595 /// Constructs a transparent union from an expression that is
8596 /// used to initialize the transparent union.
8597 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8598                                       ExprResult &EResult, QualType UnionType,
8599                                       FieldDecl *Field) {
8600   // Build an initializer list that designates the appropriate member
8601   // of the transparent union.
8602   Expr *E = EResult.get();
8603   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8604                                                    E, SourceLocation());
8605   Initializer->setType(UnionType);
8606   Initializer->setInitializedFieldInUnion(Field);
8607 
8608   // Build a compound literal constructing a value of the transparent
8609   // union type from this initializer list.
8610   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8611   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8612                                         VK_RValue, Initializer, false);
8613 }
8614 
8615 Sema::AssignConvertType
8616 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8617                                                ExprResult &RHS) {
8618   QualType RHSType = RHS.get()->getType();
8619 
8620   // If the ArgType is a Union type, we want to handle a potential
8621   // transparent_union GCC extension.
8622   const RecordType *UT = ArgType->getAsUnionType();
8623   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8624     return Incompatible;
8625 
8626   // The field to initialize within the transparent union.
8627   RecordDecl *UD = UT->getDecl();
8628   FieldDecl *InitField = nullptr;
8629   // It's compatible if the expression matches any of the fields.
8630   for (auto *it : UD->fields()) {
8631     if (it->getType()->isPointerType()) {
8632       // If the transparent union contains a pointer type, we allow:
8633       // 1) void pointer
8634       // 2) null pointer constant
8635       if (RHSType->isPointerType())
8636         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8637           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8638           InitField = it;
8639           break;
8640         }
8641 
8642       if (RHS.get()->isNullPointerConstant(Context,
8643                                            Expr::NPC_ValueDependentIsNull)) {
8644         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8645                                 CK_NullToPointer);
8646         InitField = it;
8647         break;
8648       }
8649     }
8650 
8651     CastKind Kind;
8652     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8653           == Compatible) {
8654       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8655       InitField = it;
8656       break;
8657     }
8658   }
8659 
8660   if (!InitField)
8661     return Incompatible;
8662 
8663   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8664   return Compatible;
8665 }
8666 
8667 Sema::AssignConvertType
8668 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8669                                        bool Diagnose,
8670                                        bool DiagnoseCFAudited,
8671                                        bool ConvertRHS) {
8672   // We need to be able to tell the caller whether we diagnosed a problem, if
8673   // they ask us to issue diagnostics.
8674   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8675 
8676   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8677   // we can't avoid *all* modifications at the moment, so we need some somewhere
8678   // to put the updated value.
8679   ExprResult LocalRHS = CallerRHS;
8680   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8681 
8682   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8683     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8684       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8685           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8686         Diag(RHS.get()->getExprLoc(),
8687              diag::warn_noderef_to_dereferenceable_pointer)
8688             << RHS.get()->getSourceRange();
8689       }
8690     }
8691   }
8692 
8693   if (getLangOpts().CPlusPlus) {
8694     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8695       // C++ 5.17p3: If the left operand is not of class type, the
8696       // expression is implicitly converted (C++ 4) to the
8697       // cv-unqualified type of the left operand.
8698       QualType RHSType = RHS.get()->getType();
8699       if (Diagnose) {
8700         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8701                                         AA_Assigning);
8702       } else {
8703         ImplicitConversionSequence ICS =
8704             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8705                                   /*SuppressUserConversions=*/false,
8706                                   AllowedExplicit::None,
8707                                   /*InOverloadResolution=*/false,
8708                                   /*CStyle=*/false,
8709                                   /*AllowObjCWritebackConversion=*/false);
8710         if (ICS.isFailure())
8711           return Incompatible;
8712         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8713                                         ICS, AA_Assigning);
8714       }
8715       if (RHS.isInvalid())
8716         return Incompatible;
8717       Sema::AssignConvertType result = Compatible;
8718       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8719           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8720         result = IncompatibleObjCWeakRef;
8721       return result;
8722     }
8723 
8724     // FIXME: Currently, we fall through and treat C++ classes like C
8725     // structures.
8726     // FIXME: We also fall through for atomics; not sure what should
8727     // happen there, though.
8728   } else if (RHS.get()->getType() == Context.OverloadTy) {
8729     // As a set of extensions to C, we support overloading on functions. These
8730     // functions need to be resolved here.
8731     DeclAccessPair DAP;
8732     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8733             RHS.get(), LHSType, /*Complain=*/false, DAP))
8734       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8735     else
8736       return Incompatible;
8737   }
8738 
8739   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8740   // a null pointer constant.
8741   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8742        LHSType->isBlockPointerType()) &&
8743       RHS.get()->isNullPointerConstant(Context,
8744                                        Expr::NPC_ValueDependentIsNull)) {
8745     if (Diagnose || ConvertRHS) {
8746       CastKind Kind;
8747       CXXCastPath Path;
8748       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8749                              /*IgnoreBaseAccess=*/false, Diagnose);
8750       if (ConvertRHS)
8751         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8752     }
8753     return Compatible;
8754   }
8755 
8756   // OpenCL queue_t type assignment.
8757   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8758                                  Context, Expr::NPC_ValueDependentIsNull)) {
8759     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8760     return Compatible;
8761   }
8762 
8763   // This check seems unnatural, however it is necessary to ensure the proper
8764   // conversion of functions/arrays. If the conversion were done for all
8765   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8766   // expressions that suppress this implicit conversion (&, sizeof).
8767   //
8768   // Suppress this for references: C++ 8.5.3p5.
8769   if (!LHSType->isReferenceType()) {
8770     // FIXME: We potentially allocate here even if ConvertRHS is false.
8771     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8772     if (RHS.isInvalid())
8773       return Incompatible;
8774   }
8775   CastKind Kind;
8776   Sema::AssignConvertType result =
8777     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8778 
8779   // C99 6.5.16.1p2: The value of the right operand is converted to the
8780   // type of the assignment expression.
8781   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8782   // so that we can use references in built-in functions even in C.
8783   // The getNonReferenceType() call makes sure that the resulting expression
8784   // does not have reference type.
8785   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8786     QualType Ty = LHSType.getNonLValueExprType(Context);
8787     Expr *E = RHS.get();
8788 
8789     // Check for various Objective-C errors. If we are not reporting
8790     // diagnostics and just checking for errors, e.g., during overload
8791     // resolution, return Incompatible to indicate the failure.
8792     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8793         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8794                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8795       if (!Diagnose)
8796         return Incompatible;
8797     }
8798     if (getLangOpts().ObjC &&
8799         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8800                                            E->getType(), E, Diagnose) ||
8801          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8802       if (!Diagnose)
8803         return Incompatible;
8804       // Replace the expression with a corrected version and continue so we
8805       // can find further errors.
8806       RHS = E;
8807       return Compatible;
8808     }
8809 
8810     if (ConvertRHS)
8811       RHS = ImpCastExprToType(E, Ty, Kind);
8812   }
8813 
8814   return result;
8815 }
8816 
8817 namespace {
8818 /// The original operand to an operator, prior to the application of the usual
8819 /// arithmetic conversions and converting the arguments of a builtin operator
8820 /// candidate.
8821 struct OriginalOperand {
8822   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8823     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8824       Op = MTE->getSubExpr();
8825     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8826       Op = BTE->getSubExpr();
8827     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8828       Orig = ICE->getSubExprAsWritten();
8829       Conversion = ICE->getConversionFunction();
8830     }
8831   }
8832 
8833   QualType getType() const { return Orig->getType(); }
8834 
8835   Expr *Orig;
8836   NamedDecl *Conversion;
8837 };
8838 }
8839 
8840 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8841                                ExprResult &RHS) {
8842   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8843 
8844   Diag(Loc, diag::err_typecheck_invalid_operands)
8845     << OrigLHS.getType() << OrigRHS.getType()
8846     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8847 
8848   // If a user-defined conversion was applied to either of the operands prior
8849   // to applying the built-in operator rules, tell the user about it.
8850   if (OrigLHS.Conversion) {
8851     Diag(OrigLHS.Conversion->getLocation(),
8852          diag::note_typecheck_invalid_operands_converted)
8853       << 0 << LHS.get()->getType();
8854   }
8855   if (OrigRHS.Conversion) {
8856     Diag(OrigRHS.Conversion->getLocation(),
8857          diag::note_typecheck_invalid_operands_converted)
8858       << 1 << RHS.get()->getType();
8859   }
8860 
8861   return QualType();
8862 }
8863 
8864 // Diagnose cases where a scalar was implicitly converted to a vector and
8865 // diagnose the underlying types. Otherwise, diagnose the error
8866 // as invalid vector logical operands for non-C++ cases.
8867 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8868                                             ExprResult &RHS) {
8869   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8870   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8871 
8872   bool LHSNatVec = LHSType->isVectorType();
8873   bool RHSNatVec = RHSType->isVectorType();
8874 
8875   if (!(LHSNatVec && RHSNatVec)) {
8876     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8877     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8878     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8879         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8880         << Vector->getSourceRange();
8881     return QualType();
8882   }
8883 
8884   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8885       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8886       << RHS.get()->getSourceRange();
8887 
8888   return QualType();
8889 }
8890 
8891 /// Try to convert a value of non-vector type to a vector type by converting
8892 /// the type to the element type of the vector and then performing a splat.
8893 /// If the language is OpenCL, we only use conversions that promote scalar
8894 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8895 /// for float->int.
8896 ///
8897 /// OpenCL V2.0 6.2.6.p2:
8898 /// An error shall occur if any scalar operand type has greater rank
8899 /// than the type of the vector element.
8900 ///
8901 /// \param scalar - if non-null, actually perform the conversions
8902 /// \return true if the operation fails (but without diagnosing the failure)
8903 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8904                                      QualType scalarTy,
8905                                      QualType vectorEltTy,
8906                                      QualType vectorTy,
8907                                      unsigned &DiagID) {
8908   // The conversion to apply to the scalar before splatting it,
8909   // if necessary.
8910   CastKind scalarCast = CK_NoOp;
8911 
8912   if (vectorEltTy->isIntegralType(S.Context)) {
8913     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8914         (scalarTy->isIntegerType() &&
8915          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8916       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8917       return true;
8918     }
8919     if (!scalarTy->isIntegralType(S.Context))
8920       return true;
8921     scalarCast = CK_IntegralCast;
8922   } else if (vectorEltTy->isRealFloatingType()) {
8923     if (scalarTy->isRealFloatingType()) {
8924       if (S.getLangOpts().OpenCL &&
8925           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8926         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8927         return true;
8928       }
8929       scalarCast = CK_FloatingCast;
8930     }
8931     else if (scalarTy->isIntegralType(S.Context))
8932       scalarCast = CK_IntegralToFloating;
8933     else
8934       return true;
8935   } else {
8936     return true;
8937   }
8938 
8939   // Adjust scalar if desired.
8940   if (scalar) {
8941     if (scalarCast != CK_NoOp)
8942       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8943     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8944   }
8945   return false;
8946 }
8947 
8948 /// Convert vector E to a vector with the same number of elements but different
8949 /// element type.
8950 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8951   const auto *VecTy = E->getType()->getAs<VectorType>();
8952   assert(VecTy && "Expression E must be a vector");
8953   QualType NewVecTy = S.Context.getVectorType(ElementType,
8954                                               VecTy->getNumElements(),
8955                                               VecTy->getVectorKind());
8956 
8957   // Look through the implicit cast. Return the subexpression if its type is
8958   // NewVecTy.
8959   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8960     if (ICE->getSubExpr()->getType() == NewVecTy)
8961       return ICE->getSubExpr();
8962 
8963   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8964   return S.ImpCastExprToType(E, NewVecTy, Cast);
8965 }
8966 
8967 /// Test if a (constant) integer Int can be casted to another integer type
8968 /// IntTy without losing precision.
8969 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8970                                       QualType OtherIntTy) {
8971   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8972 
8973   // Reject cases where the value of the Int is unknown as that would
8974   // possibly cause truncation, but accept cases where the scalar can be
8975   // demoted without loss of precision.
8976   Expr::EvalResult EVResult;
8977   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8978   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8979   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8980   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8981 
8982   if (CstInt) {
8983     // If the scalar is constant and is of a higher order and has more active
8984     // bits that the vector element type, reject it.
8985     llvm::APSInt Result = EVResult.Val.getInt();
8986     unsigned NumBits = IntSigned
8987                            ? (Result.isNegative() ? Result.getMinSignedBits()
8988                                                   : Result.getActiveBits())
8989                            : Result.getActiveBits();
8990     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8991       return true;
8992 
8993     // If the signedness of the scalar type and the vector element type
8994     // differs and the number of bits is greater than that of the vector
8995     // element reject it.
8996     return (IntSigned != OtherIntSigned &&
8997             NumBits > S.Context.getIntWidth(OtherIntTy));
8998   }
8999 
9000   // Reject cases where the value of the scalar is not constant and it's
9001   // order is greater than that of the vector element type.
9002   return (Order < 0);
9003 }
9004 
9005 /// Test if a (constant) integer Int can be casted to floating point type
9006 /// FloatTy without losing precision.
9007 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9008                                      QualType FloatTy) {
9009   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9010 
9011   // Determine if the integer constant can be expressed as a floating point
9012   // number of the appropriate type.
9013   Expr::EvalResult EVResult;
9014   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9015 
9016   uint64_t Bits = 0;
9017   if (CstInt) {
9018     // Reject constants that would be truncated if they were converted to
9019     // the floating point type. Test by simple to/from conversion.
9020     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9021     //        could be avoided if there was a convertFromAPInt method
9022     //        which could signal back if implicit truncation occurred.
9023     llvm::APSInt Result = EVResult.Val.getInt();
9024     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9025     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9026                            llvm::APFloat::rmTowardZero);
9027     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9028                              !IntTy->hasSignedIntegerRepresentation());
9029     bool Ignored = false;
9030     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9031                            &Ignored);
9032     if (Result != ConvertBack)
9033       return true;
9034   } else {
9035     // Reject types that cannot be fully encoded into the mantissa of
9036     // the float.
9037     Bits = S.Context.getTypeSize(IntTy);
9038     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9039         S.Context.getFloatTypeSemantics(FloatTy));
9040     if (Bits > FloatPrec)
9041       return true;
9042   }
9043 
9044   return false;
9045 }
9046 
9047 /// Attempt to convert and splat Scalar into a vector whose types matches
9048 /// Vector following GCC conversion rules. The rule is that implicit
9049 /// conversion can occur when Scalar can be casted to match Vector's element
9050 /// type without causing truncation of Scalar.
9051 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9052                                         ExprResult *Vector) {
9053   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9054   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9055   const VectorType *VT = VectorTy->getAs<VectorType>();
9056 
9057   assert(!isa<ExtVectorType>(VT) &&
9058          "ExtVectorTypes should not be handled here!");
9059 
9060   QualType VectorEltTy = VT->getElementType();
9061 
9062   // Reject cases where the vector element type or the scalar element type are
9063   // not integral or floating point types.
9064   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9065     return true;
9066 
9067   // The conversion to apply to the scalar before splatting it,
9068   // if necessary.
9069   CastKind ScalarCast = CK_NoOp;
9070 
9071   // Accept cases where the vector elements are integers and the scalar is
9072   // an integer.
9073   // FIXME: Notionally if the scalar was a floating point value with a precise
9074   //        integral representation, we could cast it to an appropriate integer
9075   //        type and then perform the rest of the checks here. GCC will perform
9076   //        this conversion in some cases as determined by the input language.
9077   //        We should accept it on a language independent basis.
9078   if (VectorEltTy->isIntegralType(S.Context) &&
9079       ScalarTy->isIntegralType(S.Context) &&
9080       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9081 
9082     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9083       return true;
9084 
9085     ScalarCast = CK_IntegralCast;
9086   } else if (VectorEltTy->isIntegralType(S.Context) &&
9087              ScalarTy->isRealFloatingType()) {
9088     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9089       ScalarCast = CK_FloatingToIntegral;
9090     else
9091       return true;
9092   } else if (VectorEltTy->isRealFloatingType()) {
9093     if (ScalarTy->isRealFloatingType()) {
9094 
9095       // Reject cases where the scalar type is not a constant and has a higher
9096       // Order than the vector element type.
9097       llvm::APFloat Result(0.0);
9098       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
9099       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9100       if (!CstScalar && Order < 0)
9101         return true;
9102 
9103       // If the scalar cannot be safely casted to the vector element type,
9104       // reject it.
9105       if (CstScalar) {
9106         bool Truncated = false;
9107         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9108                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9109         if (Truncated)
9110           return true;
9111       }
9112 
9113       ScalarCast = CK_FloatingCast;
9114     } else if (ScalarTy->isIntegralType(S.Context)) {
9115       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9116         return true;
9117 
9118       ScalarCast = CK_IntegralToFloating;
9119     } else
9120       return true;
9121   }
9122 
9123   // Adjust scalar if desired.
9124   if (Scalar) {
9125     if (ScalarCast != CK_NoOp)
9126       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9127     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9128   }
9129   return false;
9130 }
9131 
9132 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9133                                    SourceLocation Loc, bool IsCompAssign,
9134                                    bool AllowBothBool,
9135                                    bool AllowBoolConversions) {
9136   if (!IsCompAssign) {
9137     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9138     if (LHS.isInvalid())
9139       return QualType();
9140   }
9141   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9142   if (RHS.isInvalid())
9143     return QualType();
9144 
9145   // For conversion purposes, we ignore any qualifiers.
9146   // For example, "const float" and "float" are equivalent.
9147   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9148   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9149 
9150   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9151   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9152   assert(LHSVecType || RHSVecType);
9153 
9154   // AltiVec-style "vector bool op vector bool" combinations are allowed
9155   // for some operators but not others.
9156   if (!AllowBothBool &&
9157       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9158       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9159     return InvalidOperands(Loc, LHS, RHS);
9160 
9161   // If the vector types are identical, return.
9162   if (Context.hasSameType(LHSType, RHSType))
9163     return LHSType;
9164 
9165   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9166   if (LHSVecType && RHSVecType &&
9167       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9168     if (isa<ExtVectorType>(LHSVecType)) {
9169       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9170       return LHSType;
9171     }
9172 
9173     if (!IsCompAssign)
9174       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9175     return RHSType;
9176   }
9177 
9178   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9179   // can be mixed, with the result being the non-bool type.  The non-bool
9180   // operand must have integer element type.
9181   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9182       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9183       (Context.getTypeSize(LHSVecType->getElementType()) ==
9184        Context.getTypeSize(RHSVecType->getElementType()))) {
9185     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9186         LHSVecType->getElementType()->isIntegerType() &&
9187         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9188       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9189       return LHSType;
9190     }
9191     if (!IsCompAssign &&
9192         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9193         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9194         RHSVecType->getElementType()->isIntegerType()) {
9195       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9196       return RHSType;
9197     }
9198   }
9199 
9200   // If there's a vector type and a scalar, try to convert the scalar to
9201   // the vector element type and splat.
9202   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9203   if (!RHSVecType) {
9204     if (isa<ExtVectorType>(LHSVecType)) {
9205       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9206                                     LHSVecType->getElementType(), LHSType,
9207                                     DiagID))
9208         return LHSType;
9209     } else {
9210       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9211         return LHSType;
9212     }
9213   }
9214   if (!LHSVecType) {
9215     if (isa<ExtVectorType>(RHSVecType)) {
9216       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9217                                     LHSType, RHSVecType->getElementType(),
9218                                     RHSType, DiagID))
9219         return RHSType;
9220     } else {
9221       if (LHS.get()->getValueKind() == VK_LValue ||
9222           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9223         return RHSType;
9224     }
9225   }
9226 
9227   // FIXME: The code below also handles conversion between vectors and
9228   // non-scalars, we should break this down into fine grained specific checks
9229   // and emit proper diagnostics.
9230   QualType VecType = LHSVecType ? LHSType : RHSType;
9231   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9232   QualType OtherType = LHSVecType ? RHSType : LHSType;
9233   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9234   if (isLaxVectorConversion(OtherType, VecType)) {
9235     // If we're allowing lax vector conversions, only the total (data) size
9236     // needs to be the same. For non compound assignment, if one of the types is
9237     // scalar, the result is always the vector type.
9238     if (!IsCompAssign) {
9239       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9240       return VecType;
9241     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9242     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9243     // type. Note that this is already done by non-compound assignments in
9244     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9245     // <1 x T> -> T. The result is also a vector type.
9246     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9247                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9248       ExprResult *RHSExpr = &RHS;
9249       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9250       return VecType;
9251     }
9252   }
9253 
9254   // Okay, the expression is invalid.
9255 
9256   // If there's a non-vector, non-real operand, diagnose that.
9257   if ((!RHSVecType && !RHSType->isRealType()) ||
9258       (!LHSVecType && !LHSType->isRealType())) {
9259     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9260       << LHSType << RHSType
9261       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9262     return QualType();
9263   }
9264 
9265   // OpenCL V1.1 6.2.6.p1:
9266   // If the operands are of more than one vector type, then an error shall
9267   // occur. Implicit conversions between vector types are not permitted, per
9268   // section 6.2.1.
9269   if (getLangOpts().OpenCL &&
9270       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9271       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9272     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9273                                                            << RHSType;
9274     return QualType();
9275   }
9276 
9277 
9278   // If there is a vector type that is not a ExtVector and a scalar, we reach
9279   // this point if scalar could not be converted to the vector's element type
9280   // without truncation.
9281   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9282       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9283     QualType Scalar = LHSVecType ? RHSType : LHSType;
9284     QualType Vector = LHSVecType ? LHSType : RHSType;
9285     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9286     Diag(Loc,
9287          diag::err_typecheck_vector_not_convertable_implict_truncation)
9288         << ScalarOrVector << Scalar << Vector;
9289 
9290     return QualType();
9291   }
9292 
9293   // Otherwise, use the generic diagnostic.
9294   Diag(Loc, DiagID)
9295     << LHSType << RHSType
9296     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9297   return QualType();
9298 }
9299 
9300 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9301 // expression.  These are mainly cases where the null pointer is used as an
9302 // integer instead of a pointer.
9303 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9304                                 SourceLocation Loc, bool IsCompare) {
9305   // The canonical way to check for a GNU null is with isNullPointerConstant,
9306   // but we use a bit of a hack here for speed; this is a relatively
9307   // hot path, and isNullPointerConstant is slow.
9308   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9309   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9310 
9311   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9312 
9313   // Avoid analyzing cases where the result will either be invalid (and
9314   // diagnosed as such) or entirely valid and not something to warn about.
9315   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9316       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9317     return;
9318 
9319   // Comparison operations would not make sense with a null pointer no matter
9320   // what the other expression is.
9321   if (!IsCompare) {
9322     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9323         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9324         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9325     return;
9326   }
9327 
9328   // The rest of the operations only make sense with a null pointer
9329   // if the other expression is a pointer.
9330   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9331       NonNullType->canDecayToPointerType())
9332     return;
9333 
9334   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9335       << LHSNull /* LHS is NULL */ << NonNullType
9336       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9337 }
9338 
9339 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9340                                           SourceLocation Loc) {
9341   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9342   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9343   if (!LUE || !RUE)
9344     return;
9345   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9346       RUE->getKind() != UETT_SizeOf)
9347     return;
9348 
9349   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9350   QualType LHSTy = LHSArg->getType();
9351   QualType RHSTy;
9352 
9353   if (RUE->isArgumentType())
9354     RHSTy = RUE->getArgumentType();
9355   else
9356     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9357 
9358   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9359     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9360       return;
9361 
9362     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9363     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9364       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9365         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9366             << LHSArgDecl;
9367     }
9368   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9369     QualType ArrayElemTy = ArrayTy->getElementType();
9370     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9371         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9372         ArrayElemTy->isCharType() ||
9373         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9374       return;
9375     S.Diag(Loc, diag::warn_division_sizeof_array)
9376         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9377     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9378       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9379         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9380             << LHSArgDecl;
9381     }
9382 
9383     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9384   }
9385 }
9386 
9387 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9388                                                ExprResult &RHS,
9389                                                SourceLocation Loc, bool IsDiv) {
9390   // Check for division/remainder by zero.
9391   Expr::EvalResult RHSValue;
9392   if (!RHS.get()->isValueDependent() &&
9393       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9394       RHSValue.Val.getInt() == 0)
9395     S.DiagRuntimeBehavior(Loc, RHS.get(),
9396                           S.PDiag(diag::warn_remainder_division_by_zero)
9397                             << IsDiv << RHS.get()->getSourceRange());
9398 }
9399 
9400 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9401                                            SourceLocation Loc,
9402                                            bool IsCompAssign, bool IsDiv) {
9403   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9404 
9405   if (LHS.get()->getType()->isVectorType() ||
9406       RHS.get()->getType()->isVectorType())
9407     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9408                                /*AllowBothBool*/getLangOpts().AltiVec,
9409                                /*AllowBoolConversions*/false);
9410 
9411   QualType compType = UsualArithmeticConversions(
9412       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9413   if (LHS.isInvalid() || RHS.isInvalid())
9414     return QualType();
9415 
9416 
9417   if (compType.isNull() || !compType->isArithmeticType())
9418     return InvalidOperands(Loc, LHS, RHS);
9419   if (IsDiv) {
9420     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9421     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9422   }
9423   return compType;
9424 }
9425 
9426 QualType Sema::CheckRemainderOperands(
9427   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9428   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9429 
9430   if (LHS.get()->getType()->isVectorType() ||
9431       RHS.get()->getType()->isVectorType()) {
9432     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9433         RHS.get()->getType()->hasIntegerRepresentation())
9434       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9435                                  /*AllowBothBool*/getLangOpts().AltiVec,
9436                                  /*AllowBoolConversions*/false);
9437     return InvalidOperands(Loc, LHS, RHS);
9438   }
9439 
9440   QualType compType = UsualArithmeticConversions(
9441       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9442   if (LHS.isInvalid() || RHS.isInvalid())
9443     return QualType();
9444 
9445   if (compType.isNull() || !compType->isIntegerType())
9446     return InvalidOperands(Loc, LHS, RHS);
9447   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9448   return compType;
9449 }
9450 
9451 /// Diagnose invalid arithmetic on two void pointers.
9452 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9453                                                 Expr *LHSExpr, Expr *RHSExpr) {
9454   S.Diag(Loc, S.getLangOpts().CPlusPlus
9455                 ? diag::err_typecheck_pointer_arith_void_type
9456                 : diag::ext_gnu_void_ptr)
9457     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9458                             << RHSExpr->getSourceRange();
9459 }
9460 
9461 /// Diagnose invalid arithmetic on a void pointer.
9462 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9463                                             Expr *Pointer) {
9464   S.Diag(Loc, S.getLangOpts().CPlusPlus
9465                 ? diag::err_typecheck_pointer_arith_void_type
9466                 : diag::ext_gnu_void_ptr)
9467     << 0 /* one pointer */ << Pointer->getSourceRange();
9468 }
9469 
9470 /// Diagnose invalid arithmetic on a null pointer.
9471 ///
9472 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9473 /// idiom, which we recognize as a GNU extension.
9474 ///
9475 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9476                                             Expr *Pointer, bool IsGNUIdiom) {
9477   if (IsGNUIdiom)
9478     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9479       << Pointer->getSourceRange();
9480   else
9481     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9482       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9483 }
9484 
9485 /// Diagnose invalid arithmetic on two function pointers.
9486 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9487                                                     Expr *LHS, Expr *RHS) {
9488   assert(LHS->getType()->isAnyPointerType());
9489   assert(RHS->getType()->isAnyPointerType());
9490   S.Diag(Loc, S.getLangOpts().CPlusPlus
9491                 ? diag::err_typecheck_pointer_arith_function_type
9492                 : diag::ext_gnu_ptr_func_arith)
9493     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9494     // We only show the second type if it differs from the first.
9495     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9496                                                    RHS->getType())
9497     << RHS->getType()->getPointeeType()
9498     << LHS->getSourceRange() << RHS->getSourceRange();
9499 }
9500 
9501 /// Diagnose invalid arithmetic on a function pointer.
9502 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9503                                                 Expr *Pointer) {
9504   assert(Pointer->getType()->isAnyPointerType());
9505   S.Diag(Loc, S.getLangOpts().CPlusPlus
9506                 ? diag::err_typecheck_pointer_arith_function_type
9507                 : diag::ext_gnu_ptr_func_arith)
9508     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9509     << 0 /* one pointer, so only one type */
9510     << Pointer->getSourceRange();
9511 }
9512 
9513 /// Emit error if Operand is incomplete pointer type
9514 ///
9515 /// \returns True if pointer has incomplete type
9516 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9517                                                  Expr *Operand) {
9518   QualType ResType = Operand->getType();
9519   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9520     ResType = ResAtomicType->getValueType();
9521 
9522   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9523   QualType PointeeTy = ResType->getPointeeType();
9524   return S.RequireCompleteType(Loc, PointeeTy,
9525                                diag::err_typecheck_arithmetic_incomplete_type,
9526                                PointeeTy, Operand->getSourceRange());
9527 }
9528 
9529 /// Check the validity of an arithmetic pointer operand.
9530 ///
9531 /// If the operand has pointer type, this code will check for pointer types
9532 /// which are invalid in arithmetic operations. These will be diagnosed
9533 /// appropriately, including whether or not the use is supported as an
9534 /// extension.
9535 ///
9536 /// \returns True when the operand is valid to use (even if as an extension).
9537 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9538                                             Expr *Operand) {
9539   QualType ResType = Operand->getType();
9540   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9541     ResType = ResAtomicType->getValueType();
9542 
9543   if (!ResType->isAnyPointerType()) return true;
9544 
9545   QualType PointeeTy = ResType->getPointeeType();
9546   if (PointeeTy->isVoidType()) {
9547     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9548     return !S.getLangOpts().CPlusPlus;
9549   }
9550   if (PointeeTy->isFunctionType()) {
9551     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9552     return !S.getLangOpts().CPlusPlus;
9553   }
9554 
9555   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9556 
9557   return true;
9558 }
9559 
9560 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9561 /// operands.
9562 ///
9563 /// This routine will diagnose any invalid arithmetic on pointer operands much
9564 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9565 /// for emitting a single diagnostic even for operations where both LHS and RHS
9566 /// are (potentially problematic) pointers.
9567 ///
9568 /// \returns True when the operand is valid to use (even if as an extension).
9569 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9570                                                 Expr *LHSExpr, Expr *RHSExpr) {
9571   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9572   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9573   if (!isLHSPointer && !isRHSPointer) return true;
9574 
9575   QualType LHSPointeeTy, RHSPointeeTy;
9576   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9577   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9578 
9579   // if both are pointers check if operation is valid wrt address spaces
9580   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9581     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9582     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9583     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9584       S.Diag(Loc,
9585              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9586           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9587           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9588       return false;
9589     }
9590   }
9591 
9592   // Check for arithmetic on pointers to incomplete types.
9593   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9594   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9595   if (isLHSVoidPtr || isRHSVoidPtr) {
9596     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9597     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9598     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9599 
9600     return !S.getLangOpts().CPlusPlus;
9601   }
9602 
9603   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9604   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9605   if (isLHSFuncPtr || isRHSFuncPtr) {
9606     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9607     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9608                                                                 RHSExpr);
9609     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9610 
9611     return !S.getLangOpts().CPlusPlus;
9612   }
9613 
9614   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9615     return false;
9616   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9617     return false;
9618 
9619   return true;
9620 }
9621 
9622 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9623 /// literal.
9624 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9625                                   Expr *LHSExpr, Expr *RHSExpr) {
9626   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9627   Expr* IndexExpr = RHSExpr;
9628   if (!StrExpr) {
9629     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9630     IndexExpr = LHSExpr;
9631   }
9632 
9633   bool IsStringPlusInt = StrExpr &&
9634       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9635   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9636     return;
9637 
9638   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9639   Self.Diag(OpLoc, diag::warn_string_plus_int)
9640       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9641 
9642   // Only print a fixit for "str" + int, not for int + "str".
9643   if (IndexExpr == RHSExpr) {
9644     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9645     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9646         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9647         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9648         << FixItHint::CreateInsertion(EndLoc, "]");
9649   } else
9650     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9651 }
9652 
9653 /// Emit a warning when adding a char literal to a string.
9654 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9655                                    Expr *LHSExpr, Expr *RHSExpr) {
9656   const Expr *StringRefExpr = LHSExpr;
9657   const CharacterLiteral *CharExpr =
9658       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9659 
9660   if (!CharExpr) {
9661     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9662     StringRefExpr = RHSExpr;
9663   }
9664 
9665   if (!CharExpr || !StringRefExpr)
9666     return;
9667 
9668   const QualType StringType = StringRefExpr->getType();
9669 
9670   // Return if not a PointerType.
9671   if (!StringType->isAnyPointerType())
9672     return;
9673 
9674   // Return if not a CharacterType.
9675   if (!StringType->getPointeeType()->isAnyCharacterType())
9676     return;
9677 
9678   ASTContext &Ctx = Self.getASTContext();
9679   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9680 
9681   const QualType CharType = CharExpr->getType();
9682   if (!CharType->isAnyCharacterType() &&
9683       CharType->isIntegerType() &&
9684       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9685     Self.Diag(OpLoc, diag::warn_string_plus_char)
9686         << DiagRange << Ctx.CharTy;
9687   } else {
9688     Self.Diag(OpLoc, diag::warn_string_plus_char)
9689         << DiagRange << CharExpr->getType();
9690   }
9691 
9692   // Only print a fixit for str + char, not for char + str.
9693   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9694     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9695     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9696         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9697         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9698         << FixItHint::CreateInsertion(EndLoc, "]");
9699   } else {
9700     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9701   }
9702 }
9703 
9704 /// Emit error when two pointers are incompatible.
9705 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9706                                            Expr *LHSExpr, Expr *RHSExpr) {
9707   assert(LHSExpr->getType()->isAnyPointerType());
9708   assert(RHSExpr->getType()->isAnyPointerType());
9709   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9710     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9711     << RHSExpr->getSourceRange();
9712 }
9713 
9714 // C99 6.5.6
9715 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9716                                      SourceLocation Loc, BinaryOperatorKind Opc,
9717                                      QualType* CompLHSTy) {
9718   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9719 
9720   if (LHS.get()->getType()->isVectorType() ||
9721       RHS.get()->getType()->isVectorType()) {
9722     QualType compType = CheckVectorOperands(
9723         LHS, RHS, Loc, CompLHSTy,
9724         /*AllowBothBool*/getLangOpts().AltiVec,
9725         /*AllowBoolConversions*/getLangOpts().ZVector);
9726     if (CompLHSTy) *CompLHSTy = compType;
9727     return compType;
9728   }
9729 
9730   QualType compType = UsualArithmeticConversions(
9731       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9732   if (LHS.isInvalid() || RHS.isInvalid())
9733     return QualType();
9734 
9735   // Diagnose "string literal" '+' int and string '+' "char literal".
9736   if (Opc == BO_Add) {
9737     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9738     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9739   }
9740 
9741   // handle the common case first (both operands are arithmetic).
9742   if (!compType.isNull() && compType->isArithmeticType()) {
9743     if (CompLHSTy) *CompLHSTy = compType;
9744     return compType;
9745   }
9746 
9747   // Type-checking.  Ultimately the pointer's going to be in PExp;
9748   // note that we bias towards the LHS being the pointer.
9749   Expr *PExp = LHS.get(), *IExp = RHS.get();
9750 
9751   bool isObjCPointer;
9752   if (PExp->getType()->isPointerType()) {
9753     isObjCPointer = false;
9754   } else if (PExp->getType()->isObjCObjectPointerType()) {
9755     isObjCPointer = true;
9756   } else {
9757     std::swap(PExp, IExp);
9758     if (PExp->getType()->isPointerType()) {
9759       isObjCPointer = false;
9760     } else if (PExp->getType()->isObjCObjectPointerType()) {
9761       isObjCPointer = true;
9762     } else {
9763       return InvalidOperands(Loc, LHS, RHS);
9764     }
9765   }
9766   assert(PExp->getType()->isAnyPointerType());
9767 
9768   if (!IExp->getType()->isIntegerType())
9769     return InvalidOperands(Loc, LHS, RHS);
9770 
9771   // Adding to a null pointer results in undefined behavior.
9772   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9773           Context, Expr::NPC_ValueDependentIsNotNull)) {
9774     // In C++ adding zero to a null pointer is defined.
9775     Expr::EvalResult KnownVal;
9776     if (!getLangOpts().CPlusPlus ||
9777         (!IExp->isValueDependent() &&
9778          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9779           KnownVal.Val.getInt() != 0))) {
9780       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9781       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9782           Context, BO_Add, PExp, IExp);
9783       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9784     }
9785   }
9786 
9787   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9788     return QualType();
9789 
9790   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9791     return QualType();
9792 
9793   // Check array bounds for pointer arithemtic
9794   CheckArrayAccess(PExp, IExp);
9795 
9796   if (CompLHSTy) {
9797     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9798     if (LHSTy.isNull()) {
9799       LHSTy = LHS.get()->getType();
9800       if (LHSTy->isPromotableIntegerType())
9801         LHSTy = Context.getPromotedIntegerType(LHSTy);
9802     }
9803     *CompLHSTy = LHSTy;
9804   }
9805 
9806   return PExp->getType();
9807 }
9808 
9809 // C99 6.5.6
9810 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9811                                         SourceLocation Loc,
9812                                         QualType* CompLHSTy) {
9813   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9814 
9815   if (LHS.get()->getType()->isVectorType() ||
9816       RHS.get()->getType()->isVectorType()) {
9817     QualType compType = CheckVectorOperands(
9818         LHS, RHS, Loc, CompLHSTy,
9819         /*AllowBothBool*/getLangOpts().AltiVec,
9820         /*AllowBoolConversions*/getLangOpts().ZVector);
9821     if (CompLHSTy) *CompLHSTy = compType;
9822     return compType;
9823   }
9824 
9825   QualType compType = UsualArithmeticConversions(
9826       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9827   if (LHS.isInvalid() || RHS.isInvalid())
9828     return QualType();
9829 
9830   // Enforce type constraints: C99 6.5.6p3.
9831 
9832   // Handle the common case first (both operands are arithmetic).
9833   if (!compType.isNull() && compType->isArithmeticType()) {
9834     if (CompLHSTy) *CompLHSTy = compType;
9835     return compType;
9836   }
9837 
9838   // Either ptr - int   or   ptr - ptr.
9839   if (LHS.get()->getType()->isAnyPointerType()) {
9840     QualType lpointee = LHS.get()->getType()->getPointeeType();
9841 
9842     // Diagnose bad cases where we step over interface counts.
9843     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9844         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9845       return QualType();
9846 
9847     // The result type of a pointer-int computation is the pointer type.
9848     if (RHS.get()->getType()->isIntegerType()) {
9849       // Subtracting from a null pointer should produce a warning.
9850       // The last argument to the diagnose call says this doesn't match the
9851       // GNU int-to-pointer idiom.
9852       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9853                                            Expr::NPC_ValueDependentIsNotNull)) {
9854         // In C++ adding zero to a null pointer is defined.
9855         Expr::EvalResult KnownVal;
9856         if (!getLangOpts().CPlusPlus ||
9857             (!RHS.get()->isValueDependent() &&
9858              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9859               KnownVal.Val.getInt() != 0))) {
9860           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9861         }
9862       }
9863 
9864       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9865         return QualType();
9866 
9867       // Check array bounds for pointer arithemtic
9868       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9869                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9870 
9871       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9872       return LHS.get()->getType();
9873     }
9874 
9875     // Handle pointer-pointer subtractions.
9876     if (const PointerType *RHSPTy
9877           = RHS.get()->getType()->getAs<PointerType>()) {
9878       QualType rpointee = RHSPTy->getPointeeType();
9879 
9880       if (getLangOpts().CPlusPlus) {
9881         // Pointee types must be the same: C++ [expr.add]
9882         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9883           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9884         }
9885       } else {
9886         // Pointee types must be compatible C99 6.5.6p3
9887         if (!Context.typesAreCompatible(
9888                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9889                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9890           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9891           return QualType();
9892         }
9893       }
9894 
9895       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9896                                                LHS.get(), RHS.get()))
9897         return QualType();
9898 
9899       // FIXME: Add warnings for nullptr - ptr.
9900 
9901       // The pointee type may have zero size.  As an extension, a structure or
9902       // union may have zero size or an array may have zero length.  In this
9903       // case subtraction does not make sense.
9904       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9905         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9906         if (ElementSize.isZero()) {
9907           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9908             << rpointee.getUnqualifiedType()
9909             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9910         }
9911       }
9912 
9913       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9914       return Context.getPointerDiffType();
9915     }
9916   }
9917 
9918   return InvalidOperands(Loc, LHS, RHS);
9919 }
9920 
9921 static bool isScopedEnumerationType(QualType T) {
9922   if (const EnumType *ET = T->getAs<EnumType>())
9923     return ET->getDecl()->isScoped();
9924   return false;
9925 }
9926 
9927 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9928                                    SourceLocation Loc, BinaryOperatorKind Opc,
9929                                    QualType LHSType) {
9930   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9931   // so skip remaining warnings as we don't want to modify values within Sema.
9932   if (S.getLangOpts().OpenCL)
9933     return;
9934 
9935   // Check right/shifter operand
9936   Expr::EvalResult RHSResult;
9937   if (RHS.get()->isValueDependent() ||
9938       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9939     return;
9940   llvm::APSInt Right = RHSResult.Val.getInt();
9941 
9942   if (Right.isNegative()) {
9943     S.DiagRuntimeBehavior(Loc, RHS.get(),
9944                           S.PDiag(diag::warn_shift_negative)
9945                             << RHS.get()->getSourceRange());
9946     return;
9947   }
9948   llvm::APInt LeftBits(Right.getBitWidth(),
9949                        S.Context.getTypeSize(LHS.get()->getType()));
9950   if (Right.uge(LeftBits)) {
9951     S.DiagRuntimeBehavior(Loc, RHS.get(),
9952                           S.PDiag(diag::warn_shift_gt_typewidth)
9953                             << RHS.get()->getSourceRange());
9954     return;
9955   }
9956   if (Opc != BO_Shl)
9957     return;
9958 
9959   // When left shifting an ICE which is signed, we can check for overflow which
9960   // according to C++ standards prior to C++2a has undefined behavior
9961   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9962   // more than the maximum value representable in the result type, so never
9963   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9964   // expression is still probably a bug.)
9965   Expr::EvalResult LHSResult;
9966   if (LHS.get()->isValueDependent() ||
9967       LHSType->hasUnsignedIntegerRepresentation() ||
9968       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9969     return;
9970   llvm::APSInt Left = LHSResult.Val.getInt();
9971 
9972   // If LHS does not have a signed type and non-negative value
9973   // then, the behavior is undefined before C++2a. Warn about it.
9974   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9975       !S.getLangOpts().CPlusPlus2a) {
9976     S.DiagRuntimeBehavior(Loc, LHS.get(),
9977                           S.PDiag(diag::warn_shift_lhs_negative)
9978                             << LHS.get()->getSourceRange());
9979     return;
9980   }
9981 
9982   llvm::APInt ResultBits =
9983       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9984   if (LeftBits.uge(ResultBits))
9985     return;
9986   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9987   Result = Result.shl(Right);
9988 
9989   // Print the bit representation of the signed integer as an unsigned
9990   // hexadecimal number.
9991   SmallString<40> HexResult;
9992   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9993 
9994   // If we are only missing a sign bit, this is less likely to result in actual
9995   // bugs -- if the result is cast back to an unsigned type, it will have the
9996   // expected value. Thus we place this behind a different warning that can be
9997   // turned off separately if needed.
9998   if (LeftBits == ResultBits - 1) {
9999     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10000         << HexResult << LHSType
10001         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10002     return;
10003   }
10004 
10005   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10006     << HexResult.str() << Result.getMinSignedBits() << LHSType
10007     << Left.getBitWidth() << LHS.get()->getSourceRange()
10008     << RHS.get()->getSourceRange();
10009 }
10010 
10011 /// Return the resulting type when a vector is shifted
10012 ///        by a scalar or vector shift amount.
10013 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10014                                  SourceLocation Loc, bool IsCompAssign) {
10015   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10016   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10017       !LHS.get()->getType()->isVectorType()) {
10018     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10019       << RHS.get()->getType() << LHS.get()->getType()
10020       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10021     return QualType();
10022   }
10023 
10024   if (!IsCompAssign) {
10025     LHS = S.UsualUnaryConversions(LHS.get());
10026     if (LHS.isInvalid()) return QualType();
10027   }
10028 
10029   RHS = S.UsualUnaryConversions(RHS.get());
10030   if (RHS.isInvalid()) return QualType();
10031 
10032   QualType LHSType = LHS.get()->getType();
10033   // Note that LHS might be a scalar because the routine calls not only in
10034   // OpenCL case.
10035   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10036   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10037 
10038   // Note that RHS might not be a vector.
10039   QualType RHSType = RHS.get()->getType();
10040   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10041   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10042 
10043   // The operands need to be integers.
10044   if (!LHSEleType->isIntegerType()) {
10045     S.Diag(Loc, diag::err_typecheck_expect_int)
10046       << LHS.get()->getType() << LHS.get()->getSourceRange();
10047     return QualType();
10048   }
10049 
10050   if (!RHSEleType->isIntegerType()) {
10051     S.Diag(Loc, diag::err_typecheck_expect_int)
10052       << RHS.get()->getType() << RHS.get()->getSourceRange();
10053     return QualType();
10054   }
10055 
10056   if (!LHSVecTy) {
10057     assert(RHSVecTy);
10058     if (IsCompAssign)
10059       return RHSType;
10060     if (LHSEleType != RHSEleType) {
10061       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10062       LHSEleType = RHSEleType;
10063     }
10064     QualType VecTy =
10065         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10066     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10067     LHSType = VecTy;
10068   } else if (RHSVecTy) {
10069     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10070     // are applied component-wise. So if RHS is a vector, then ensure
10071     // that the number of elements is the same as LHS...
10072     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10073       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10074         << LHS.get()->getType() << RHS.get()->getType()
10075         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10076       return QualType();
10077     }
10078     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10079       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10080       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10081       if (LHSBT != RHSBT &&
10082           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10083         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10084             << LHS.get()->getType() << RHS.get()->getType()
10085             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10086       }
10087     }
10088   } else {
10089     // ...else expand RHS to match the number of elements in LHS.
10090     QualType VecTy =
10091       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10092     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10093   }
10094 
10095   return LHSType;
10096 }
10097 
10098 // C99 6.5.7
10099 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10100                                   SourceLocation Loc, BinaryOperatorKind Opc,
10101                                   bool IsCompAssign) {
10102   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10103 
10104   // Vector shifts promote their scalar inputs to vector type.
10105   if (LHS.get()->getType()->isVectorType() ||
10106       RHS.get()->getType()->isVectorType()) {
10107     if (LangOpts.ZVector) {
10108       // The shift operators for the z vector extensions work basically
10109       // like general shifts, except that neither the LHS nor the RHS is
10110       // allowed to be a "vector bool".
10111       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10112         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10113           return InvalidOperands(Loc, LHS, RHS);
10114       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10115         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10116           return InvalidOperands(Loc, LHS, RHS);
10117     }
10118     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10119   }
10120 
10121   // Shifts don't perform usual arithmetic conversions, they just do integer
10122   // promotions on each operand. C99 6.5.7p3
10123 
10124   // For the LHS, do usual unary conversions, but then reset them away
10125   // if this is a compound assignment.
10126   ExprResult OldLHS = LHS;
10127   LHS = UsualUnaryConversions(LHS.get());
10128   if (LHS.isInvalid())
10129     return QualType();
10130   QualType LHSType = LHS.get()->getType();
10131   if (IsCompAssign) LHS = OldLHS;
10132 
10133   // The RHS is simpler.
10134   RHS = UsualUnaryConversions(RHS.get());
10135   if (RHS.isInvalid())
10136     return QualType();
10137   QualType RHSType = RHS.get()->getType();
10138 
10139   // C99 6.5.7p2: Each of the operands shall have integer type.
10140   if (!LHSType->hasIntegerRepresentation() ||
10141       !RHSType->hasIntegerRepresentation())
10142     return InvalidOperands(Loc, LHS, RHS);
10143 
10144   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10145   // hasIntegerRepresentation() above instead of this.
10146   if (isScopedEnumerationType(LHSType) ||
10147       isScopedEnumerationType(RHSType)) {
10148     return InvalidOperands(Loc, LHS, RHS);
10149   }
10150   // Sanity-check shift operands
10151   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10152 
10153   // "The type of the result is that of the promoted left operand."
10154   return LHSType;
10155 }
10156 
10157 /// Diagnose bad pointer comparisons.
10158 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10159                                               ExprResult &LHS, ExprResult &RHS,
10160                                               bool IsError) {
10161   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10162                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10163     << LHS.get()->getType() << RHS.get()->getType()
10164     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10165 }
10166 
10167 /// Returns false if the pointers are converted to a composite type,
10168 /// true otherwise.
10169 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10170                                            ExprResult &LHS, ExprResult &RHS) {
10171   // C++ [expr.rel]p2:
10172   //   [...] Pointer conversions (4.10) and qualification
10173   //   conversions (4.4) are performed on pointer operands (or on
10174   //   a pointer operand and a null pointer constant) to bring
10175   //   them to their composite pointer type. [...]
10176   //
10177   // C++ [expr.eq]p1 uses the same notion for (in)equality
10178   // comparisons of pointers.
10179 
10180   QualType LHSType = LHS.get()->getType();
10181   QualType RHSType = RHS.get()->getType();
10182   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10183          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10184 
10185   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10186   if (T.isNull()) {
10187     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10188         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10189       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10190     else
10191       S.InvalidOperands(Loc, LHS, RHS);
10192     return true;
10193   }
10194 
10195   return false;
10196 }
10197 
10198 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10199                                                     ExprResult &LHS,
10200                                                     ExprResult &RHS,
10201                                                     bool IsError) {
10202   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10203                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10204     << LHS.get()->getType() << RHS.get()->getType()
10205     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10206 }
10207 
10208 static bool isObjCObjectLiteral(ExprResult &E) {
10209   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10210   case Stmt::ObjCArrayLiteralClass:
10211   case Stmt::ObjCDictionaryLiteralClass:
10212   case Stmt::ObjCStringLiteralClass:
10213   case Stmt::ObjCBoxedExprClass:
10214     return true;
10215   default:
10216     // Note that ObjCBoolLiteral is NOT an object literal!
10217     return false;
10218   }
10219 }
10220 
10221 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10222   const ObjCObjectPointerType *Type =
10223     LHS->getType()->getAs<ObjCObjectPointerType>();
10224 
10225   // If this is not actually an Objective-C object, bail out.
10226   if (!Type)
10227     return false;
10228 
10229   // Get the LHS object's interface type.
10230   QualType InterfaceType = Type->getPointeeType();
10231 
10232   // If the RHS isn't an Objective-C object, bail out.
10233   if (!RHS->getType()->isObjCObjectPointerType())
10234     return false;
10235 
10236   // Try to find the -isEqual: method.
10237   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10238   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10239                                                       InterfaceType,
10240                                                       /*IsInstance=*/true);
10241   if (!Method) {
10242     if (Type->isObjCIdType()) {
10243       // For 'id', just check the global pool.
10244       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10245                                                   /*receiverId=*/true);
10246     } else {
10247       // Check protocols.
10248       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10249                                              /*IsInstance=*/true);
10250     }
10251   }
10252 
10253   if (!Method)
10254     return false;
10255 
10256   QualType T = Method->parameters()[0]->getType();
10257   if (!T->isObjCObjectPointerType())
10258     return false;
10259 
10260   QualType R = Method->getReturnType();
10261   if (!R->isScalarType())
10262     return false;
10263 
10264   return true;
10265 }
10266 
10267 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10268   FromE = FromE->IgnoreParenImpCasts();
10269   switch (FromE->getStmtClass()) {
10270     default:
10271       break;
10272     case Stmt::ObjCStringLiteralClass:
10273       // "string literal"
10274       return LK_String;
10275     case Stmt::ObjCArrayLiteralClass:
10276       // "array literal"
10277       return LK_Array;
10278     case Stmt::ObjCDictionaryLiteralClass:
10279       // "dictionary literal"
10280       return LK_Dictionary;
10281     case Stmt::BlockExprClass:
10282       return LK_Block;
10283     case Stmt::ObjCBoxedExprClass: {
10284       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10285       switch (Inner->getStmtClass()) {
10286         case Stmt::IntegerLiteralClass:
10287         case Stmt::FloatingLiteralClass:
10288         case Stmt::CharacterLiteralClass:
10289         case Stmt::ObjCBoolLiteralExprClass:
10290         case Stmt::CXXBoolLiteralExprClass:
10291           // "numeric literal"
10292           return LK_Numeric;
10293         case Stmt::ImplicitCastExprClass: {
10294           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10295           // Boolean literals can be represented by implicit casts.
10296           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10297             return LK_Numeric;
10298           break;
10299         }
10300         default:
10301           break;
10302       }
10303       return LK_Boxed;
10304     }
10305   }
10306   return LK_None;
10307 }
10308 
10309 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10310                                           ExprResult &LHS, ExprResult &RHS,
10311                                           BinaryOperator::Opcode Opc){
10312   Expr *Literal;
10313   Expr *Other;
10314   if (isObjCObjectLiteral(LHS)) {
10315     Literal = LHS.get();
10316     Other = RHS.get();
10317   } else {
10318     Literal = RHS.get();
10319     Other = LHS.get();
10320   }
10321 
10322   // Don't warn on comparisons against nil.
10323   Other = Other->IgnoreParenCasts();
10324   if (Other->isNullPointerConstant(S.getASTContext(),
10325                                    Expr::NPC_ValueDependentIsNotNull))
10326     return;
10327 
10328   // This should be kept in sync with warn_objc_literal_comparison.
10329   // LK_String should always be after the other literals, since it has its own
10330   // warning flag.
10331   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10332   assert(LiteralKind != Sema::LK_Block);
10333   if (LiteralKind == Sema::LK_None) {
10334     llvm_unreachable("Unknown Objective-C object literal kind");
10335   }
10336 
10337   if (LiteralKind == Sema::LK_String)
10338     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10339       << Literal->getSourceRange();
10340   else
10341     S.Diag(Loc, diag::warn_objc_literal_comparison)
10342       << LiteralKind << Literal->getSourceRange();
10343 
10344   if (BinaryOperator::isEqualityOp(Opc) &&
10345       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10346     SourceLocation Start = LHS.get()->getBeginLoc();
10347     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10348     CharSourceRange OpRange =
10349       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10350 
10351     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10352       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10353       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10354       << FixItHint::CreateInsertion(End, "]");
10355   }
10356 }
10357 
10358 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10359 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10360                                            ExprResult &RHS, SourceLocation Loc,
10361                                            BinaryOperatorKind Opc) {
10362   // Check that left hand side is !something.
10363   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10364   if (!UO || UO->getOpcode() != UO_LNot) return;
10365 
10366   // Only check if the right hand side is non-bool arithmetic type.
10367   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10368 
10369   // Make sure that the something in !something is not bool.
10370   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10371   if (SubExpr->isKnownToHaveBooleanValue()) return;
10372 
10373   // Emit warning.
10374   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10375   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10376       << Loc << IsBitwiseOp;
10377 
10378   // First note suggest !(x < y)
10379   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10380   SourceLocation FirstClose = RHS.get()->getEndLoc();
10381   FirstClose = S.getLocForEndOfToken(FirstClose);
10382   if (FirstClose.isInvalid())
10383     FirstOpen = SourceLocation();
10384   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10385       << IsBitwiseOp
10386       << FixItHint::CreateInsertion(FirstOpen, "(")
10387       << FixItHint::CreateInsertion(FirstClose, ")");
10388 
10389   // Second note suggests (!x) < y
10390   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10391   SourceLocation SecondClose = LHS.get()->getEndLoc();
10392   SecondClose = S.getLocForEndOfToken(SecondClose);
10393   if (SecondClose.isInvalid())
10394     SecondOpen = SourceLocation();
10395   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10396       << FixItHint::CreateInsertion(SecondOpen, "(")
10397       << FixItHint::CreateInsertion(SecondClose, ")");
10398 }
10399 
10400 // Returns true if E refers to a non-weak array.
10401 static bool checkForArray(const Expr *E) {
10402   const ValueDecl *D = nullptr;
10403   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10404     D = DR->getDecl();
10405   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10406     if (Mem->isImplicitAccess())
10407       D = Mem->getMemberDecl();
10408   }
10409   if (!D)
10410     return false;
10411   return D->getType()->isArrayType() && !D->isWeak();
10412 }
10413 
10414 /// Diagnose some forms of syntactically-obvious tautological comparison.
10415 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10416                                            Expr *LHS, Expr *RHS,
10417                                            BinaryOperatorKind Opc) {
10418   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10419   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10420 
10421   QualType LHSType = LHS->getType();
10422   QualType RHSType = RHS->getType();
10423   if (LHSType->hasFloatingRepresentation() ||
10424       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10425       S.inTemplateInstantiation())
10426     return;
10427 
10428   // Comparisons between two array types are ill-formed for operator<=>, so
10429   // we shouldn't emit any additional warnings about it.
10430   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10431     return;
10432 
10433   // For non-floating point types, check for self-comparisons of the form
10434   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10435   // often indicate logic errors in the program.
10436   //
10437   // NOTE: Don't warn about comparison expressions resulting from macro
10438   // expansion. Also don't warn about comparisons which are only self
10439   // comparisons within a template instantiation. The warnings should catch
10440   // obvious cases in the definition of the template anyways. The idea is to
10441   // warn when the typed comparison operator will always evaluate to the same
10442   // result.
10443 
10444   // Used for indexing into %select in warn_comparison_always
10445   enum {
10446     AlwaysConstant,
10447     AlwaysTrue,
10448     AlwaysFalse,
10449     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10450   };
10451 
10452   // C++2a [depr.array.comp]:
10453   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10454   //   operands of array type are deprecated.
10455   if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10456       RHSStripped->getType()->isArrayType()) {
10457     S.Diag(Loc, diag::warn_depr_array_comparison)
10458         << LHS->getSourceRange() << RHS->getSourceRange()
10459         << LHSStripped->getType() << RHSStripped->getType();
10460     // Carry on to produce the tautological comparison warning, if this
10461     // expression is potentially-evaluated, we can resolve the array to a
10462     // non-weak declaration, and so on.
10463   }
10464 
10465   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10466     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10467       unsigned Result;
10468       switch (Opc) {
10469       case BO_EQ:
10470       case BO_LE:
10471       case BO_GE:
10472         Result = AlwaysTrue;
10473         break;
10474       case BO_NE:
10475       case BO_LT:
10476       case BO_GT:
10477         Result = AlwaysFalse;
10478         break;
10479       case BO_Cmp:
10480         Result = AlwaysEqual;
10481         break;
10482       default:
10483         Result = AlwaysConstant;
10484         break;
10485       }
10486       S.DiagRuntimeBehavior(Loc, nullptr,
10487                             S.PDiag(diag::warn_comparison_always)
10488                                 << 0 /*self-comparison*/
10489                                 << Result);
10490     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10491       // What is it always going to evaluate to?
10492       unsigned Result;
10493       switch (Opc) {
10494       case BO_EQ: // e.g. array1 == array2
10495         Result = AlwaysFalse;
10496         break;
10497       case BO_NE: // e.g. array1 != array2
10498         Result = AlwaysTrue;
10499         break;
10500       default: // e.g. array1 <= array2
10501         // The best we can say is 'a constant'
10502         Result = AlwaysConstant;
10503         break;
10504       }
10505       S.DiagRuntimeBehavior(Loc, nullptr,
10506                             S.PDiag(diag::warn_comparison_always)
10507                                 << 1 /*array comparison*/
10508                                 << Result);
10509     }
10510   }
10511 
10512   if (isa<CastExpr>(LHSStripped))
10513     LHSStripped = LHSStripped->IgnoreParenCasts();
10514   if (isa<CastExpr>(RHSStripped))
10515     RHSStripped = RHSStripped->IgnoreParenCasts();
10516 
10517   // Warn about comparisons against a string constant (unless the other
10518   // operand is null); the user probably wants string comparison function.
10519   Expr *LiteralString = nullptr;
10520   Expr *LiteralStringStripped = nullptr;
10521   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10522       !RHSStripped->isNullPointerConstant(S.Context,
10523                                           Expr::NPC_ValueDependentIsNull)) {
10524     LiteralString = LHS;
10525     LiteralStringStripped = LHSStripped;
10526   } else if ((isa<StringLiteral>(RHSStripped) ||
10527               isa<ObjCEncodeExpr>(RHSStripped)) &&
10528              !LHSStripped->isNullPointerConstant(S.Context,
10529                                           Expr::NPC_ValueDependentIsNull)) {
10530     LiteralString = RHS;
10531     LiteralStringStripped = RHSStripped;
10532   }
10533 
10534   if (LiteralString) {
10535     S.DiagRuntimeBehavior(Loc, nullptr,
10536                           S.PDiag(diag::warn_stringcompare)
10537                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10538                               << LiteralString->getSourceRange());
10539   }
10540 }
10541 
10542 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10543   switch (CK) {
10544   default: {
10545 #ifndef NDEBUG
10546     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10547                  << "\n";
10548 #endif
10549     llvm_unreachable("unhandled cast kind");
10550   }
10551   case CK_UserDefinedConversion:
10552     return ICK_Identity;
10553   case CK_LValueToRValue:
10554     return ICK_Lvalue_To_Rvalue;
10555   case CK_ArrayToPointerDecay:
10556     return ICK_Array_To_Pointer;
10557   case CK_FunctionToPointerDecay:
10558     return ICK_Function_To_Pointer;
10559   case CK_IntegralCast:
10560     return ICK_Integral_Conversion;
10561   case CK_FloatingCast:
10562     return ICK_Floating_Conversion;
10563   case CK_IntegralToFloating:
10564   case CK_FloatingToIntegral:
10565     return ICK_Floating_Integral;
10566   case CK_IntegralComplexCast:
10567   case CK_FloatingComplexCast:
10568   case CK_FloatingComplexToIntegralComplex:
10569   case CK_IntegralComplexToFloatingComplex:
10570     return ICK_Complex_Conversion;
10571   case CK_FloatingComplexToReal:
10572   case CK_FloatingRealToComplex:
10573   case CK_IntegralComplexToReal:
10574   case CK_IntegralRealToComplex:
10575     return ICK_Complex_Real;
10576   }
10577 }
10578 
10579 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10580                                              QualType FromType,
10581                                              SourceLocation Loc) {
10582   // Check for a narrowing implicit conversion.
10583   StandardConversionSequence SCS;
10584   SCS.setAsIdentityConversion();
10585   SCS.setToType(0, FromType);
10586   SCS.setToType(1, ToType);
10587   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10588     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10589 
10590   APValue PreNarrowingValue;
10591   QualType PreNarrowingType;
10592   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10593                                PreNarrowingType,
10594                                /*IgnoreFloatToIntegralConversion*/ true)) {
10595   case NK_Dependent_Narrowing:
10596     // Implicit conversion to a narrower type, but the expression is
10597     // value-dependent so we can't tell whether it's actually narrowing.
10598   case NK_Not_Narrowing:
10599     return false;
10600 
10601   case NK_Constant_Narrowing:
10602     // Implicit conversion to a narrower type, and the value is not a constant
10603     // expression.
10604     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10605         << /*Constant*/ 1
10606         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10607     return true;
10608 
10609   case NK_Variable_Narrowing:
10610     // Implicit conversion to a narrower type, and the value is not a constant
10611     // expression.
10612   case NK_Type_Narrowing:
10613     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10614         << /*Constant*/ 0 << FromType << ToType;
10615     // TODO: It's not a constant expression, but what if the user intended it
10616     // to be? Can we produce notes to help them figure out why it isn't?
10617     return true;
10618   }
10619   llvm_unreachable("unhandled case in switch");
10620 }
10621 
10622 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10623                                                          ExprResult &LHS,
10624                                                          ExprResult &RHS,
10625                                                          SourceLocation Loc) {
10626   QualType LHSType = LHS.get()->getType();
10627   QualType RHSType = RHS.get()->getType();
10628   // Dig out the original argument type and expression before implicit casts
10629   // were applied. These are the types/expressions we need to check the
10630   // [expr.spaceship] requirements against.
10631   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10632   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10633   QualType LHSStrippedType = LHSStripped.get()->getType();
10634   QualType RHSStrippedType = RHSStripped.get()->getType();
10635 
10636   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10637   // other is not, the program is ill-formed.
10638   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10639     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10640     return QualType();
10641   }
10642 
10643   // FIXME: Consider combining this with checkEnumArithmeticConversions.
10644   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10645                     RHSStrippedType->isEnumeralType();
10646   if (NumEnumArgs == 1) {
10647     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10648     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10649     if (OtherTy->hasFloatingRepresentation()) {
10650       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10651       return QualType();
10652     }
10653   }
10654   if (NumEnumArgs == 2) {
10655     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10656     // type E, the operator yields the result of converting the operands
10657     // to the underlying type of E and applying <=> to the converted operands.
10658     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10659       S.InvalidOperands(Loc, LHS, RHS);
10660       return QualType();
10661     }
10662     QualType IntType =
10663         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10664     assert(IntType->isArithmeticType());
10665 
10666     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10667     // promote the boolean type, and all other promotable integer types, to
10668     // avoid this.
10669     if (IntType->isPromotableIntegerType())
10670       IntType = S.Context.getPromotedIntegerType(IntType);
10671 
10672     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10673     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10674     LHSType = RHSType = IntType;
10675   }
10676 
10677   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10678   // usual arithmetic conversions are applied to the operands.
10679   QualType Type =
10680       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10681   if (LHS.isInvalid() || RHS.isInvalid())
10682     return QualType();
10683   if (Type.isNull())
10684     return S.InvalidOperands(Loc, LHS, RHS);
10685 
10686   Optional<ComparisonCategoryType> CCT =
10687       getComparisonCategoryForBuiltinCmp(Type);
10688   if (!CCT)
10689     return S.InvalidOperands(Loc, LHS, RHS);
10690 
10691   bool HasNarrowing = checkThreeWayNarrowingConversion(
10692       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10693   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10694                                                    RHS.get()->getBeginLoc());
10695   if (HasNarrowing)
10696     return QualType();
10697 
10698   assert(!Type.isNull() && "composite type for <=> has not been set");
10699 
10700   return S.CheckComparisonCategoryType(
10701       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
10702 }
10703 
10704 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10705                                                  ExprResult &RHS,
10706                                                  SourceLocation Loc,
10707                                                  BinaryOperatorKind Opc) {
10708   if (Opc == BO_Cmp)
10709     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10710 
10711   // C99 6.5.8p3 / C99 6.5.9p4
10712   QualType Type =
10713       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10714   if (LHS.isInvalid() || RHS.isInvalid())
10715     return QualType();
10716   if (Type.isNull())
10717     return S.InvalidOperands(Loc, LHS, RHS);
10718   assert(Type->isArithmeticType() || Type->isEnumeralType());
10719 
10720   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10721     return S.InvalidOperands(Loc, LHS, RHS);
10722 
10723   // Check for comparisons of floating point operands using != and ==.
10724   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10725     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10726 
10727   // The result of comparisons is 'bool' in C++, 'int' in C.
10728   return S.Context.getLogicalOperationType();
10729 }
10730 
10731 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10732   if (!NullE.get()->getType()->isAnyPointerType())
10733     return;
10734   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10735   if (!E.get()->getType()->isAnyPointerType() &&
10736       E.get()->isNullPointerConstant(Context,
10737                                      Expr::NPC_ValueDependentIsNotNull) ==
10738         Expr::NPCK_ZeroExpression) {
10739     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10740       if (CL->getValue() == 0)
10741         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10742             << NullValue
10743             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10744                                             NullValue ? "NULL" : "(void *)0");
10745     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10746         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10747         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10748         if (T == Context.CharTy)
10749           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10750               << NullValue
10751               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10752                                               NullValue ? "NULL" : "(void *)0");
10753       }
10754   }
10755 }
10756 
10757 // C99 6.5.8, C++ [expr.rel]
10758 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10759                                     SourceLocation Loc,
10760                                     BinaryOperatorKind Opc) {
10761   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10762   bool IsThreeWay = Opc == BO_Cmp;
10763   bool IsOrdered = IsRelational || IsThreeWay;
10764   auto IsAnyPointerType = [](ExprResult E) {
10765     QualType Ty = E.get()->getType();
10766     return Ty->isPointerType() || Ty->isMemberPointerType();
10767   };
10768 
10769   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10770   // type, array-to-pointer, ..., conversions are performed on both operands to
10771   // bring them to their composite type.
10772   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10773   // any type-related checks.
10774   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10775     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10776     if (LHS.isInvalid())
10777       return QualType();
10778     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10779     if (RHS.isInvalid())
10780       return QualType();
10781   } else {
10782     LHS = DefaultLvalueConversion(LHS.get());
10783     if (LHS.isInvalid())
10784       return QualType();
10785     RHS = DefaultLvalueConversion(RHS.get());
10786     if (RHS.isInvalid())
10787       return QualType();
10788   }
10789 
10790   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10791   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10792     CheckPtrComparisonWithNullChar(LHS, RHS);
10793     CheckPtrComparisonWithNullChar(RHS, LHS);
10794   }
10795 
10796   // Handle vector comparisons separately.
10797   if (LHS.get()->getType()->isVectorType() ||
10798       RHS.get()->getType()->isVectorType())
10799     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10800 
10801   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10802   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10803 
10804   QualType LHSType = LHS.get()->getType();
10805   QualType RHSType = RHS.get()->getType();
10806   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10807       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10808     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10809 
10810   const Expr::NullPointerConstantKind LHSNullKind =
10811       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10812   const Expr::NullPointerConstantKind RHSNullKind =
10813       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10814   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10815   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10816 
10817   auto computeResultTy = [&]() {
10818     if (Opc != BO_Cmp)
10819       return Context.getLogicalOperationType();
10820     assert(getLangOpts().CPlusPlus);
10821     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10822 
10823     QualType CompositeTy = LHS.get()->getType();
10824     assert(!CompositeTy->isReferenceType());
10825 
10826     Optional<ComparisonCategoryType> CCT =
10827         getComparisonCategoryForBuiltinCmp(CompositeTy);
10828     if (!CCT)
10829       return InvalidOperands(Loc, LHS, RHS);
10830 
10831     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
10832       // P0946R0: Comparisons between a null pointer constant and an object
10833       // pointer result in std::strong_equality, which is ill-formed under
10834       // P1959R0.
10835       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
10836           << (LHSIsNull ? LHS.get()->getSourceRange()
10837                         : RHS.get()->getSourceRange());
10838       return QualType();
10839     }
10840 
10841     return CheckComparisonCategoryType(
10842         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
10843   };
10844 
10845   if (!IsOrdered && LHSIsNull != RHSIsNull) {
10846     bool IsEquality = Opc == BO_EQ;
10847     if (RHSIsNull)
10848       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10849                                    RHS.get()->getSourceRange());
10850     else
10851       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10852                                    LHS.get()->getSourceRange());
10853   }
10854 
10855   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10856       (RHSType->isIntegerType() && !RHSIsNull)) {
10857     // Skip normal pointer conversion checks in this case; we have better
10858     // diagnostics for this below.
10859   } else if (getLangOpts().CPlusPlus) {
10860     // Equality comparison of a function pointer to a void pointer is invalid,
10861     // but we allow it as an extension.
10862     // FIXME: If we really want to allow this, should it be part of composite
10863     // pointer type computation so it works in conditionals too?
10864     if (!IsOrdered &&
10865         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10866          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10867       // This is a gcc extension compatibility comparison.
10868       // In a SFINAE context, we treat this as a hard error to maintain
10869       // conformance with the C++ standard.
10870       diagnoseFunctionPointerToVoidComparison(
10871           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10872 
10873       if (isSFINAEContext())
10874         return QualType();
10875 
10876       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10877       return computeResultTy();
10878     }
10879 
10880     // C++ [expr.eq]p2:
10881     //   If at least one operand is a pointer [...] bring them to their
10882     //   composite pointer type.
10883     // C++ [expr.spaceship]p6
10884     //  If at least one of the operands is of pointer type, [...] bring them
10885     //  to their composite pointer type.
10886     // C++ [expr.rel]p2:
10887     //   If both operands are pointers, [...] bring them to their composite
10888     //   pointer type.
10889     // For <=>, the only valid non-pointer types are arrays and functions, and
10890     // we already decayed those, so this is really the same as the relational
10891     // comparison rule.
10892     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10893             (IsOrdered ? 2 : 1) &&
10894         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10895                                          RHSType->isObjCObjectPointerType()))) {
10896       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10897         return QualType();
10898       return computeResultTy();
10899     }
10900   } else if (LHSType->isPointerType() &&
10901              RHSType->isPointerType()) { // C99 6.5.8p2
10902     // All of the following pointer-related warnings are GCC extensions, except
10903     // when handling null pointer constants.
10904     QualType LCanPointeeTy =
10905       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10906     QualType RCanPointeeTy =
10907       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10908 
10909     // C99 6.5.9p2 and C99 6.5.8p2
10910     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10911                                    RCanPointeeTy.getUnqualifiedType())) {
10912       // Valid unless a relational comparison of function pointers
10913       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10914         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10915           << LHSType << RHSType << LHS.get()->getSourceRange()
10916           << RHS.get()->getSourceRange();
10917       }
10918     } else if (!IsRelational &&
10919                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10920       // Valid unless comparison between non-null pointer and function pointer
10921       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10922           && !LHSIsNull && !RHSIsNull)
10923         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10924                                                 /*isError*/false);
10925     } else {
10926       // Invalid
10927       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10928     }
10929     if (LCanPointeeTy != RCanPointeeTy) {
10930       // Treat NULL constant as a special case in OpenCL.
10931       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10932         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10933         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10934           Diag(Loc,
10935                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10936               << LHSType << RHSType << 0 /* comparison */
10937               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10938         }
10939       }
10940       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10941       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10942       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10943                                                : CK_BitCast;
10944       if (LHSIsNull && !RHSIsNull)
10945         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10946       else
10947         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10948     }
10949     return computeResultTy();
10950   }
10951 
10952   if (getLangOpts().CPlusPlus) {
10953     // C++ [expr.eq]p4:
10954     //   Two operands of type std::nullptr_t or one operand of type
10955     //   std::nullptr_t and the other a null pointer constant compare equal.
10956     if (!IsOrdered && LHSIsNull && RHSIsNull) {
10957       if (LHSType->isNullPtrType()) {
10958         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10959         return computeResultTy();
10960       }
10961       if (RHSType->isNullPtrType()) {
10962         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10963         return computeResultTy();
10964       }
10965     }
10966 
10967     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10968     // These aren't covered by the composite pointer type rules.
10969     if (!IsOrdered && RHSType->isNullPtrType() &&
10970         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10971       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10972       return computeResultTy();
10973     }
10974     if (!IsOrdered && LHSType->isNullPtrType() &&
10975         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10976       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10977       return computeResultTy();
10978     }
10979 
10980     if (IsRelational &&
10981         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10982          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10983       // HACK: Relational comparison of nullptr_t against a pointer type is
10984       // invalid per DR583, but we allow it within std::less<> and friends,
10985       // since otherwise common uses of it break.
10986       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10987       // friends to have std::nullptr_t overload candidates.
10988       DeclContext *DC = CurContext;
10989       if (isa<FunctionDecl>(DC))
10990         DC = DC->getParent();
10991       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10992         if (CTSD->isInStdNamespace() &&
10993             llvm::StringSwitch<bool>(CTSD->getName())
10994                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10995                 .Default(false)) {
10996           if (RHSType->isNullPtrType())
10997             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10998           else
10999             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11000           return computeResultTy();
11001         }
11002       }
11003     }
11004 
11005     // C++ [expr.eq]p2:
11006     //   If at least one operand is a pointer to member, [...] bring them to
11007     //   their composite pointer type.
11008     if (!IsOrdered &&
11009         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11010       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11011         return QualType();
11012       else
11013         return computeResultTy();
11014     }
11015   }
11016 
11017   // Handle block pointer types.
11018   if (!IsOrdered && LHSType->isBlockPointerType() &&
11019       RHSType->isBlockPointerType()) {
11020     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11021     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11022 
11023     if (!LHSIsNull && !RHSIsNull &&
11024         !Context.typesAreCompatible(lpointee, rpointee)) {
11025       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11026         << LHSType << RHSType << LHS.get()->getSourceRange()
11027         << RHS.get()->getSourceRange();
11028     }
11029     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11030     return computeResultTy();
11031   }
11032 
11033   // Allow block pointers to be compared with null pointer constants.
11034   if (!IsOrdered
11035       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11036           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11037     if (!LHSIsNull && !RHSIsNull) {
11038       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11039              ->getPointeeType()->isVoidType())
11040             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11041                 ->getPointeeType()->isVoidType())))
11042         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11043           << LHSType << RHSType << LHS.get()->getSourceRange()
11044           << RHS.get()->getSourceRange();
11045     }
11046     if (LHSIsNull && !RHSIsNull)
11047       LHS = ImpCastExprToType(LHS.get(), RHSType,
11048                               RHSType->isPointerType() ? CK_BitCast
11049                                 : CK_AnyPointerToBlockPointerCast);
11050     else
11051       RHS = ImpCastExprToType(RHS.get(), LHSType,
11052                               LHSType->isPointerType() ? CK_BitCast
11053                                 : CK_AnyPointerToBlockPointerCast);
11054     return computeResultTy();
11055   }
11056 
11057   if (LHSType->isObjCObjectPointerType() ||
11058       RHSType->isObjCObjectPointerType()) {
11059     const PointerType *LPT = LHSType->getAs<PointerType>();
11060     const PointerType *RPT = RHSType->getAs<PointerType>();
11061     if (LPT || RPT) {
11062       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11063       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11064 
11065       if (!LPtrToVoid && !RPtrToVoid &&
11066           !Context.typesAreCompatible(LHSType, RHSType)) {
11067         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11068                                           /*isError*/false);
11069       }
11070       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11071       // the RHS, but we have test coverage for this behavior.
11072       // FIXME: Consider using convertPointersToCompositeType in C++.
11073       if (LHSIsNull && !RHSIsNull) {
11074         Expr *E = LHS.get();
11075         if (getLangOpts().ObjCAutoRefCount)
11076           CheckObjCConversion(SourceRange(), RHSType, E,
11077                               CCK_ImplicitConversion);
11078         LHS = ImpCastExprToType(E, RHSType,
11079                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11080       }
11081       else {
11082         Expr *E = RHS.get();
11083         if (getLangOpts().ObjCAutoRefCount)
11084           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11085                               /*Diagnose=*/true,
11086                               /*DiagnoseCFAudited=*/false, Opc);
11087         RHS = ImpCastExprToType(E, LHSType,
11088                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11089       }
11090       return computeResultTy();
11091     }
11092     if (LHSType->isObjCObjectPointerType() &&
11093         RHSType->isObjCObjectPointerType()) {
11094       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11095         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11096                                           /*isError*/false);
11097       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11098         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11099 
11100       if (LHSIsNull && !RHSIsNull)
11101         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11102       else
11103         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11104       return computeResultTy();
11105     }
11106 
11107     if (!IsOrdered && LHSType->isBlockPointerType() &&
11108         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11109       LHS = ImpCastExprToType(LHS.get(), RHSType,
11110                               CK_BlockPointerToObjCPointerCast);
11111       return computeResultTy();
11112     } else if (!IsOrdered &&
11113                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11114                RHSType->isBlockPointerType()) {
11115       RHS = ImpCastExprToType(RHS.get(), LHSType,
11116                               CK_BlockPointerToObjCPointerCast);
11117       return computeResultTy();
11118     }
11119   }
11120   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11121       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11122     unsigned DiagID = 0;
11123     bool isError = false;
11124     if (LangOpts.DebuggerSupport) {
11125       // Under a debugger, allow the comparison of pointers to integers,
11126       // since users tend to want to compare addresses.
11127     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11128                (RHSIsNull && RHSType->isIntegerType())) {
11129       if (IsOrdered) {
11130         isError = getLangOpts().CPlusPlus;
11131         DiagID =
11132           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11133                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11134       }
11135     } else if (getLangOpts().CPlusPlus) {
11136       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11137       isError = true;
11138     } else if (IsOrdered)
11139       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11140     else
11141       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11142 
11143     if (DiagID) {
11144       Diag(Loc, DiagID)
11145         << LHSType << RHSType << LHS.get()->getSourceRange()
11146         << RHS.get()->getSourceRange();
11147       if (isError)
11148         return QualType();
11149     }
11150 
11151     if (LHSType->isIntegerType())
11152       LHS = ImpCastExprToType(LHS.get(), RHSType,
11153                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11154     else
11155       RHS = ImpCastExprToType(RHS.get(), LHSType,
11156                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11157     return computeResultTy();
11158   }
11159 
11160   // Handle block pointers.
11161   if (!IsOrdered && RHSIsNull
11162       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11163     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11164     return computeResultTy();
11165   }
11166   if (!IsOrdered && LHSIsNull
11167       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11168     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11169     return computeResultTy();
11170   }
11171 
11172   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11173     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11174       return computeResultTy();
11175     }
11176 
11177     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11178       return computeResultTy();
11179     }
11180 
11181     if (LHSIsNull && RHSType->isQueueT()) {
11182       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11183       return computeResultTy();
11184     }
11185 
11186     if (LHSType->isQueueT() && RHSIsNull) {
11187       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11188       return computeResultTy();
11189     }
11190   }
11191 
11192   return InvalidOperands(Loc, LHS, RHS);
11193 }
11194 
11195 // Return a signed ext_vector_type that is of identical size and number of
11196 // elements. For floating point vectors, return an integer type of identical
11197 // size and number of elements. In the non ext_vector_type case, search from
11198 // the largest type to the smallest type to avoid cases where long long == long,
11199 // where long gets picked over long long.
11200 QualType Sema::GetSignedVectorType(QualType V) {
11201   const VectorType *VTy = V->castAs<VectorType>();
11202   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11203 
11204   if (isa<ExtVectorType>(VTy)) {
11205     if (TypeSize == Context.getTypeSize(Context.CharTy))
11206       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11207     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11208       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11209     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11210       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11211     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11212       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11213     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11214            "Unhandled vector element size in vector compare");
11215     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11216   }
11217 
11218   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11219     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11220                                  VectorType::GenericVector);
11221   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11222     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11223                                  VectorType::GenericVector);
11224   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11225     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11226                                  VectorType::GenericVector);
11227   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11228     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11229                                  VectorType::GenericVector);
11230   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11231          "Unhandled vector element size in vector compare");
11232   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11233                                VectorType::GenericVector);
11234 }
11235 
11236 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11237 /// operates on extended vector types.  Instead of producing an IntTy result,
11238 /// like a scalar comparison, a vector comparison produces a vector of integer
11239 /// types.
11240 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11241                                           SourceLocation Loc,
11242                                           BinaryOperatorKind Opc) {
11243   if (Opc == BO_Cmp) {
11244     Diag(Loc, diag::err_three_way_vector_comparison);
11245     return QualType();
11246   }
11247 
11248   // Check to make sure we're operating on vectors of the same type and width,
11249   // Allowing one side to be a scalar of element type.
11250   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11251                               /*AllowBothBool*/true,
11252                               /*AllowBoolConversions*/getLangOpts().ZVector);
11253   if (vType.isNull())
11254     return vType;
11255 
11256   QualType LHSType = LHS.get()->getType();
11257 
11258   // If AltiVec, the comparison results in a numeric type, i.e.
11259   // bool for C++, int for C
11260   if (getLangOpts().AltiVec &&
11261       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11262     return Context.getLogicalOperationType();
11263 
11264   // For non-floating point types, check for self-comparisons of the form
11265   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11266   // often indicate logic errors in the program.
11267   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11268 
11269   // Check for comparisons of floating point operands using != and ==.
11270   if (BinaryOperator::isEqualityOp(Opc) &&
11271       LHSType->hasFloatingRepresentation()) {
11272     assert(RHS.get()->getType()->hasFloatingRepresentation());
11273     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11274   }
11275 
11276   // Return a signed type for the vector.
11277   return GetSignedVectorType(vType);
11278 }
11279 
11280 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11281                                     const ExprResult &XorRHS,
11282                                     const SourceLocation Loc) {
11283   // Do not diagnose macros.
11284   if (Loc.isMacroID())
11285     return;
11286 
11287   bool Negative = false;
11288   bool ExplicitPlus = false;
11289   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11290   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11291 
11292   if (!LHSInt)
11293     return;
11294   if (!RHSInt) {
11295     // Check negative literals.
11296     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11297       UnaryOperatorKind Opc = UO->getOpcode();
11298       if (Opc != UO_Minus && Opc != UO_Plus)
11299         return;
11300       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11301       if (!RHSInt)
11302         return;
11303       Negative = (Opc == UO_Minus);
11304       ExplicitPlus = !Negative;
11305     } else {
11306       return;
11307     }
11308   }
11309 
11310   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11311   llvm::APInt RightSideValue = RHSInt->getValue();
11312   if (LeftSideValue != 2 && LeftSideValue != 10)
11313     return;
11314 
11315   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11316     return;
11317 
11318   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11319       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11320   llvm::StringRef ExprStr =
11321       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11322 
11323   CharSourceRange XorRange =
11324       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11325   llvm::StringRef XorStr =
11326       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11327   // Do not diagnose if xor keyword/macro is used.
11328   if (XorStr == "xor")
11329     return;
11330 
11331   std::string LHSStr = std::string(Lexer::getSourceText(
11332       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11333       S.getSourceManager(), S.getLangOpts()));
11334   std::string RHSStr = std::string(Lexer::getSourceText(
11335       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11336       S.getSourceManager(), S.getLangOpts()));
11337 
11338   if (Negative) {
11339     RightSideValue = -RightSideValue;
11340     RHSStr = "-" + RHSStr;
11341   } else if (ExplicitPlus) {
11342     RHSStr = "+" + RHSStr;
11343   }
11344 
11345   StringRef LHSStrRef = LHSStr;
11346   StringRef RHSStrRef = RHSStr;
11347   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11348   // literals.
11349   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11350       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11351       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11352       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11353       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11354       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11355       LHSStrRef.find('\'') != StringRef::npos ||
11356       RHSStrRef.find('\'') != StringRef::npos)
11357     return;
11358 
11359   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11360   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11361   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11362   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11363     std::string SuggestedExpr = "1 << " + RHSStr;
11364     bool Overflow = false;
11365     llvm::APInt One = (LeftSideValue - 1);
11366     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11367     if (Overflow) {
11368       if (RightSideIntValue < 64)
11369         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11370             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11371             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11372       else if (RightSideIntValue == 64)
11373         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11374       else
11375         return;
11376     } else {
11377       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11378           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11379           << PowValue.toString(10, true)
11380           << FixItHint::CreateReplacement(
11381                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11382     }
11383 
11384     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11385   } else if (LeftSideValue == 10) {
11386     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11387     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11388         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11389         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11390     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11391   }
11392 }
11393 
11394 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11395                                           SourceLocation Loc) {
11396   // Ensure that either both operands are of the same vector type, or
11397   // one operand is of a vector type and the other is of its element type.
11398   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11399                                        /*AllowBothBool*/true,
11400                                        /*AllowBoolConversions*/false);
11401   if (vType.isNull())
11402     return InvalidOperands(Loc, LHS, RHS);
11403   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11404       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11405     return InvalidOperands(Loc, LHS, RHS);
11406   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11407   //        usage of the logical operators && and || with vectors in C. This
11408   //        check could be notionally dropped.
11409   if (!getLangOpts().CPlusPlus &&
11410       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11411     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11412 
11413   return GetSignedVectorType(LHS.get()->getType());
11414 }
11415 
11416 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11417                                            SourceLocation Loc,
11418                                            BinaryOperatorKind Opc) {
11419   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11420 
11421   bool IsCompAssign =
11422       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11423 
11424   if (LHS.get()->getType()->isVectorType() ||
11425       RHS.get()->getType()->isVectorType()) {
11426     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11427         RHS.get()->getType()->hasIntegerRepresentation())
11428       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11429                         /*AllowBothBool*/true,
11430                         /*AllowBoolConversions*/getLangOpts().ZVector);
11431     return InvalidOperands(Loc, LHS, RHS);
11432   }
11433 
11434   if (Opc == BO_And)
11435     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11436 
11437   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11438       RHS.get()->getType()->hasFloatingRepresentation())
11439     return InvalidOperands(Loc, LHS, RHS);
11440 
11441   ExprResult LHSResult = LHS, RHSResult = RHS;
11442   QualType compType = UsualArithmeticConversions(
11443       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11444   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11445     return QualType();
11446   LHS = LHSResult.get();
11447   RHS = RHSResult.get();
11448 
11449   if (Opc == BO_Xor)
11450     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11451 
11452   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11453     return compType;
11454   return InvalidOperands(Loc, LHS, RHS);
11455 }
11456 
11457 // C99 6.5.[13,14]
11458 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11459                                            SourceLocation Loc,
11460                                            BinaryOperatorKind Opc) {
11461   // Check vector operands differently.
11462   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11463     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11464 
11465   bool EnumConstantInBoolContext = false;
11466   for (const ExprResult &HS : {LHS, RHS}) {
11467     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11468       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11469       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11470         EnumConstantInBoolContext = true;
11471     }
11472   }
11473 
11474   if (EnumConstantInBoolContext)
11475     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11476 
11477   // Diagnose cases where the user write a logical and/or but probably meant a
11478   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11479   // is a constant.
11480   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11481       !LHS.get()->getType()->isBooleanType() &&
11482       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11483       // Don't warn in macros or template instantiations.
11484       !Loc.isMacroID() && !inTemplateInstantiation()) {
11485     // If the RHS can be constant folded, and if it constant folds to something
11486     // that isn't 0 or 1 (which indicate a potential logical operation that
11487     // happened to fold to true/false) then warn.
11488     // Parens on the RHS are ignored.
11489     Expr::EvalResult EVResult;
11490     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11491       llvm::APSInt Result = EVResult.Val.getInt();
11492       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11493            !RHS.get()->getExprLoc().isMacroID()) ||
11494           (Result != 0 && Result != 1)) {
11495         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11496           << RHS.get()->getSourceRange()
11497           << (Opc == BO_LAnd ? "&&" : "||");
11498         // Suggest replacing the logical operator with the bitwise version
11499         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11500             << (Opc == BO_LAnd ? "&" : "|")
11501             << FixItHint::CreateReplacement(SourceRange(
11502                                                  Loc, getLocForEndOfToken(Loc)),
11503                                             Opc == BO_LAnd ? "&" : "|");
11504         if (Opc == BO_LAnd)
11505           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11506           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11507               << FixItHint::CreateRemoval(
11508                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11509                                  RHS.get()->getEndLoc()));
11510       }
11511     }
11512   }
11513 
11514   if (!Context.getLangOpts().CPlusPlus) {
11515     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11516     // not operate on the built-in scalar and vector float types.
11517     if (Context.getLangOpts().OpenCL &&
11518         Context.getLangOpts().OpenCLVersion < 120) {
11519       if (LHS.get()->getType()->isFloatingType() ||
11520           RHS.get()->getType()->isFloatingType())
11521         return InvalidOperands(Loc, LHS, RHS);
11522     }
11523 
11524     LHS = UsualUnaryConversions(LHS.get());
11525     if (LHS.isInvalid())
11526       return QualType();
11527 
11528     RHS = UsualUnaryConversions(RHS.get());
11529     if (RHS.isInvalid())
11530       return QualType();
11531 
11532     if (!LHS.get()->getType()->isScalarType() ||
11533         !RHS.get()->getType()->isScalarType())
11534       return InvalidOperands(Loc, LHS, RHS);
11535 
11536     return Context.IntTy;
11537   }
11538 
11539   // The following is safe because we only use this method for
11540   // non-overloadable operands.
11541 
11542   // C++ [expr.log.and]p1
11543   // C++ [expr.log.or]p1
11544   // The operands are both contextually converted to type bool.
11545   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11546   if (LHSRes.isInvalid())
11547     return InvalidOperands(Loc, LHS, RHS);
11548   LHS = LHSRes;
11549 
11550   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11551   if (RHSRes.isInvalid())
11552     return InvalidOperands(Loc, LHS, RHS);
11553   RHS = RHSRes;
11554 
11555   // C++ [expr.log.and]p2
11556   // C++ [expr.log.or]p2
11557   // The result is a bool.
11558   return Context.BoolTy;
11559 }
11560 
11561 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11562   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11563   if (!ME) return false;
11564   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11565   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11566       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11567   if (!Base) return false;
11568   return Base->getMethodDecl() != nullptr;
11569 }
11570 
11571 /// Is the given expression (which must be 'const') a reference to a
11572 /// variable which was originally non-const, but which has become
11573 /// 'const' due to being captured within a block?
11574 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11575 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11576   assert(E->isLValue() && E->getType().isConstQualified());
11577   E = E->IgnoreParens();
11578 
11579   // Must be a reference to a declaration from an enclosing scope.
11580   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11581   if (!DRE) return NCCK_None;
11582   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11583 
11584   // The declaration must be a variable which is not declared 'const'.
11585   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11586   if (!var) return NCCK_None;
11587   if (var->getType().isConstQualified()) return NCCK_None;
11588   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11589 
11590   // Decide whether the first capture was for a block or a lambda.
11591   DeclContext *DC = S.CurContext, *Prev = nullptr;
11592   // Decide whether the first capture was for a block or a lambda.
11593   while (DC) {
11594     // For init-capture, it is possible that the variable belongs to the
11595     // template pattern of the current context.
11596     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11597       if (var->isInitCapture() &&
11598           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11599         break;
11600     if (DC == var->getDeclContext())
11601       break;
11602     Prev = DC;
11603     DC = DC->getParent();
11604   }
11605   // Unless we have an init-capture, we've gone one step too far.
11606   if (!var->isInitCapture())
11607     DC = Prev;
11608   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11609 }
11610 
11611 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11612   Ty = Ty.getNonReferenceType();
11613   if (IsDereference && Ty->isPointerType())
11614     Ty = Ty->getPointeeType();
11615   return !Ty.isConstQualified();
11616 }
11617 
11618 // Update err_typecheck_assign_const and note_typecheck_assign_const
11619 // when this enum is changed.
11620 enum {
11621   ConstFunction,
11622   ConstVariable,
11623   ConstMember,
11624   ConstMethod,
11625   NestedConstMember,
11626   ConstUnknown,  // Keep as last element
11627 };
11628 
11629 /// Emit the "read-only variable not assignable" error and print notes to give
11630 /// more information about why the variable is not assignable, such as pointing
11631 /// to the declaration of a const variable, showing that a method is const, or
11632 /// that the function is returning a const reference.
11633 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11634                                     SourceLocation Loc) {
11635   SourceRange ExprRange = E->getSourceRange();
11636 
11637   // Only emit one error on the first const found.  All other consts will emit
11638   // a note to the error.
11639   bool DiagnosticEmitted = false;
11640 
11641   // Track if the current expression is the result of a dereference, and if the
11642   // next checked expression is the result of a dereference.
11643   bool IsDereference = false;
11644   bool NextIsDereference = false;
11645 
11646   // Loop to process MemberExpr chains.
11647   while (true) {
11648     IsDereference = NextIsDereference;
11649 
11650     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11651     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11652       NextIsDereference = ME->isArrow();
11653       const ValueDecl *VD = ME->getMemberDecl();
11654       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11655         // Mutable fields can be modified even if the class is const.
11656         if (Field->isMutable()) {
11657           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11658           break;
11659         }
11660 
11661         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11662           if (!DiagnosticEmitted) {
11663             S.Diag(Loc, diag::err_typecheck_assign_const)
11664                 << ExprRange << ConstMember << false /*static*/ << Field
11665                 << Field->getType();
11666             DiagnosticEmitted = true;
11667           }
11668           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11669               << ConstMember << false /*static*/ << Field << Field->getType()
11670               << Field->getSourceRange();
11671         }
11672         E = ME->getBase();
11673         continue;
11674       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11675         if (VDecl->getType().isConstQualified()) {
11676           if (!DiagnosticEmitted) {
11677             S.Diag(Loc, diag::err_typecheck_assign_const)
11678                 << ExprRange << ConstMember << true /*static*/ << VDecl
11679                 << VDecl->getType();
11680             DiagnosticEmitted = true;
11681           }
11682           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11683               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11684               << VDecl->getSourceRange();
11685         }
11686         // Static fields do not inherit constness from parents.
11687         break;
11688       }
11689       break; // End MemberExpr
11690     } else if (const ArraySubscriptExpr *ASE =
11691                    dyn_cast<ArraySubscriptExpr>(E)) {
11692       E = ASE->getBase()->IgnoreParenImpCasts();
11693       continue;
11694     } else if (const ExtVectorElementExpr *EVE =
11695                    dyn_cast<ExtVectorElementExpr>(E)) {
11696       E = EVE->getBase()->IgnoreParenImpCasts();
11697       continue;
11698     }
11699     break;
11700   }
11701 
11702   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11703     // Function calls
11704     const FunctionDecl *FD = CE->getDirectCallee();
11705     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11706       if (!DiagnosticEmitted) {
11707         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11708                                                       << ConstFunction << FD;
11709         DiagnosticEmitted = true;
11710       }
11711       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11712              diag::note_typecheck_assign_const)
11713           << ConstFunction << FD << FD->getReturnType()
11714           << FD->getReturnTypeSourceRange();
11715     }
11716   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11717     // Point to variable declaration.
11718     if (const ValueDecl *VD = DRE->getDecl()) {
11719       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11720         if (!DiagnosticEmitted) {
11721           S.Diag(Loc, diag::err_typecheck_assign_const)
11722               << ExprRange << ConstVariable << VD << VD->getType();
11723           DiagnosticEmitted = true;
11724         }
11725         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11726             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11727       }
11728     }
11729   } else if (isa<CXXThisExpr>(E)) {
11730     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11731       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11732         if (MD->isConst()) {
11733           if (!DiagnosticEmitted) {
11734             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11735                                                           << ConstMethod << MD;
11736             DiagnosticEmitted = true;
11737           }
11738           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11739               << ConstMethod << MD << MD->getSourceRange();
11740         }
11741       }
11742     }
11743   }
11744 
11745   if (DiagnosticEmitted)
11746     return;
11747 
11748   // Can't determine a more specific message, so display the generic error.
11749   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11750 }
11751 
11752 enum OriginalExprKind {
11753   OEK_Variable,
11754   OEK_Member,
11755   OEK_LValue
11756 };
11757 
11758 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11759                                          const RecordType *Ty,
11760                                          SourceLocation Loc, SourceRange Range,
11761                                          OriginalExprKind OEK,
11762                                          bool &DiagnosticEmitted) {
11763   std::vector<const RecordType *> RecordTypeList;
11764   RecordTypeList.push_back(Ty);
11765   unsigned NextToCheckIndex = 0;
11766   // We walk the record hierarchy breadth-first to ensure that we print
11767   // diagnostics in field nesting order.
11768   while (RecordTypeList.size() > NextToCheckIndex) {
11769     bool IsNested = NextToCheckIndex > 0;
11770     for (const FieldDecl *Field :
11771          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11772       // First, check every field for constness.
11773       QualType FieldTy = Field->getType();
11774       if (FieldTy.isConstQualified()) {
11775         if (!DiagnosticEmitted) {
11776           S.Diag(Loc, diag::err_typecheck_assign_const)
11777               << Range << NestedConstMember << OEK << VD
11778               << IsNested << Field;
11779           DiagnosticEmitted = true;
11780         }
11781         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11782             << NestedConstMember << IsNested << Field
11783             << FieldTy << Field->getSourceRange();
11784       }
11785 
11786       // Then we append it to the list to check next in order.
11787       FieldTy = FieldTy.getCanonicalType();
11788       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11789         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11790           RecordTypeList.push_back(FieldRecTy);
11791       }
11792     }
11793     ++NextToCheckIndex;
11794   }
11795 }
11796 
11797 /// Emit an error for the case where a record we are trying to assign to has a
11798 /// const-qualified field somewhere in its hierarchy.
11799 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11800                                          SourceLocation Loc) {
11801   QualType Ty = E->getType();
11802   assert(Ty->isRecordType() && "lvalue was not record?");
11803   SourceRange Range = E->getSourceRange();
11804   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11805   bool DiagEmitted = false;
11806 
11807   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11808     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11809             Range, OEK_Member, DiagEmitted);
11810   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11811     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11812             Range, OEK_Variable, DiagEmitted);
11813   else
11814     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11815             Range, OEK_LValue, DiagEmitted);
11816   if (!DiagEmitted)
11817     DiagnoseConstAssignment(S, E, Loc);
11818 }
11819 
11820 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11821 /// emit an error and return true.  If so, return false.
11822 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11823   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11824 
11825   S.CheckShadowingDeclModification(E, Loc);
11826 
11827   SourceLocation OrigLoc = Loc;
11828   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11829                                                               &Loc);
11830   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11831     IsLV = Expr::MLV_InvalidMessageExpression;
11832   if (IsLV == Expr::MLV_Valid)
11833     return false;
11834 
11835   unsigned DiagID = 0;
11836   bool NeedType = false;
11837   switch (IsLV) { // C99 6.5.16p2
11838   case Expr::MLV_ConstQualified:
11839     // Use a specialized diagnostic when we're assigning to an object
11840     // from an enclosing function or block.
11841     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11842       if (NCCK == NCCK_Block)
11843         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11844       else
11845         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11846       break;
11847     }
11848 
11849     // In ARC, use some specialized diagnostics for occasions where we
11850     // infer 'const'.  These are always pseudo-strong variables.
11851     if (S.getLangOpts().ObjCAutoRefCount) {
11852       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11853       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11854         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11855 
11856         // Use the normal diagnostic if it's pseudo-__strong but the
11857         // user actually wrote 'const'.
11858         if (var->isARCPseudoStrong() &&
11859             (!var->getTypeSourceInfo() ||
11860              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11861           // There are three pseudo-strong cases:
11862           //  - self
11863           ObjCMethodDecl *method = S.getCurMethodDecl();
11864           if (method && var == method->getSelfDecl()) {
11865             DiagID = method->isClassMethod()
11866               ? diag::err_typecheck_arc_assign_self_class_method
11867               : diag::err_typecheck_arc_assign_self;
11868 
11869           //  - Objective-C externally_retained attribute.
11870           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11871                      isa<ParmVarDecl>(var)) {
11872             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11873 
11874           //  - fast enumeration variables
11875           } else {
11876             DiagID = diag::err_typecheck_arr_assign_enumeration;
11877           }
11878 
11879           SourceRange Assign;
11880           if (Loc != OrigLoc)
11881             Assign = SourceRange(OrigLoc, OrigLoc);
11882           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11883           // We need to preserve the AST regardless, so migration tool
11884           // can do its job.
11885           return false;
11886         }
11887       }
11888     }
11889 
11890     // If none of the special cases above are triggered, then this is a
11891     // simple const assignment.
11892     if (DiagID == 0) {
11893       DiagnoseConstAssignment(S, E, Loc);
11894       return true;
11895     }
11896 
11897     break;
11898   case Expr::MLV_ConstAddrSpace:
11899     DiagnoseConstAssignment(S, E, Loc);
11900     return true;
11901   case Expr::MLV_ConstQualifiedField:
11902     DiagnoseRecursiveConstFields(S, E, Loc);
11903     return true;
11904   case Expr::MLV_ArrayType:
11905   case Expr::MLV_ArrayTemporary:
11906     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11907     NeedType = true;
11908     break;
11909   case Expr::MLV_NotObjectType:
11910     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11911     NeedType = true;
11912     break;
11913   case Expr::MLV_LValueCast:
11914     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11915     break;
11916   case Expr::MLV_Valid:
11917     llvm_unreachable("did not take early return for MLV_Valid");
11918   case Expr::MLV_InvalidExpression:
11919   case Expr::MLV_MemberFunction:
11920   case Expr::MLV_ClassTemporary:
11921     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11922     break;
11923   case Expr::MLV_IncompleteType:
11924   case Expr::MLV_IncompleteVoidType:
11925     return S.RequireCompleteType(Loc, E->getType(),
11926              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11927   case Expr::MLV_DuplicateVectorComponents:
11928     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11929     break;
11930   case Expr::MLV_NoSetterProperty:
11931     llvm_unreachable("readonly properties should be processed differently");
11932   case Expr::MLV_InvalidMessageExpression:
11933     DiagID = diag::err_readonly_message_assignment;
11934     break;
11935   case Expr::MLV_SubObjCPropertySetting:
11936     DiagID = diag::err_no_subobject_property_setting;
11937     break;
11938   }
11939 
11940   SourceRange Assign;
11941   if (Loc != OrigLoc)
11942     Assign = SourceRange(OrigLoc, OrigLoc);
11943   if (NeedType)
11944     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11945   else
11946     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11947   return true;
11948 }
11949 
11950 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11951                                          SourceLocation Loc,
11952                                          Sema &Sema) {
11953   if (Sema.inTemplateInstantiation())
11954     return;
11955   if (Sema.isUnevaluatedContext())
11956     return;
11957   if (Loc.isInvalid() || Loc.isMacroID())
11958     return;
11959   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11960     return;
11961 
11962   // C / C++ fields
11963   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11964   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11965   if (ML && MR) {
11966     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11967       return;
11968     const ValueDecl *LHSDecl =
11969         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11970     const ValueDecl *RHSDecl =
11971         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11972     if (LHSDecl != RHSDecl)
11973       return;
11974     if (LHSDecl->getType().isVolatileQualified())
11975       return;
11976     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11977       if (RefTy->getPointeeType().isVolatileQualified())
11978         return;
11979 
11980     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11981   }
11982 
11983   // Objective-C instance variables
11984   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11985   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11986   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11987     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11988     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11989     if (RL && RR && RL->getDecl() == RR->getDecl())
11990       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11991   }
11992 }
11993 
11994 // C99 6.5.16.1
11995 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11996                                        SourceLocation Loc,
11997                                        QualType CompoundType) {
11998   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11999 
12000   // Verify that LHS is a modifiable lvalue, and emit error if not.
12001   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12002     return QualType();
12003 
12004   QualType LHSType = LHSExpr->getType();
12005   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12006                                              CompoundType;
12007   // OpenCL v1.2 s6.1.1.1 p2:
12008   // The half data type can only be used to declare a pointer to a buffer that
12009   // contains half values
12010   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12011     LHSType->isHalfType()) {
12012     Diag(Loc, diag::err_opencl_half_load_store) << 1
12013         << LHSType.getUnqualifiedType();
12014     return QualType();
12015   }
12016 
12017   AssignConvertType ConvTy;
12018   if (CompoundType.isNull()) {
12019     Expr *RHSCheck = RHS.get();
12020 
12021     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12022 
12023     QualType LHSTy(LHSType);
12024     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12025     if (RHS.isInvalid())
12026       return QualType();
12027     // Special case of NSObject attributes on c-style pointer types.
12028     if (ConvTy == IncompatiblePointer &&
12029         ((Context.isObjCNSObjectType(LHSType) &&
12030           RHSType->isObjCObjectPointerType()) ||
12031          (Context.isObjCNSObjectType(RHSType) &&
12032           LHSType->isObjCObjectPointerType())))
12033       ConvTy = Compatible;
12034 
12035     if (ConvTy == Compatible &&
12036         LHSType->isObjCObjectType())
12037         Diag(Loc, diag::err_objc_object_assignment)
12038           << LHSType;
12039 
12040     // If the RHS is a unary plus or minus, check to see if they = and + are
12041     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12042     // instead of "x += 4".
12043     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12044       RHSCheck = ICE->getSubExpr();
12045     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12046       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12047           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12048           // Only if the two operators are exactly adjacent.
12049           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12050           // And there is a space or other character before the subexpr of the
12051           // unary +/-.  We don't want to warn on "x=-1".
12052           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12053           UO->getSubExpr()->getBeginLoc().isFileID()) {
12054         Diag(Loc, diag::warn_not_compound_assign)
12055           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12056           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12057       }
12058     }
12059 
12060     if (ConvTy == Compatible) {
12061       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12062         // Warn about retain cycles where a block captures the LHS, but
12063         // not if the LHS is a simple variable into which the block is
12064         // being stored...unless that variable can be captured by reference!
12065         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12066         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12067         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12068           checkRetainCycles(LHSExpr, RHS.get());
12069       }
12070 
12071       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12072           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12073         // It is safe to assign a weak reference into a strong variable.
12074         // Although this code can still have problems:
12075         //   id x = self.weakProp;
12076         //   id y = self.weakProp;
12077         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12078         // paths through the function. This should be revisited if
12079         // -Wrepeated-use-of-weak is made flow-sensitive.
12080         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12081         // variable, which will be valid for the current autorelease scope.
12082         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12083                              RHS.get()->getBeginLoc()))
12084           getCurFunction()->markSafeWeakUse(RHS.get());
12085 
12086       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12087         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12088       }
12089     }
12090   } else {
12091     // Compound assignment "x += y"
12092     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12093   }
12094 
12095   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12096                                RHS.get(), AA_Assigning))
12097     return QualType();
12098 
12099   CheckForNullPointerDereference(*this, LHSExpr);
12100 
12101   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12102     if (CompoundType.isNull()) {
12103       // C++2a [expr.ass]p5:
12104       //   A simple-assignment whose left operand is of a volatile-qualified
12105       //   type is deprecated unless the assignment is either a discarded-value
12106       //   expression or an unevaluated operand
12107       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12108     } else {
12109       // C++2a [expr.ass]p6:
12110       //   [Compound-assignment] expressions are deprecated if E1 has
12111       //   volatile-qualified type
12112       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12113     }
12114   }
12115 
12116   // C99 6.5.16p3: The type of an assignment expression is the type of the
12117   // left operand unless the left operand has qualified type, in which case
12118   // it is the unqualified version of the type of the left operand.
12119   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12120   // is converted to the type of the assignment expression (above).
12121   // C++ 5.17p1: the type of the assignment expression is that of its left
12122   // operand.
12123   return (getLangOpts().CPlusPlus
12124           ? LHSType : LHSType.getUnqualifiedType());
12125 }
12126 
12127 // Only ignore explicit casts to void.
12128 static bool IgnoreCommaOperand(const Expr *E) {
12129   E = E->IgnoreParens();
12130 
12131   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12132     if (CE->getCastKind() == CK_ToVoid) {
12133       return true;
12134     }
12135 
12136     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12137     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12138         CE->getSubExpr()->getType()->isDependentType()) {
12139       return true;
12140     }
12141   }
12142 
12143   return false;
12144 }
12145 
12146 // Look for instances where it is likely the comma operator is confused with
12147 // another operator.  There is a whitelist of acceptable expressions for the
12148 // left hand side of the comma operator, otherwise emit a warning.
12149 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12150   // No warnings in macros
12151   if (Loc.isMacroID())
12152     return;
12153 
12154   // Don't warn in template instantiations.
12155   if (inTemplateInstantiation())
12156     return;
12157 
12158   // Scope isn't fine-grained enough to whitelist the specific cases, so
12159   // instead, skip more than needed, then call back into here with the
12160   // CommaVisitor in SemaStmt.cpp.
12161   // The whitelisted locations are the initialization and increment portions
12162   // of a for loop.  The additional checks are on the condition of
12163   // if statements, do/while loops, and for loops.
12164   // Differences in scope flags for C89 mode requires the extra logic.
12165   const unsigned ForIncrementFlags =
12166       getLangOpts().C99 || getLangOpts().CPlusPlus
12167           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12168           : Scope::ContinueScope | Scope::BreakScope;
12169   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12170   const unsigned ScopeFlags = getCurScope()->getFlags();
12171   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12172       (ScopeFlags & ForInitFlags) == ForInitFlags)
12173     return;
12174 
12175   // If there are multiple comma operators used together, get the RHS of the
12176   // of the comma operator as the LHS.
12177   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12178     if (BO->getOpcode() != BO_Comma)
12179       break;
12180     LHS = BO->getRHS();
12181   }
12182 
12183   // Only allow some expressions on LHS to not warn.
12184   if (IgnoreCommaOperand(LHS))
12185     return;
12186 
12187   Diag(Loc, diag::warn_comma_operator);
12188   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12189       << LHS->getSourceRange()
12190       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12191                                     LangOpts.CPlusPlus ? "static_cast<void>("
12192                                                        : "(void)(")
12193       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12194                                     ")");
12195 }
12196 
12197 // C99 6.5.17
12198 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12199                                    SourceLocation Loc) {
12200   LHS = S.CheckPlaceholderExpr(LHS.get());
12201   RHS = S.CheckPlaceholderExpr(RHS.get());
12202   if (LHS.isInvalid() || RHS.isInvalid())
12203     return QualType();
12204 
12205   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12206   // operands, but not unary promotions.
12207   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12208 
12209   // So we treat the LHS as a ignored value, and in C++ we allow the
12210   // containing site to determine what should be done with the RHS.
12211   LHS = S.IgnoredValueConversions(LHS.get());
12212   if (LHS.isInvalid())
12213     return QualType();
12214 
12215   S.DiagnoseUnusedExprResult(LHS.get());
12216 
12217   if (!S.getLangOpts().CPlusPlus) {
12218     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12219     if (RHS.isInvalid())
12220       return QualType();
12221     if (!RHS.get()->getType()->isVoidType())
12222       S.RequireCompleteType(Loc, RHS.get()->getType(),
12223                             diag::err_incomplete_type);
12224   }
12225 
12226   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12227     S.DiagnoseCommaOperator(LHS.get(), Loc);
12228 
12229   return RHS.get()->getType();
12230 }
12231 
12232 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12233 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12234 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12235                                                ExprValueKind &VK,
12236                                                ExprObjectKind &OK,
12237                                                SourceLocation OpLoc,
12238                                                bool IsInc, bool IsPrefix) {
12239   if (Op->isTypeDependent())
12240     return S.Context.DependentTy;
12241 
12242   QualType ResType = Op->getType();
12243   // Atomic types can be used for increment / decrement where the non-atomic
12244   // versions can, so ignore the _Atomic() specifier for the purpose of
12245   // checking.
12246   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12247     ResType = ResAtomicType->getValueType();
12248 
12249   assert(!ResType.isNull() && "no type for increment/decrement expression");
12250 
12251   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12252     // Decrement of bool is not allowed.
12253     if (!IsInc) {
12254       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12255       return QualType();
12256     }
12257     // Increment of bool sets it to true, but is deprecated.
12258     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12259                                               : diag::warn_increment_bool)
12260       << Op->getSourceRange();
12261   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12262     // Error on enum increments and decrements in C++ mode
12263     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12264     return QualType();
12265   } else if (ResType->isRealType()) {
12266     // OK!
12267   } else if (ResType->isPointerType()) {
12268     // C99 6.5.2.4p2, 6.5.6p2
12269     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12270       return QualType();
12271   } else if (ResType->isObjCObjectPointerType()) {
12272     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12273     // Otherwise, we just need a complete type.
12274     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12275         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12276       return QualType();
12277   } else if (ResType->isAnyComplexType()) {
12278     // C99 does not support ++/-- on complex types, we allow as an extension.
12279     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12280       << ResType << Op->getSourceRange();
12281   } else if (ResType->isPlaceholderType()) {
12282     ExprResult PR = S.CheckPlaceholderExpr(Op);
12283     if (PR.isInvalid()) return QualType();
12284     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12285                                           IsInc, IsPrefix);
12286   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12287     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12288   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12289              (ResType->castAs<VectorType>()->getVectorKind() !=
12290               VectorType::AltiVecBool)) {
12291     // The z vector extensions allow ++ and -- for non-bool vectors.
12292   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12293             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12294     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12295   } else {
12296     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12297       << ResType << int(IsInc) << Op->getSourceRange();
12298     return QualType();
12299   }
12300   // At this point, we know we have a real, complex or pointer type.
12301   // Now make sure the operand is a modifiable lvalue.
12302   if (CheckForModifiableLvalue(Op, OpLoc, S))
12303     return QualType();
12304   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12305     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12306     //   An operand with volatile-qualified type is deprecated
12307     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12308         << IsInc << ResType;
12309   }
12310   // In C++, a prefix increment is the same type as the operand. Otherwise
12311   // (in C or with postfix), the increment is the unqualified type of the
12312   // operand.
12313   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12314     VK = VK_LValue;
12315     OK = Op->getObjectKind();
12316     return ResType;
12317   } else {
12318     VK = VK_RValue;
12319     return ResType.getUnqualifiedType();
12320   }
12321 }
12322 
12323 
12324 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12325 /// This routine allows us to typecheck complex/recursive expressions
12326 /// where the declaration is needed for type checking. We only need to
12327 /// handle cases when the expression references a function designator
12328 /// or is an lvalue. Here are some examples:
12329 ///  - &(x) => x
12330 ///  - &*****f => f for f a function designator.
12331 ///  - &s.xx => s
12332 ///  - &s.zz[1].yy -> s, if zz is an array
12333 ///  - *(x + 1) -> x, if x is an array
12334 ///  - &"123"[2] -> 0
12335 ///  - & __real__ x -> x
12336 static ValueDecl *getPrimaryDecl(Expr *E) {
12337   switch (E->getStmtClass()) {
12338   case Stmt::DeclRefExprClass:
12339     return cast<DeclRefExpr>(E)->getDecl();
12340   case Stmt::MemberExprClass:
12341     // If this is an arrow operator, the address is an offset from
12342     // the base's value, so the object the base refers to is
12343     // irrelevant.
12344     if (cast<MemberExpr>(E)->isArrow())
12345       return nullptr;
12346     // Otherwise, the expression refers to a part of the base
12347     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12348   case Stmt::ArraySubscriptExprClass: {
12349     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12350     // promotion of register arrays earlier.
12351     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12352     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12353       if (ICE->getSubExpr()->getType()->isArrayType())
12354         return getPrimaryDecl(ICE->getSubExpr());
12355     }
12356     return nullptr;
12357   }
12358   case Stmt::UnaryOperatorClass: {
12359     UnaryOperator *UO = cast<UnaryOperator>(E);
12360 
12361     switch(UO->getOpcode()) {
12362     case UO_Real:
12363     case UO_Imag:
12364     case UO_Extension:
12365       return getPrimaryDecl(UO->getSubExpr());
12366     default:
12367       return nullptr;
12368     }
12369   }
12370   case Stmt::ParenExprClass:
12371     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12372   case Stmt::ImplicitCastExprClass:
12373     // If the result of an implicit cast is an l-value, we care about
12374     // the sub-expression; otherwise, the result here doesn't matter.
12375     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12376   default:
12377     return nullptr;
12378   }
12379 }
12380 
12381 namespace {
12382   enum {
12383     AO_Bit_Field = 0,
12384     AO_Vector_Element = 1,
12385     AO_Property_Expansion = 2,
12386     AO_Register_Variable = 3,
12387     AO_No_Error = 4
12388   };
12389 }
12390 /// Diagnose invalid operand for address of operations.
12391 ///
12392 /// \param Type The type of operand which cannot have its address taken.
12393 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12394                                          Expr *E, unsigned Type) {
12395   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12396 }
12397 
12398 /// CheckAddressOfOperand - The operand of & must be either a function
12399 /// designator or an lvalue designating an object. If it is an lvalue, the
12400 /// object cannot be declared with storage class register or be a bit field.
12401 /// Note: The usual conversions are *not* applied to the operand of the &
12402 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12403 /// In C++, the operand might be an overloaded function name, in which case
12404 /// we allow the '&' but retain the overloaded-function type.
12405 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12406   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12407     if (PTy->getKind() == BuiltinType::Overload) {
12408       Expr *E = OrigOp.get()->IgnoreParens();
12409       if (!isa<OverloadExpr>(E)) {
12410         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12411         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12412           << OrigOp.get()->getSourceRange();
12413         return QualType();
12414       }
12415 
12416       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12417       if (isa<UnresolvedMemberExpr>(Ovl))
12418         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12419           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12420             << OrigOp.get()->getSourceRange();
12421           return QualType();
12422         }
12423 
12424       return Context.OverloadTy;
12425     }
12426 
12427     if (PTy->getKind() == BuiltinType::UnknownAny)
12428       return Context.UnknownAnyTy;
12429 
12430     if (PTy->getKind() == BuiltinType::BoundMember) {
12431       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12432         << OrigOp.get()->getSourceRange();
12433       return QualType();
12434     }
12435 
12436     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12437     if (OrigOp.isInvalid()) return QualType();
12438   }
12439 
12440   if (OrigOp.get()->isTypeDependent())
12441     return Context.DependentTy;
12442 
12443   assert(!OrigOp.get()->getType()->isPlaceholderType());
12444 
12445   // Make sure to ignore parentheses in subsequent checks
12446   Expr *op = OrigOp.get()->IgnoreParens();
12447 
12448   // In OpenCL captures for blocks called as lambda functions
12449   // are located in the private address space. Blocks used in
12450   // enqueue_kernel can be located in a different address space
12451   // depending on a vendor implementation. Thus preventing
12452   // taking an address of the capture to avoid invalid AS casts.
12453   if (LangOpts.OpenCL) {
12454     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12455     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12456       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12457       return QualType();
12458     }
12459   }
12460 
12461   if (getLangOpts().C99) {
12462     // Implement C99-only parts of addressof rules.
12463     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12464       if (uOp->getOpcode() == UO_Deref)
12465         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12466         // (assuming the deref expression is valid).
12467         return uOp->getSubExpr()->getType();
12468     }
12469     // Technically, there should be a check for array subscript
12470     // expressions here, but the result of one is always an lvalue anyway.
12471   }
12472   ValueDecl *dcl = getPrimaryDecl(op);
12473 
12474   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12475     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12476                                            op->getBeginLoc()))
12477       return QualType();
12478 
12479   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12480   unsigned AddressOfError = AO_No_Error;
12481 
12482   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12483     bool sfinae = (bool)isSFINAEContext();
12484     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12485                                   : diag::ext_typecheck_addrof_temporary)
12486       << op->getType() << op->getSourceRange();
12487     if (sfinae)
12488       return QualType();
12489     // Materialize the temporary as an lvalue so that we can take its address.
12490     OrigOp = op =
12491         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12492   } else if (isa<ObjCSelectorExpr>(op)) {
12493     return Context.getPointerType(op->getType());
12494   } else if (lval == Expr::LV_MemberFunction) {
12495     // If it's an instance method, make a member pointer.
12496     // The expression must have exactly the form &A::foo.
12497 
12498     // If the underlying expression isn't a decl ref, give up.
12499     if (!isa<DeclRefExpr>(op)) {
12500       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12501         << OrigOp.get()->getSourceRange();
12502       return QualType();
12503     }
12504     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12505     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12506 
12507     // The id-expression was parenthesized.
12508     if (OrigOp.get() != DRE) {
12509       Diag(OpLoc, diag::err_parens_pointer_member_function)
12510         << OrigOp.get()->getSourceRange();
12511 
12512     // The method was named without a qualifier.
12513     } else if (!DRE->getQualifier()) {
12514       if (MD->getParent()->getName().empty())
12515         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12516           << op->getSourceRange();
12517       else {
12518         SmallString<32> Str;
12519         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12520         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12521           << op->getSourceRange()
12522           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12523       }
12524     }
12525 
12526     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12527     if (isa<CXXDestructorDecl>(MD))
12528       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12529 
12530     QualType MPTy = Context.getMemberPointerType(
12531         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12532     // Under the MS ABI, lock down the inheritance model now.
12533     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12534       (void)isCompleteType(OpLoc, MPTy);
12535     return MPTy;
12536   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12537     // C99 6.5.3.2p1
12538     // The operand must be either an l-value or a function designator
12539     if (!op->getType()->isFunctionType()) {
12540       // Use a special diagnostic for loads from property references.
12541       if (isa<PseudoObjectExpr>(op)) {
12542         AddressOfError = AO_Property_Expansion;
12543       } else {
12544         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12545           << op->getType() << op->getSourceRange();
12546         return QualType();
12547       }
12548     }
12549   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12550     // The operand cannot be a bit-field
12551     AddressOfError = AO_Bit_Field;
12552   } else if (op->getObjectKind() == OK_VectorComponent) {
12553     // The operand cannot be an element of a vector
12554     AddressOfError = AO_Vector_Element;
12555   } else if (dcl) { // C99 6.5.3.2p1
12556     // We have an lvalue with a decl. Make sure the decl is not declared
12557     // with the register storage-class specifier.
12558     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12559       // in C++ it is not error to take address of a register
12560       // variable (c++03 7.1.1P3)
12561       if (vd->getStorageClass() == SC_Register &&
12562           !getLangOpts().CPlusPlus) {
12563         AddressOfError = AO_Register_Variable;
12564       }
12565     } else if (isa<MSPropertyDecl>(dcl)) {
12566       AddressOfError = AO_Property_Expansion;
12567     } else if (isa<FunctionTemplateDecl>(dcl)) {
12568       return Context.OverloadTy;
12569     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12570       // Okay: we can take the address of a field.
12571       // Could be a pointer to member, though, if there is an explicit
12572       // scope qualifier for the class.
12573       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12574         DeclContext *Ctx = dcl->getDeclContext();
12575         if (Ctx && Ctx->isRecord()) {
12576           if (dcl->getType()->isReferenceType()) {
12577             Diag(OpLoc,
12578                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12579               << dcl->getDeclName() << dcl->getType();
12580             return QualType();
12581           }
12582 
12583           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12584             Ctx = Ctx->getParent();
12585 
12586           QualType MPTy = Context.getMemberPointerType(
12587               op->getType(),
12588               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12589           // Under the MS ABI, lock down the inheritance model now.
12590           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12591             (void)isCompleteType(OpLoc, MPTy);
12592           return MPTy;
12593         }
12594       }
12595     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12596                !isa<BindingDecl>(dcl))
12597       llvm_unreachable("Unknown/unexpected decl type");
12598   }
12599 
12600   if (AddressOfError != AO_No_Error) {
12601     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12602     return QualType();
12603   }
12604 
12605   if (lval == Expr::LV_IncompleteVoidType) {
12606     // Taking the address of a void variable is technically illegal, but we
12607     // allow it in cases which are otherwise valid.
12608     // Example: "extern void x; void* y = &x;".
12609     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12610   }
12611 
12612   // If the operand has type "type", the result has type "pointer to type".
12613   if (op->getType()->isObjCObjectType())
12614     return Context.getObjCObjectPointerType(op->getType());
12615 
12616   CheckAddressOfPackedMember(op);
12617 
12618   return Context.getPointerType(op->getType());
12619 }
12620 
12621 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12622   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12623   if (!DRE)
12624     return;
12625   const Decl *D = DRE->getDecl();
12626   if (!D)
12627     return;
12628   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12629   if (!Param)
12630     return;
12631   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12632     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12633       return;
12634   if (FunctionScopeInfo *FD = S.getCurFunction())
12635     if (!FD->ModifiedNonNullParams.count(Param))
12636       FD->ModifiedNonNullParams.insert(Param);
12637 }
12638 
12639 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12640 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12641                                         SourceLocation OpLoc) {
12642   if (Op->isTypeDependent())
12643     return S.Context.DependentTy;
12644 
12645   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12646   if (ConvResult.isInvalid())
12647     return QualType();
12648   Op = ConvResult.get();
12649   QualType OpTy = Op->getType();
12650   QualType Result;
12651 
12652   if (isa<CXXReinterpretCastExpr>(Op)) {
12653     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12654     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12655                                      Op->getSourceRange());
12656   }
12657 
12658   if (const PointerType *PT = OpTy->getAs<PointerType>())
12659   {
12660     Result = PT->getPointeeType();
12661   }
12662   else if (const ObjCObjectPointerType *OPT =
12663              OpTy->getAs<ObjCObjectPointerType>())
12664     Result = OPT->getPointeeType();
12665   else {
12666     ExprResult PR = S.CheckPlaceholderExpr(Op);
12667     if (PR.isInvalid()) return QualType();
12668     if (PR.get() != Op)
12669       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12670   }
12671 
12672   if (Result.isNull()) {
12673     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12674       << OpTy << Op->getSourceRange();
12675     return QualType();
12676   }
12677 
12678   // Note that per both C89 and C99, indirection is always legal, even if Result
12679   // is an incomplete type or void.  It would be possible to warn about
12680   // dereferencing a void pointer, but it's completely well-defined, and such a
12681   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12682   // for pointers to 'void' but is fine for any other pointer type:
12683   //
12684   // C++ [expr.unary.op]p1:
12685   //   [...] the expression to which [the unary * operator] is applied shall
12686   //   be a pointer to an object type, or a pointer to a function type
12687   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12688     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12689       << OpTy << Op->getSourceRange();
12690 
12691   // Dereferences are usually l-values...
12692   VK = VK_LValue;
12693 
12694   // ...except that certain expressions are never l-values in C.
12695   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12696     VK = VK_RValue;
12697 
12698   return Result;
12699 }
12700 
12701 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12702   BinaryOperatorKind Opc;
12703   switch (Kind) {
12704   default: llvm_unreachable("Unknown binop!");
12705   case tok::periodstar:           Opc = BO_PtrMemD; break;
12706   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12707   case tok::star:                 Opc = BO_Mul; break;
12708   case tok::slash:                Opc = BO_Div; break;
12709   case tok::percent:              Opc = BO_Rem; break;
12710   case tok::plus:                 Opc = BO_Add; break;
12711   case tok::minus:                Opc = BO_Sub; break;
12712   case tok::lessless:             Opc = BO_Shl; break;
12713   case tok::greatergreater:       Opc = BO_Shr; break;
12714   case tok::lessequal:            Opc = BO_LE; break;
12715   case tok::less:                 Opc = BO_LT; break;
12716   case tok::greaterequal:         Opc = BO_GE; break;
12717   case tok::greater:              Opc = BO_GT; break;
12718   case tok::exclaimequal:         Opc = BO_NE; break;
12719   case tok::equalequal:           Opc = BO_EQ; break;
12720   case tok::spaceship:            Opc = BO_Cmp; break;
12721   case tok::amp:                  Opc = BO_And; break;
12722   case tok::caret:                Opc = BO_Xor; break;
12723   case tok::pipe:                 Opc = BO_Or; break;
12724   case tok::ampamp:               Opc = BO_LAnd; break;
12725   case tok::pipepipe:             Opc = BO_LOr; break;
12726   case tok::equal:                Opc = BO_Assign; break;
12727   case tok::starequal:            Opc = BO_MulAssign; break;
12728   case tok::slashequal:           Opc = BO_DivAssign; break;
12729   case tok::percentequal:         Opc = BO_RemAssign; break;
12730   case tok::plusequal:            Opc = BO_AddAssign; break;
12731   case tok::minusequal:           Opc = BO_SubAssign; break;
12732   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12733   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12734   case tok::ampequal:             Opc = BO_AndAssign; break;
12735   case tok::caretequal:           Opc = BO_XorAssign; break;
12736   case tok::pipeequal:            Opc = BO_OrAssign; break;
12737   case tok::comma:                Opc = BO_Comma; break;
12738   }
12739   return Opc;
12740 }
12741 
12742 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12743   tok::TokenKind Kind) {
12744   UnaryOperatorKind Opc;
12745   switch (Kind) {
12746   default: llvm_unreachable("Unknown unary op!");
12747   case tok::plusplus:     Opc = UO_PreInc; break;
12748   case tok::minusminus:   Opc = UO_PreDec; break;
12749   case tok::amp:          Opc = UO_AddrOf; break;
12750   case tok::star:         Opc = UO_Deref; break;
12751   case tok::plus:         Opc = UO_Plus; break;
12752   case tok::minus:        Opc = UO_Minus; break;
12753   case tok::tilde:        Opc = UO_Not; break;
12754   case tok::exclaim:      Opc = UO_LNot; break;
12755   case tok::kw___real:    Opc = UO_Real; break;
12756   case tok::kw___imag:    Opc = UO_Imag; break;
12757   case tok::kw___extension__: Opc = UO_Extension; break;
12758   }
12759   return Opc;
12760 }
12761 
12762 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12763 /// This warning suppressed in the event of macro expansions.
12764 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12765                                    SourceLocation OpLoc, bool IsBuiltin) {
12766   if (S.inTemplateInstantiation())
12767     return;
12768   if (S.isUnevaluatedContext())
12769     return;
12770   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12771     return;
12772   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12773   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12774   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12775   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12776   if (!LHSDeclRef || !RHSDeclRef ||
12777       LHSDeclRef->getLocation().isMacroID() ||
12778       RHSDeclRef->getLocation().isMacroID())
12779     return;
12780   const ValueDecl *LHSDecl =
12781     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12782   const ValueDecl *RHSDecl =
12783     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12784   if (LHSDecl != RHSDecl)
12785     return;
12786   if (LHSDecl->getType().isVolatileQualified())
12787     return;
12788   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12789     if (RefTy->getPointeeType().isVolatileQualified())
12790       return;
12791 
12792   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12793                           : diag::warn_self_assignment_overloaded)
12794       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12795       << RHSExpr->getSourceRange();
12796 }
12797 
12798 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12799 /// is usually indicative of introspection within the Objective-C pointer.
12800 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12801                                           SourceLocation OpLoc) {
12802   if (!S.getLangOpts().ObjC)
12803     return;
12804 
12805   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12806   const Expr *LHS = L.get();
12807   const Expr *RHS = R.get();
12808 
12809   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12810     ObjCPointerExpr = LHS;
12811     OtherExpr = RHS;
12812   }
12813   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12814     ObjCPointerExpr = RHS;
12815     OtherExpr = LHS;
12816   }
12817 
12818   // This warning is deliberately made very specific to reduce false
12819   // positives with logic that uses '&' for hashing.  This logic mainly
12820   // looks for code trying to introspect into tagged pointers, which
12821   // code should generally never do.
12822   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12823     unsigned Diag = diag::warn_objc_pointer_masking;
12824     // Determine if we are introspecting the result of performSelectorXXX.
12825     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12826     // Special case messages to -performSelector and friends, which
12827     // can return non-pointer values boxed in a pointer value.
12828     // Some clients may wish to silence warnings in this subcase.
12829     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12830       Selector S = ME->getSelector();
12831       StringRef SelArg0 = S.getNameForSlot(0);
12832       if (SelArg0.startswith("performSelector"))
12833         Diag = diag::warn_objc_pointer_masking_performSelector;
12834     }
12835 
12836     S.Diag(OpLoc, Diag)
12837       << ObjCPointerExpr->getSourceRange();
12838   }
12839 }
12840 
12841 static NamedDecl *getDeclFromExpr(Expr *E) {
12842   if (!E)
12843     return nullptr;
12844   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12845     return DRE->getDecl();
12846   if (auto *ME = dyn_cast<MemberExpr>(E))
12847     return ME->getMemberDecl();
12848   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12849     return IRE->getDecl();
12850   return nullptr;
12851 }
12852 
12853 // This helper function promotes a binary operator's operands (which are of a
12854 // half vector type) to a vector of floats and then truncates the result to
12855 // a vector of either half or short.
12856 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12857                                       BinaryOperatorKind Opc, QualType ResultTy,
12858                                       ExprValueKind VK, ExprObjectKind OK,
12859                                       bool IsCompAssign, SourceLocation OpLoc,
12860                                       FPOptions FPFeatures) {
12861   auto &Context = S.getASTContext();
12862   assert((isVector(ResultTy, Context.HalfTy) ||
12863           isVector(ResultTy, Context.ShortTy)) &&
12864          "Result must be a vector of half or short");
12865   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12866          isVector(RHS.get()->getType(), Context.HalfTy) &&
12867          "both operands expected to be a half vector");
12868 
12869   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12870   QualType BinOpResTy = RHS.get()->getType();
12871 
12872   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12873   // change BinOpResTy to a vector of ints.
12874   if (isVector(ResultTy, Context.ShortTy))
12875     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12876 
12877   if (IsCompAssign)
12878     return new (Context) CompoundAssignOperator(
12879         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12880         OpLoc, FPFeatures);
12881 
12882   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12883   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12884                                           VK, OK, OpLoc, FPFeatures);
12885   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12886 }
12887 
12888 static std::pair<ExprResult, ExprResult>
12889 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12890                            Expr *RHSExpr) {
12891   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12892   if (!S.getLangOpts().CPlusPlus) {
12893     // C cannot handle TypoExpr nodes on either side of a binop because it
12894     // doesn't handle dependent types properly, so make sure any TypoExprs have
12895     // been dealt with before checking the operands.
12896     LHS = S.CorrectDelayedTyposInExpr(LHS);
12897     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12898       if (Opc != BO_Assign)
12899         return ExprResult(E);
12900       // Avoid correcting the RHS to the same Expr as the LHS.
12901       Decl *D = getDeclFromExpr(E);
12902       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12903     });
12904   }
12905   return std::make_pair(LHS, RHS);
12906 }
12907 
12908 /// Returns true if conversion between vectors of halfs and vectors of floats
12909 /// is needed.
12910 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12911                                      QualType SrcType) {
12912   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12913          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12914          isVector(SrcType, Ctx.HalfTy);
12915 }
12916 
12917 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12918 /// operator @p Opc at location @c TokLoc. This routine only supports
12919 /// built-in operations; ActOnBinOp handles overloaded operators.
12920 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12921                                     BinaryOperatorKind Opc,
12922                                     Expr *LHSExpr, Expr *RHSExpr) {
12923   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12924     // The syntax only allows initializer lists on the RHS of assignment,
12925     // so we don't need to worry about accepting invalid code for
12926     // non-assignment operators.
12927     // C++11 5.17p9:
12928     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12929     //   of x = {} is x = T().
12930     InitializationKind Kind = InitializationKind::CreateDirectList(
12931         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12932     InitializedEntity Entity =
12933         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12934     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12935     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12936     if (Init.isInvalid())
12937       return Init;
12938     RHSExpr = Init.get();
12939   }
12940 
12941   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12942   QualType ResultTy;     // Result type of the binary operator.
12943   // The following two variables are used for compound assignment operators
12944   QualType CompLHSTy;    // Type of LHS after promotions for computation
12945   QualType CompResultTy; // Type of computation result
12946   ExprValueKind VK = VK_RValue;
12947   ExprObjectKind OK = OK_Ordinary;
12948   bool ConvertHalfVec = false;
12949 
12950   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12951   if (!LHS.isUsable() || !RHS.isUsable())
12952     return ExprError();
12953 
12954   if (getLangOpts().OpenCL) {
12955     QualType LHSTy = LHSExpr->getType();
12956     QualType RHSTy = RHSExpr->getType();
12957     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12958     // the ATOMIC_VAR_INIT macro.
12959     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12960       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12961       if (BO_Assign == Opc)
12962         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12963       else
12964         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12965       return ExprError();
12966     }
12967 
12968     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12969     // only with a builtin functions and therefore should be disallowed here.
12970     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12971         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12972         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12973         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12974       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12975       return ExprError();
12976     }
12977   }
12978 
12979   // Diagnose operations on the unsupported types for OpenMP device compilation.
12980   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12981     if (Opc != BO_Assign && Opc != BO_Comma) {
12982       checkOpenMPDeviceExpr(LHSExpr);
12983       checkOpenMPDeviceExpr(RHSExpr);
12984     }
12985   }
12986 
12987   switch (Opc) {
12988   case BO_Assign:
12989     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12990     if (getLangOpts().CPlusPlus &&
12991         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12992       VK = LHS.get()->getValueKind();
12993       OK = LHS.get()->getObjectKind();
12994     }
12995     if (!ResultTy.isNull()) {
12996       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12997       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12998 
12999       // Avoid copying a block to the heap if the block is assigned to a local
13000       // auto variable that is declared in the same scope as the block. This
13001       // optimization is unsafe if the local variable is declared in an outer
13002       // scope. For example:
13003       //
13004       // BlockTy b;
13005       // {
13006       //   b = ^{...};
13007       // }
13008       // // It is unsafe to invoke the block here if it wasn't copied to the
13009       // // heap.
13010       // b();
13011 
13012       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13013         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13014           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13015             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13016               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13017 
13018       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13019         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13020                               NTCUC_Assignment, NTCUK_Copy);
13021     }
13022     RecordModifiableNonNullParam(*this, LHS.get());
13023     break;
13024   case BO_PtrMemD:
13025   case BO_PtrMemI:
13026     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13027                                             Opc == BO_PtrMemI);
13028     break;
13029   case BO_Mul:
13030   case BO_Div:
13031     ConvertHalfVec = true;
13032     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13033                                            Opc == BO_Div);
13034     break;
13035   case BO_Rem:
13036     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13037     break;
13038   case BO_Add:
13039     ConvertHalfVec = true;
13040     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13041     break;
13042   case BO_Sub:
13043     ConvertHalfVec = true;
13044     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13045     break;
13046   case BO_Shl:
13047   case BO_Shr:
13048     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13049     break;
13050   case BO_LE:
13051   case BO_LT:
13052   case BO_GE:
13053   case BO_GT:
13054     ConvertHalfVec = true;
13055     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13056     break;
13057   case BO_EQ:
13058   case BO_NE:
13059     ConvertHalfVec = true;
13060     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13061     break;
13062   case BO_Cmp:
13063     ConvertHalfVec = true;
13064     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13065     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13066     break;
13067   case BO_And:
13068     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13069     LLVM_FALLTHROUGH;
13070   case BO_Xor:
13071   case BO_Or:
13072     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13073     break;
13074   case BO_LAnd:
13075   case BO_LOr:
13076     ConvertHalfVec = true;
13077     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13078     break;
13079   case BO_MulAssign:
13080   case BO_DivAssign:
13081     ConvertHalfVec = true;
13082     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13083                                                Opc == BO_DivAssign);
13084     CompLHSTy = CompResultTy;
13085     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13086       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13087     break;
13088   case BO_RemAssign:
13089     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13090     CompLHSTy = CompResultTy;
13091     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13092       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13093     break;
13094   case BO_AddAssign:
13095     ConvertHalfVec = true;
13096     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13097     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13098       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13099     break;
13100   case BO_SubAssign:
13101     ConvertHalfVec = true;
13102     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13103     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13104       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13105     break;
13106   case BO_ShlAssign:
13107   case BO_ShrAssign:
13108     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13109     CompLHSTy = CompResultTy;
13110     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13111       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13112     break;
13113   case BO_AndAssign:
13114   case BO_OrAssign: // fallthrough
13115     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13116     LLVM_FALLTHROUGH;
13117   case BO_XorAssign:
13118     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13119     CompLHSTy = CompResultTy;
13120     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13121       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13122     break;
13123   case BO_Comma:
13124     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13125     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13126       VK = RHS.get()->getValueKind();
13127       OK = RHS.get()->getObjectKind();
13128     }
13129     break;
13130   }
13131   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13132     return ExprError();
13133 
13134   if (ResultTy->isRealFloatingType() &&
13135       (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13136        getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13137     // Mark the current function as usng floating point constrained intrinsics
13138     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13139       F->setUsesFPIntrin(true);
13140     }
13141 
13142   // Some of the binary operations require promoting operands of half vector to
13143   // float vectors and truncating the result back to half vector. For now, we do
13144   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13145   // arm64).
13146   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13147          isVector(LHS.get()->getType(), Context.HalfTy) &&
13148          "both sides are half vectors or neither sides are");
13149   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13150                                             LHS.get()->getType());
13151 
13152   // Check for array bounds violations for both sides of the BinaryOperator
13153   CheckArrayAccess(LHS.get());
13154   CheckArrayAccess(RHS.get());
13155 
13156   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13157     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13158                                                  &Context.Idents.get("object_setClass"),
13159                                                  SourceLocation(), LookupOrdinaryName);
13160     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13161       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13162       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13163           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13164                                         "object_setClass(")
13165           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13166                                           ",")
13167           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13168     }
13169     else
13170       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13171   }
13172   else if (const ObjCIvarRefExpr *OIRE =
13173            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13174     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13175 
13176   // Opc is not a compound assignment if CompResultTy is null.
13177   if (CompResultTy.isNull()) {
13178     if (ConvertHalfVec)
13179       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13180                                  OpLoc, FPFeatures);
13181     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13182                                         OK, OpLoc, FPFeatures);
13183   }
13184 
13185   // Handle compound assignments.
13186   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13187       OK_ObjCProperty) {
13188     VK = VK_LValue;
13189     OK = LHS.get()->getObjectKind();
13190   }
13191 
13192   if (ConvertHalfVec)
13193     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13194                                OpLoc, FPFeatures);
13195 
13196   return new (Context) CompoundAssignOperator(
13197       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13198       OpLoc, FPFeatures);
13199 }
13200 
13201 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13202 /// operators are mixed in a way that suggests that the programmer forgot that
13203 /// comparison operators have higher precedence. The most typical example of
13204 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13205 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13206                                       SourceLocation OpLoc, Expr *LHSExpr,
13207                                       Expr *RHSExpr) {
13208   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13209   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13210 
13211   // Check that one of the sides is a comparison operator and the other isn't.
13212   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13213   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13214   if (isLeftComp == isRightComp)
13215     return;
13216 
13217   // Bitwise operations are sometimes used as eager logical ops.
13218   // Don't diagnose this.
13219   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13220   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13221   if (isLeftBitwise || isRightBitwise)
13222     return;
13223 
13224   SourceRange DiagRange = isLeftComp
13225                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13226                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13227   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13228   SourceRange ParensRange =
13229       isLeftComp
13230           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13231           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13232 
13233   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13234     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13235   SuggestParentheses(Self, OpLoc,
13236     Self.PDiag(diag::note_precedence_silence) << OpStr,
13237     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13238   SuggestParentheses(Self, OpLoc,
13239     Self.PDiag(diag::note_precedence_bitwise_first)
13240       << BinaryOperator::getOpcodeStr(Opc),
13241     ParensRange);
13242 }
13243 
13244 /// It accepts a '&&' expr that is inside a '||' one.
13245 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13246 /// in parentheses.
13247 static void
13248 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13249                                        BinaryOperator *Bop) {
13250   assert(Bop->getOpcode() == BO_LAnd);
13251   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13252       << Bop->getSourceRange() << OpLoc;
13253   SuggestParentheses(Self, Bop->getOperatorLoc(),
13254     Self.PDiag(diag::note_precedence_silence)
13255       << Bop->getOpcodeStr(),
13256     Bop->getSourceRange());
13257 }
13258 
13259 /// Returns true if the given expression can be evaluated as a constant
13260 /// 'true'.
13261 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13262   bool Res;
13263   return !E->isValueDependent() &&
13264          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13265 }
13266 
13267 /// Returns true if the given expression can be evaluated as a constant
13268 /// 'false'.
13269 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13270   bool Res;
13271   return !E->isValueDependent() &&
13272          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13273 }
13274 
13275 /// Look for '&&' in the left hand of a '||' expr.
13276 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13277                                              Expr *LHSExpr, Expr *RHSExpr) {
13278   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13279     if (Bop->getOpcode() == BO_LAnd) {
13280       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13281       if (EvaluatesAsFalse(S, RHSExpr))
13282         return;
13283       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13284       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13285         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13286     } else if (Bop->getOpcode() == BO_LOr) {
13287       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13288         // If it's "a || b && 1 || c" we didn't warn earlier for
13289         // "a || b && 1", but warn now.
13290         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13291           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13292       }
13293     }
13294   }
13295 }
13296 
13297 /// Look for '&&' in the right hand of a '||' expr.
13298 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13299                                              Expr *LHSExpr, Expr *RHSExpr) {
13300   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13301     if (Bop->getOpcode() == BO_LAnd) {
13302       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13303       if (EvaluatesAsFalse(S, LHSExpr))
13304         return;
13305       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13306       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13307         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13308     }
13309   }
13310 }
13311 
13312 /// Look for bitwise op in the left or right hand of a bitwise op with
13313 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13314 /// the '&' expression in parentheses.
13315 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13316                                          SourceLocation OpLoc, Expr *SubExpr) {
13317   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13318     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13319       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13320         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13321         << Bop->getSourceRange() << OpLoc;
13322       SuggestParentheses(S, Bop->getOperatorLoc(),
13323         S.PDiag(diag::note_precedence_silence)
13324           << Bop->getOpcodeStr(),
13325         Bop->getSourceRange());
13326     }
13327   }
13328 }
13329 
13330 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13331                                     Expr *SubExpr, StringRef Shift) {
13332   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13333     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13334       StringRef Op = Bop->getOpcodeStr();
13335       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13336           << Bop->getSourceRange() << OpLoc << Shift << Op;
13337       SuggestParentheses(S, Bop->getOperatorLoc(),
13338           S.PDiag(diag::note_precedence_silence) << Op,
13339           Bop->getSourceRange());
13340     }
13341   }
13342 }
13343 
13344 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13345                                  Expr *LHSExpr, Expr *RHSExpr) {
13346   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13347   if (!OCE)
13348     return;
13349 
13350   FunctionDecl *FD = OCE->getDirectCallee();
13351   if (!FD || !FD->isOverloadedOperator())
13352     return;
13353 
13354   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13355   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13356     return;
13357 
13358   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13359       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13360       << (Kind == OO_LessLess);
13361   SuggestParentheses(S, OCE->getOperatorLoc(),
13362                      S.PDiag(diag::note_precedence_silence)
13363                          << (Kind == OO_LessLess ? "<<" : ">>"),
13364                      OCE->getSourceRange());
13365   SuggestParentheses(
13366       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13367       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13368 }
13369 
13370 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13371 /// precedence.
13372 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13373                                     SourceLocation OpLoc, Expr *LHSExpr,
13374                                     Expr *RHSExpr){
13375   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13376   if (BinaryOperator::isBitwiseOp(Opc))
13377     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13378 
13379   // Diagnose "arg1 & arg2 | arg3"
13380   if ((Opc == BO_Or || Opc == BO_Xor) &&
13381       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13382     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13383     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13384   }
13385 
13386   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13387   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13388   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13389     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13390     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13391   }
13392 
13393   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13394       || Opc == BO_Shr) {
13395     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13396     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13397     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13398   }
13399 
13400   // Warn on overloaded shift operators and comparisons, such as:
13401   // cout << 5 == 4;
13402   if (BinaryOperator::isComparisonOp(Opc))
13403     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13404 }
13405 
13406 // Binary Operators.  'Tok' is the token for the operator.
13407 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13408                             tok::TokenKind Kind,
13409                             Expr *LHSExpr, Expr *RHSExpr) {
13410   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13411   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13412   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13413 
13414   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13415   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13416 
13417   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13418 }
13419 
13420 /// Build an overloaded binary operator expression in the given scope.
13421 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13422                                        BinaryOperatorKind Opc,
13423                                        Expr *LHS, Expr *RHS) {
13424   switch (Opc) {
13425   case BO_Assign:
13426   case BO_DivAssign:
13427   case BO_RemAssign:
13428   case BO_SubAssign:
13429   case BO_AndAssign:
13430   case BO_OrAssign:
13431   case BO_XorAssign:
13432     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13433     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13434     break;
13435   default:
13436     break;
13437   }
13438 
13439   // Find all of the overloaded operators visible from this
13440   // point. We perform both an operator-name lookup from the local
13441   // scope and an argument-dependent lookup based on the types of
13442   // the arguments.
13443   UnresolvedSet<16> Functions;
13444   OverloadedOperatorKind OverOp
13445     = BinaryOperator::getOverloadedOperator(Opc);
13446   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13447     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13448                                    RHS->getType(), Functions);
13449 
13450   // In C++20 onwards, we may have a second operator to look up.
13451   if (S.getLangOpts().CPlusPlus2a) {
13452     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13453       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13454                                      RHS->getType(), Functions);
13455   }
13456 
13457   // Build the (potentially-overloaded, potentially-dependent)
13458   // binary operation.
13459   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13460 }
13461 
13462 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13463                             BinaryOperatorKind Opc,
13464                             Expr *LHSExpr, Expr *RHSExpr) {
13465   ExprResult LHS, RHS;
13466   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13467   if (!LHS.isUsable() || !RHS.isUsable())
13468     return ExprError();
13469   LHSExpr = LHS.get();
13470   RHSExpr = RHS.get();
13471 
13472   // We want to end up calling one of checkPseudoObjectAssignment
13473   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13474   // both expressions are overloadable or either is type-dependent),
13475   // or CreateBuiltinBinOp (in any other case).  We also want to get
13476   // any placeholder types out of the way.
13477 
13478   // Handle pseudo-objects in the LHS.
13479   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13480     // Assignments with a pseudo-object l-value need special analysis.
13481     if (pty->getKind() == BuiltinType::PseudoObject &&
13482         BinaryOperator::isAssignmentOp(Opc))
13483       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13484 
13485     // Don't resolve overloads if the other type is overloadable.
13486     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13487       // We can't actually test that if we still have a placeholder,
13488       // though.  Fortunately, none of the exceptions we see in that
13489       // code below are valid when the LHS is an overload set.  Note
13490       // that an overload set can be dependently-typed, but it never
13491       // instantiates to having an overloadable type.
13492       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13493       if (resolvedRHS.isInvalid()) return ExprError();
13494       RHSExpr = resolvedRHS.get();
13495 
13496       if (RHSExpr->isTypeDependent() ||
13497           RHSExpr->getType()->isOverloadableType())
13498         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13499     }
13500 
13501     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13502     // template, diagnose the missing 'template' keyword instead of diagnosing
13503     // an invalid use of a bound member function.
13504     //
13505     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13506     // to C++1z [over.over]/1.4, but we already checked for that case above.
13507     if (Opc == BO_LT && inTemplateInstantiation() &&
13508         (pty->getKind() == BuiltinType::BoundMember ||
13509          pty->getKind() == BuiltinType::Overload)) {
13510       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13511       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13512           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13513             return isa<FunctionTemplateDecl>(ND);
13514           })) {
13515         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13516                                 : OE->getNameLoc(),
13517              diag::err_template_kw_missing)
13518           << OE->getName().getAsString() << "";
13519         return ExprError();
13520       }
13521     }
13522 
13523     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13524     if (LHS.isInvalid()) return ExprError();
13525     LHSExpr = LHS.get();
13526   }
13527 
13528   // Handle pseudo-objects in the RHS.
13529   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13530     // An overload in the RHS can potentially be resolved by the type
13531     // being assigned to.
13532     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13533       if (getLangOpts().CPlusPlus &&
13534           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13535            LHSExpr->getType()->isOverloadableType()))
13536         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13537 
13538       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13539     }
13540 
13541     // Don't resolve overloads if the other type is overloadable.
13542     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13543         LHSExpr->getType()->isOverloadableType())
13544       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13545 
13546     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13547     if (!resolvedRHS.isUsable()) return ExprError();
13548     RHSExpr = resolvedRHS.get();
13549   }
13550 
13551   if (getLangOpts().CPlusPlus) {
13552     // If either expression is type-dependent, always build an
13553     // overloaded op.
13554     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13555       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13556 
13557     // Otherwise, build an overloaded op if either expression has an
13558     // overloadable type.
13559     if (LHSExpr->getType()->isOverloadableType() ||
13560         RHSExpr->getType()->isOverloadableType())
13561       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13562   }
13563 
13564   // Build a built-in binary operation.
13565   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13566 }
13567 
13568 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13569   if (T.isNull() || T->isDependentType())
13570     return false;
13571 
13572   if (!T->isPromotableIntegerType())
13573     return true;
13574 
13575   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13576 }
13577 
13578 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13579                                       UnaryOperatorKind Opc,
13580                                       Expr *InputExpr) {
13581   ExprResult Input = InputExpr;
13582   ExprValueKind VK = VK_RValue;
13583   ExprObjectKind OK = OK_Ordinary;
13584   QualType resultType;
13585   bool CanOverflow = false;
13586 
13587   bool ConvertHalfVec = false;
13588   if (getLangOpts().OpenCL) {
13589     QualType Ty = InputExpr->getType();
13590     // The only legal unary operation for atomics is '&'.
13591     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13592     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13593     // only with a builtin functions and therefore should be disallowed here.
13594         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13595         || Ty->isBlockPointerType())) {
13596       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13597                        << InputExpr->getType()
13598                        << Input.get()->getSourceRange());
13599     }
13600   }
13601   // Diagnose operations on the unsupported types for OpenMP device compilation.
13602   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13603     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13604         UnaryOperator::isArithmeticOp(Opc))
13605       checkOpenMPDeviceExpr(InputExpr);
13606   }
13607 
13608   switch (Opc) {
13609   case UO_PreInc:
13610   case UO_PreDec:
13611   case UO_PostInc:
13612   case UO_PostDec:
13613     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13614                                                 OpLoc,
13615                                                 Opc == UO_PreInc ||
13616                                                 Opc == UO_PostInc,
13617                                                 Opc == UO_PreInc ||
13618                                                 Opc == UO_PreDec);
13619     CanOverflow = isOverflowingIntegerType(Context, resultType);
13620     break;
13621   case UO_AddrOf:
13622     resultType = CheckAddressOfOperand(Input, OpLoc);
13623     CheckAddressOfNoDeref(InputExpr);
13624     RecordModifiableNonNullParam(*this, InputExpr);
13625     break;
13626   case UO_Deref: {
13627     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13628     if (Input.isInvalid()) return ExprError();
13629     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13630     break;
13631   }
13632   case UO_Plus:
13633   case UO_Minus:
13634     CanOverflow = Opc == UO_Minus &&
13635                   isOverflowingIntegerType(Context, Input.get()->getType());
13636     Input = UsualUnaryConversions(Input.get());
13637     if (Input.isInvalid()) return ExprError();
13638     // Unary plus and minus require promoting an operand of half vector to a
13639     // float vector and truncating the result back to a half vector. For now, we
13640     // do this only when HalfArgsAndReturns is set (that is, when the target is
13641     // arm or arm64).
13642     ConvertHalfVec =
13643         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13644 
13645     // If the operand is a half vector, promote it to a float vector.
13646     if (ConvertHalfVec)
13647       Input = convertVector(Input.get(), Context.FloatTy, *this);
13648     resultType = Input.get()->getType();
13649     if (resultType->isDependentType())
13650       break;
13651     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13652       break;
13653     else if (resultType->isVectorType() &&
13654              // The z vector extensions don't allow + or - with bool vectors.
13655              (!Context.getLangOpts().ZVector ||
13656               resultType->castAs<VectorType>()->getVectorKind() !=
13657               VectorType::AltiVecBool))
13658       break;
13659     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13660              Opc == UO_Plus &&
13661              resultType->isPointerType())
13662       break;
13663 
13664     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13665       << resultType << Input.get()->getSourceRange());
13666 
13667   case UO_Not: // bitwise complement
13668     Input = UsualUnaryConversions(Input.get());
13669     if (Input.isInvalid())
13670       return ExprError();
13671     resultType = Input.get()->getType();
13672     if (resultType->isDependentType())
13673       break;
13674     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13675     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13676       // C99 does not support '~' for complex conjugation.
13677       Diag(OpLoc, diag::ext_integer_complement_complex)
13678           << resultType << Input.get()->getSourceRange();
13679     else if (resultType->hasIntegerRepresentation())
13680       break;
13681     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13682       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13683       // on vector float types.
13684       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13685       if (!T->isIntegerType())
13686         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13687                           << resultType << Input.get()->getSourceRange());
13688     } else {
13689       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13690                        << resultType << Input.get()->getSourceRange());
13691     }
13692     break;
13693 
13694   case UO_LNot: // logical negation
13695     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13696     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13697     if (Input.isInvalid()) return ExprError();
13698     resultType = Input.get()->getType();
13699 
13700     // Though we still have to promote half FP to float...
13701     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13702       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13703       resultType = Context.FloatTy;
13704     }
13705 
13706     if (resultType->isDependentType())
13707       break;
13708     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13709       // C99 6.5.3.3p1: ok, fallthrough;
13710       if (Context.getLangOpts().CPlusPlus) {
13711         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13712         // operand contextually converted to bool.
13713         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13714                                   ScalarTypeToBooleanCastKind(resultType));
13715       } else if (Context.getLangOpts().OpenCL &&
13716                  Context.getLangOpts().OpenCLVersion < 120) {
13717         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13718         // operate on scalar float types.
13719         if (!resultType->isIntegerType() && !resultType->isPointerType())
13720           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13721                            << resultType << Input.get()->getSourceRange());
13722       }
13723     } else if (resultType->isExtVectorType()) {
13724       if (Context.getLangOpts().OpenCL &&
13725           Context.getLangOpts().OpenCLVersion < 120 &&
13726           !Context.getLangOpts().OpenCLCPlusPlus) {
13727         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13728         // operate on vector float types.
13729         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13730         if (!T->isIntegerType())
13731           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13732                            << resultType << Input.get()->getSourceRange());
13733       }
13734       // Vector logical not returns the signed variant of the operand type.
13735       resultType = GetSignedVectorType(resultType);
13736       break;
13737     } else {
13738       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13739       //        type in C++. We should allow that here too.
13740       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13741         << resultType << Input.get()->getSourceRange());
13742     }
13743 
13744     // LNot always has type int. C99 6.5.3.3p5.
13745     // In C++, it's bool. C++ 5.3.1p8
13746     resultType = Context.getLogicalOperationType();
13747     break;
13748   case UO_Real:
13749   case UO_Imag:
13750     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13751     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13752     // complex l-values to ordinary l-values and all other values to r-values.
13753     if (Input.isInvalid()) return ExprError();
13754     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13755       if (Input.get()->getValueKind() != VK_RValue &&
13756           Input.get()->getObjectKind() == OK_Ordinary)
13757         VK = Input.get()->getValueKind();
13758     } else if (!getLangOpts().CPlusPlus) {
13759       // In C, a volatile scalar is read by __imag. In C++, it is not.
13760       Input = DefaultLvalueConversion(Input.get());
13761     }
13762     break;
13763   case UO_Extension:
13764     resultType = Input.get()->getType();
13765     VK = Input.get()->getValueKind();
13766     OK = Input.get()->getObjectKind();
13767     break;
13768   case UO_Coawait:
13769     // It's unnecessary to represent the pass-through operator co_await in the
13770     // AST; just return the input expression instead.
13771     assert(!Input.get()->getType()->isDependentType() &&
13772                    "the co_await expression must be non-dependant before "
13773                    "building operator co_await");
13774     return Input;
13775   }
13776   if (resultType.isNull() || Input.isInvalid())
13777     return ExprError();
13778 
13779   // Check for array bounds violations in the operand of the UnaryOperator,
13780   // except for the '*' and '&' operators that have to be handled specially
13781   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13782   // that are explicitly defined as valid by the standard).
13783   if (Opc != UO_AddrOf && Opc != UO_Deref)
13784     CheckArrayAccess(Input.get());
13785 
13786   auto *UO = new (Context)
13787       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13788 
13789   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13790       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13791     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13792 
13793   // Convert the result back to a half vector.
13794   if (ConvertHalfVec)
13795     return convertVector(UO, Context.HalfTy, *this);
13796   return UO;
13797 }
13798 
13799 /// Determine whether the given expression is a qualified member
13800 /// access expression, of a form that could be turned into a pointer to member
13801 /// with the address-of operator.
13802 bool Sema::isQualifiedMemberAccess(Expr *E) {
13803   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13804     if (!DRE->getQualifier())
13805       return false;
13806 
13807     ValueDecl *VD = DRE->getDecl();
13808     if (!VD->isCXXClassMember())
13809       return false;
13810 
13811     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13812       return true;
13813     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13814       return Method->isInstance();
13815 
13816     return false;
13817   }
13818 
13819   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13820     if (!ULE->getQualifier())
13821       return false;
13822 
13823     for (NamedDecl *D : ULE->decls()) {
13824       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13825         if (Method->isInstance())
13826           return true;
13827       } else {
13828         // Overload set does not contain methods.
13829         break;
13830       }
13831     }
13832 
13833     return false;
13834   }
13835 
13836   return false;
13837 }
13838 
13839 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13840                               UnaryOperatorKind Opc, Expr *Input) {
13841   // First things first: handle placeholders so that the
13842   // overloaded-operator check considers the right type.
13843   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13844     // Increment and decrement of pseudo-object references.
13845     if (pty->getKind() == BuiltinType::PseudoObject &&
13846         UnaryOperator::isIncrementDecrementOp(Opc))
13847       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13848 
13849     // extension is always a builtin operator.
13850     if (Opc == UO_Extension)
13851       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13852 
13853     // & gets special logic for several kinds of placeholder.
13854     // The builtin code knows what to do.
13855     if (Opc == UO_AddrOf &&
13856         (pty->getKind() == BuiltinType::Overload ||
13857          pty->getKind() == BuiltinType::UnknownAny ||
13858          pty->getKind() == BuiltinType::BoundMember))
13859       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13860 
13861     // Anything else needs to be handled now.
13862     ExprResult Result = CheckPlaceholderExpr(Input);
13863     if (Result.isInvalid()) return ExprError();
13864     Input = Result.get();
13865   }
13866 
13867   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13868       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13869       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13870     // Find all of the overloaded operators visible from this
13871     // point. We perform both an operator-name lookup from the local
13872     // scope and an argument-dependent lookup based on the types of
13873     // the arguments.
13874     UnresolvedSet<16> Functions;
13875     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13876     if (S && OverOp != OO_None)
13877       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13878                                    Functions);
13879 
13880     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13881   }
13882 
13883   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13884 }
13885 
13886 // Unary Operators.  'Tok' is the token for the operator.
13887 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13888                               tok::TokenKind Op, Expr *Input) {
13889   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13890 }
13891 
13892 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13893 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13894                                 LabelDecl *TheDecl) {
13895   TheDecl->markUsed(Context);
13896   // Create the AST node.  The address of a label always has type 'void*'.
13897   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13898                                      Context.getPointerType(Context.VoidTy));
13899 }
13900 
13901 void Sema::ActOnStartStmtExpr() {
13902   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13903 }
13904 
13905 void Sema::ActOnStmtExprError() {
13906   // Note that function is also called by TreeTransform when leaving a
13907   // StmtExpr scope without rebuilding anything.
13908 
13909   DiscardCleanupsInEvaluationContext();
13910   PopExpressionEvaluationContext();
13911 }
13912 
13913 ExprResult
13914 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13915                     SourceLocation RPLoc) { // "({..})"
13916   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13917   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13918 
13919   if (hasAnyUnrecoverableErrorsInThisFunction())
13920     DiscardCleanupsInEvaluationContext();
13921   assert(!Cleanup.exprNeedsCleanups() &&
13922          "cleanups within StmtExpr not correctly bound!");
13923   PopExpressionEvaluationContext();
13924 
13925   // FIXME: there are a variety of strange constraints to enforce here, for
13926   // example, it is not possible to goto into a stmt expression apparently.
13927   // More semantic analysis is needed.
13928 
13929   // If there are sub-stmts in the compound stmt, take the type of the last one
13930   // as the type of the stmtexpr.
13931   QualType Ty = Context.VoidTy;
13932   bool StmtExprMayBindToTemp = false;
13933   if (!Compound->body_empty()) {
13934     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13935     if (const auto *LastStmt =
13936             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13937       if (const Expr *Value = LastStmt->getExprStmt()) {
13938         StmtExprMayBindToTemp = true;
13939         Ty = Value->getType();
13940       }
13941     }
13942   }
13943 
13944   // FIXME: Check that expression type is complete/non-abstract; statement
13945   // expressions are not lvalues.
13946   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13947   if (StmtExprMayBindToTemp)
13948     return MaybeBindToTemporary(ResStmtExpr);
13949   return ResStmtExpr;
13950 }
13951 
13952 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13953   if (ER.isInvalid())
13954     return ExprError();
13955 
13956   // Do function/array conversion on the last expression, but not
13957   // lvalue-to-rvalue.  However, initialize an unqualified type.
13958   ER = DefaultFunctionArrayConversion(ER.get());
13959   if (ER.isInvalid())
13960     return ExprError();
13961   Expr *E = ER.get();
13962 
13963   if (E->isTypeDependent())
13964     return E;
13965 
13966   // In ARC, if the final expression ends in a consume, splice
13967   // the consume out and bind it later.  In the alternate case
13968   // (when dealing with a retainable type), the result
13969   // initialization will create a produce.  In both cases the
13970   // result will be +1, and we'll need to balance that out with
13971   // a bind.
13972   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13973   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13974     return Cast->getSubExpr();
13975 
13976   // FIXME: Provide a better location for the initialization.
13977   return PerformCopyInitialization(
13978       InitializedEntity::InitializeStmtExprResult(
13979           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13980       SourceLocation(), E);
13981 }
13982 
13983 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13984                                       TypeSourceInfo *TInfo,
13985                                       ArrayRef<OffsetOfComponent> Components,
13986                                       SourceLocation RParenLoc) {
13987   QualType ArgTy = TInfo->getType();
13988   bool Dependent = ArgTy->isDependentType();
13989   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13990 
13991   // We must have at least one component that refers to the type, and the first
13992   // one is known to be a field designator.  Verify that the ArgTy represents
13993   // a struct/union/class.
13994   if (!Dependent && !ArgTy->isRecordType())
13995     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13996                        << ArgTy << TypeRange);
13997 
13998   // Type must be complete per C99 7.17p3 because a declaring a variable
13999   // with an incomplete type would be ill-formed.
14000   if (!Dependent
14001       && RequireCompleteType(BuiltinLoc, ArgTy,
14002                              diag::err_offsetof_incomplete_type, TypeRange))
14003     return ExprError();
14004 
14005   bool DidWarnAboutNonPOD = false;
14006   QualType CurrentType = ArgTy;
14007   SmallVector<OffsetOfNode, 4> Comps;
14008   SmallVector<Expr*, 4> Exprs;
14009   for (const OffsetOfComponent &OC : Components) {
14010     if (OC.isBrackets) {
14011       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14012       if (!CurrentType->isDependentType()) {
14013         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14014         if(!AT)
14015           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14016                            << CurrentType);
14017         CurrentType = AT->getElementType();
14018       } else
14019         CurrentType = Context.DependentTy;
14020 
14021       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14022       if (IdxRval.isInvalid())
14023         return ExprError();
14024       Expr *Idx = IdxRval.get();
14025 
14026       // The expression must be an integral expression.
14027       // FIXME: An integral constant expression?
14028       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14029           !Idx->getType()->isIntegerType())
14030         return ExprError(
14031             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14032             << Idx->getSourceRange());
14033 
14034       // Record this array index.
14035       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14036       Exprs.push_back(Idx);
14037       continue;
14038     }
14039 
14040     // Offset of a field.
14041     if (CurrentType->isDependentType()) {
14042       // We have the offset of a field, but we can't look into the dependent
14043       // type. Just record the identifier of the field.
14044       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14045       CurrentType = Context.DependentTy;
14046       continue;
14047     }
14048 
14049     // We need to have a complete type to look into.
14050     if (RequireCompleteType(OC.LocStart, CurrentType,
14051                             diag::err_offsetof_incomplete_type))
14052       return ExprError();
14053 
14054     // Look for the designated field.
14055     const RecordType *RC = CurrentType->getAs<RecordType>();
14056     if (!RC)
14057       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14058                        << CurrentType);
14059     RecordDecl *RD = RC->getDecl();
14060 
14061     // C++ [lib.support.types]p5:
14062     //   The macro offsetof accepts a restricted set of type arguments in this
14063     //   International Standard. type shall be a POD structure or a POD union
14064     //   (clause 9).
14065     // C++11 [support.types]p4:
14066     //   If type is not a standard-layout class (Clause 9), the results are
14067     //   undefined.
14068     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14069       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14070       unsigned DiagID =
14071         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14072                             : diag::ext_offsetof_non_pod_type;
14073 
14074       if (!IsSafe && !DidWarnAboutNonPOD &&
14075           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14076                               PDiag(DiagID)
14077                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14078                               << CurrentType))
14079         DidWarnAboutNonPOD = true;
14080     }
14081 
14082     // Look for the field.
14083     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14084     LookupQualifiedName(R, RD);
14085     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14086     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14087     if (!MemberDecl) {
14088       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14089         MemberDecl = IndirectMemberDecl->getAnonField();
14090     }
14091 
14092     if (!MemberDecl)
14093       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14094                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14095                                                               OC.LocEnd));
14096 
14097     // C99 7.17p3:
14098     //   (If the specified member is a bit-field, the behavior is undefined.)
14099     //
14100     // We diagnose this as an error.
14101     if (MemberDecl->isBitField()) {
14102       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14103         << MemberDecl->getDeclName()
14104         << SourceRange(BuiltinLoc, RParenLoc);
14105       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14106       return ExprError();
14107     }
14108 
14109     RecordDecl *Parent = MemberDecl->getParent();
14110     if (IndirectMemberDecl)
14111       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14112 
14113     // If the member was found in a base class, introduce OffsetOfNodes for
14114     // the base class indirections.
14115     CXXBasePaths Paths;
14116     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14117                       Paths)) {
14118       if (Paths.getDetectedVirtual()) {
14119         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14120           << MemberDecl->getDeclName()
14121           << SourceRange(BuiltinLoc, RParenLoc);
14122         return ExprError();
14123       }
14124 
14125       CXXBasePath &Path = Paths.front();
14126       for (const CXXBasePathElement &B : Path)
14127         Comps.push_back(OffsetOfNode(B.Base));
14128     }
14129 
14130     if (IndirectMemberDecl) {
14131       for (auto *FI : IndirectMemberDecl->chain()) {
14132         assert(isa<FieldDecl>(FI));
14133         Comps.push_back(OffsetOfNode(OC.LocStart,
14134                                      cast<FieldDecl>(FI), OC.LocEnd));
14135       }
14136     } else
14137       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14138 
14139     CurrentType = MemberDecl->getType().getNonReferenceType();
14140   }
14141 
14142   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14143                               Comps, Exprs, RParenLoc);
14144 }
14145 
14146 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14147                                       SourceLocation BuiltinLoc,
14148                                       SourceLocation TypeLoc,
14149                                       ParsedType ParsedArgTy,
14150                                       ArrayRef<OffsetOfComponent> Components,
14151                                       SourceLocation RParenLoc) {
14152 
14153   TypeSourceInfo *ArgTInfo;
14154   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14155   if (ArgTy.isNull())
14156     return ExprError();
14157 
14158   if (!ArgTInfo)
14159     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14160 
14161   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14162 }
14163 
14164 
14165 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14166                                  Expr *CondExpr,
14167                                  Expr *LHSExpr, Expr *RHSExpr,
14168                                  SourceLocation RPLoc) {
14169   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14170 
14171   ExprValueKind VK = VK_RValue;
14172   ExprObjectKind OK = OK_Ordinary;
14173   QualType resType;
14174   bool ValueDependent = false;
14175   bool CondIsTrue = false;
14176   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14177     resType = Context.DependentTy;
14178     ValueDependent = true;
14179   } else {
14180     // The conditional expression is required to be a constant expression.
14181     llvm::APSInt condEval(32);
14182     ExprResult CondICE
14183       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14184           diag::err_typecheck_choose_expr_requires_constant, false);
14185     if (CondICE.isInvalid())
14186       return ExprError();
14187     CondExpr = CondICE.get();
14188     CondIsTrue = condEval.getZExtValue();
14189 
14190     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14191     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14192 
14193     resType = ActiveExpr->getType();
14194     ValueDependent = ActiveExpr->isValueDependent();
14195     VK = ActiveExpr->getValueKind();
14196     OK = ActiveExpr->getObjectKind();
14197   }
14198 
14199   return new (Context)
14200       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14201                  CondIsTrue, resType->isDependentType(), ValueDependent);
14202 }
14203 
14204 //===----------------------------------------------------------------------===//
14205 // Clang Extensions.
14206 //===----------------------------------------------------------------------===//
14207 
14208 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14209 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14210   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14211 
14212   if (LangOpts.CPlusPlus) {
14213     MangleNumberingContext *MCtx;
14214     Decl *ManglingContextDecl;
14215     std::tie(MCtx, ManglingContextDecl) =
14216         getCurrentMangleNumberContext(Block->getDeclContext());
14217     if (MCtx) {
14218       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14219       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14220     }
14221   }
14222 
14223   PushBlockScope(CurScope, Block);
14224   CurContext->addDecl(Block);
14225   if (CurScope)
14226     PushDeclContext(CurScope, Block);
14227   else
14228     CurContext = Block;
14229 
14230   getCurBlock()->HasImplicitReturnType = true;
14231 
14232   // Enter a new evaluation context to insulate the block from any
14233   // cleanups from the enclosing full-expression.
14234   PushExpressionEvaluationContext(
14235       ExpressionEvaluationContext::PotentiallyEvaluated);
14236 }
14237 
14238 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14239                                Scope *CurScope) {
14240   assert(ParamInfo.getIdentifier() == nullptr &&
14241          "block-id should have no identifier!");
14242   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14243   BlockScopeInfo *CurBlock = getCurBlock();
14244 
14245   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14246   QualType T = Sig->getType();
14247 
14248   // FIXME: We should allow unexpanded parameter packs here, but that would,
14249   // in turn, make the block expression contain unexpanded parameter packs.
14250   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14251     // Drop the parameters.
14252     FunctionProtoType::ExtProtoInfo EPI;
14253     EPI.HasTrailingReturn = false;
14254     EPI.TypeQuals.addConst();
14255     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14256     Sig = Context.getTrivialTypeSourceInfo(T);
14257   }
14258 
14259   // GetTypeForDeclarator always produces a function type for a block
14260   // literal signature.  Furthermore, it is always a FunctionProtoType
14261   // unless the function was written with a typedef.
14262   assert(T->isFunctionType() &&
14263          "GetTypeForDeclarator made a non-function block signature");
14264 
14265   // Look for an explicit signature in that function type.
14266   FunctionProtoTypeLoc ExplicitSignature;
14267 
14268   if ((ExplicitSignature = Sig->getTypeLoc()
14269                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14270 
14271     // Check whether that explicit signature was synthesized by
14272     // GetTypeForDeclarator.  If so, don't save that as part of the
14273     // written signature.
14274     if (ExplicitSignature.getLocalRangeBegin() ==
14275         ExplicitSignature.getLocalRangeEnd()) {
14276       // This would be much cheaper if we stored TypeLocs instead of
14277       // TypeSourceInfos.
14278       TypeLoc Result = ExplicitSignature.getReturnLoc();
14279       unsigned Size = Result.getFullDataSize();
14280       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14281       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14282 
14283       ExplicitSignature = FunctionProtoTypeLoc();
14284     }
14285   }
14286 
14287   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14288   CurBlock->FunctionType = T;
14289 
14290   const FunctionType *Fn = T->getAs<FunctionType>();
14291   QualType RetTy = Fn->getReturnType();
14292   bool isVariadic =
14293     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14294 
14295   CurBlock->TheDecl->setIsVariadic(isVariadic);
14296 
14297   // Context.DependentTy is used as a placeholder for a missing block
14298   // return type.  TODO:  what should we do with declarators like:
14299   //   ^ * { ... }
14300   // If the answer is "apply template argument deduction"....
14301   if (RetTy != Context.DependentTy) {
14302     CurBlock->ReturnType = RetTy;
14303     CurBlock->TheDecl->setBlockMissingReturnType(false);
14304     CurBlock->HasImplicitReturnType = false;
14305   }
14306 
14307   // Push block parameters from the declarator if we had them.
14308   SmallVector<ParmVarDecl*, 8> Params;
14309   if (ExplicitSignature) {
14310     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14311       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14312       if (Param->getIdentifier() == nullptr &&
14313           !Param->isImplicit() &&
14314           !Param->isInvalidDecl() &&
14315           !getLangOpts().CPlusPlus)
14316         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14317       Params.push_back(Param);
14318     }
14319 
14320   // Fake up parameter variables if we have a typedef, like
14321   //   ^ fntype { ... }
14322   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14323     for (const auto &I : Fn->param_types()) {
14324       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14325           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14326       Params.push_back(Param);
14327     }
14328   }
14329 
14330   // Set the parameters on the block decl.
14331   if (!Params.empty()) {
14332     CurBlock->TheDecl->setParams(Params);
14333     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14334                              /*CheckParameterNames=*/false);
14335   }
14336 
14337   // Finally we can process decl attributes.
14338   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14339 
14340   // Put the parameter variables in scope.
14341   for (auto AI : CurBlock->TheDecl->parameters()) {
14342     AI->setOwningFunction(CurBlock->TheDecl);
14343 
14344     // If this has an identifier, add it to the scope stack.
14345     if (AI->getIdentifier()) {
14346       CheckShadow(CurBlock->TheScope, AI);
14347 
14348       PushOnScopeChains(AI, CurBlock->TheScope);
14349     }
14350   }
14351 }
14352 
14353 /// ActOnBlockError - If there is an error parsing a block, this callback
14354 /// is invoked to pop the information about the block from the action impl.
14355 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14356   // Leave the expression-evaluation context.
14357   DiscardCleanupsInEvaluationContext();
14358   PopExpressionEvaluationContext();
14359 
14360   // Pop off CurBlock, handle nested blocks.
14361   PopDeclContext();
14362   PopFunctionScopeInfo();
14363 }
14364 
14365 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14366 /// literal was successfully completed.  ^(int x){...}
14367 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14368                                     Stmt *Body, Scope *CurScope) {
14369   // If blocks are disabled, emit an error.
14370   if (!LangOpts.Blocks)
14371     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14372 
14373   // Leave the expression-evaluation context.
14374   if (hasAnyUnrecoverableErrorsInThisFunction())
14375     DiscardCleanupsInEvaluationContext();
14376   assert(!Cleanup.exprNeedsCleanups() &&
14377          "cleanups within block not correctly bound!");
14378   PopExpressionEvaluationContext();
14379 
14380   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14381   BlockDecl *BD = BSI->TheDecl;
14382 
14383   if (BSI->HasImplicitReturnType)
14384     deduceClosureReturnType(*BSI);
14385 
14386   QualType RetTy = Context.VoidTy;
14387   if (!BSI->ReturnType.isNull())
14388     RetTy = BSI->ReturnType;
14389 
14390   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14391   QualType BlockTy;
14392 
14393   // If the user wrote a function type in some form, try to use that.
14394   if (!BSI->FunctionType.isNull()) {
14395     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14396 
14397     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14398     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14399 
14400     // Turn protoless block types into nullary block types.
14401     if (isa<FunctionNoProtoType>(FTy)) {
14402       FunctionProtoType::ExtProtoInfo EPI;
14403       EPI.ExtInfo = Ext;
14404       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14405 
14406     // Otherwise, if we don't need to change anything about the function type,
14407     // preserve its sugar structure.
14408     } else if (FTy->getReturnType() == RetTy &&
14409                (!NoReturn || FTy->getNoReturnAttr())) {
14410       BlockTy = BSI->FunctionType;
14411 
14412     // Otherwise, make the minimal modifications to the function type.
14413     } else {
14414       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14415       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14416       EPI.TypeQuals = Qualifiers();
14417       EPI.ExtInfo = Ext;
14418       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14419     }
14420 
14421   // If we don't have a function type, just build one from nothing.
14422   } else {
14423     FunctionProtoType::ExtProtoInfo EPI;
14424     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14425     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14426   }
14427 
14428   DiagnoseUnusedParameters(BD->parameters());
14429   BlockTy = Context.getBlockPointerType(BlockTy);
14430 
14431   // If needed, diagnose invalid gotos and switches in the block.
14432   if (getCurFunction()->NeedsScopeChecking() &&
14433       !PP.isCodeCompletionEnabled())
14434     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14435 
14436   BD->setBody(cast<CompoundStmt>(Body));
14437 
14438   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14439     DiagnoseUnguardedAvailabilityViolations(BD);
14440 
14441   // Try to apply the named return value optimization. We have to check again
14442   // if we can do this, though, because blocks keep return statements around
14443   // to deduce an implicit return type.
14444   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14445       !BD->isDependentContext())
14446     computeNRVO(Body, BSI);
14447 
14448   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14449       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14450     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14451                           NTCUK_Destruct|NTCUK_Copy);
14452 
14453   PopDeclContext();
14454 
14455   // Pop the block scope now but keep it alive to the end of this function.
14456   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14457   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14458 
14459   // Set the captured variables on the block.
14460   SmallVector<BlockDecl::Capture, 4> Captures;
14461   for (Capture &Cap : BSI->Captures) {
14462     if (Cap.isInvalid() || Cap.isThisCapture())
14463       continue;
14464 
14465     VarDecl *Var = Cap.getVariable();
14466     Expr *CopyExpr = nullptr;
14467     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14468       if (const RecordType *Record =
14469               Cap.getCaptureType()->getAs<RecordType>()) {
14470         // The capture logic needs the destructor, so make sure we mark it.
14471         // Usually this is unnecessary because most local variables have
14472         // their destructors marked at declaration time, but parameters are
14473         // an exception because it's technically only the call site that
14474         // actually requires the destructor.
14475         if (isa<ParmVarDecl>(Var))
14476           FinalizeVarWithDestructor(Var, Record);
14477 
14478         // Enter a separate potentially-evaluated context while building block
14479         // initializers to isolate their cleanups from those of the block
14480         // itself.
14481         // FIXME: Is this appropriate even when the block itself occurs in an
14482         // unevaluated operand?
14483         EnterExpressionEvaluationContext EvalContext(
14484             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14485 
14486         SourceLocation Loc = Cap.getLocation();
14487 
14488         ExprResult Result = BuildDeclarationNameExpr(
14489             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14490 
14491         // According to the blocks spec, the capture of a variable from
14492         // the stack requires a const copy constructor.  This is not true
14493         // of the copy/move done to move a __block variable to the heap.
14494         if (!Result.isInvalid() &&
14495             !Result.get()->getType().isConstQualified()) {
14496           Result = ImpCastExprToType(Result.get(),
14497                                      Result.get()->getType().withConst(),
14498                                      CK_NoOp, VK_LValue);
14499         }
14500 
14501         if (!Result.isInvalid()) {
14502           Result = PerformCopyInitialization(
14503               InitializedEntity::InitializeBlock(Var->getLocation(),
14504                                                  Cap.getCaptureType(), false),
14505               Loc, Result.get());
14506         }
14507 
14508         // Build a full-expression copy expression if initialization
14509         // succeeded and used a non-trivial constructor.  Recover from
14510         // errors by pretending that the copy isn't necessary.
14511         if (!Result.isInvalid() &&
14512             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14513                 ->isTrivial()) {
14514           Result = MaybeCreateExprWithCleanups(Result);
14515           CopyExpr = Result.get();
14516         }
14517       }
14518     }
14519 
14520     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14521                               CopyExpr);
14522     Captures.push_back(NewCap);
14523   }
14524   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14525 
14526   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14527 
14528   // If the block isn't obviously global, i.e. it captures anything at
14529   // all, then we need to do a few things in the surrounding context:
14530   if (Result->getBlockDecl()->hasCaptures()) {
14531     // First, this expression has a new cleanup object.
14532     ExprCleanupObjects.push_back(Result->getBlockDecl());
14533     Cleanup.setExprNeedsCleanups(true);
14534 
14535     // It also gets a branch-protected scope if any of the captured
14536     // variables needs destruction.
14537     for (const auto &CI : Result->getBlockDecl()->captures()) {
14538       const VarDecl *var = CI.getVariable();
14539       if (var->getType().isDestructedType() != QualType::DK_none) {
14540         setFunctionHasBranchProtectedScope();
14541         break;
14542       }
14543     }
14544   }
14545 
14546   if (getCurFunction())
14547     getCurFunction()->addBlock(BD);
14548 
14549   return Result;
14550 }
14551 
14552 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14553                             SourceLocation RPLoc) {
14554   TypeSourceInfo *TInfo;
14555   GetTypeFromParser(Ty, &TInfo);
14556   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14557 }
14558 
14559 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14560                                 Expr *E, TypeSourceInfo *TInfo,
14561                                 SourceLocation RPLoc) {
14562   Expr *OrigExpr = E;
14563   bool IsMS = false;
14564 
14565   // CUDA device code does not support varargs.
14566   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14567     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14568       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14569       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14570         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14571     }
14572   }
14573 
14574   // NVPTX does not support va_arg expression.
14575   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14576       Context.getTargetInfo().getTriple().isNVPTX())
14577     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14578 
14579   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14580   // as Microsoft ABI on an actual Microsoft platform, where
14581   // __builtin_ms_va_list and __builtin_va_list are the same.)
14582   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14583       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14584     QualType MSVaListType = Context.getBuiltinMSVaListType();
14585     if (Context.hasSameType(MSVaListType, E->getType())) {
14586       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14587         return ExprError();
14588       IsMS = true;
14589     }
14590   }
14591 
14592   // Get the va_list type
14593   QualType VaListType = Context.getBuiltinVaListType();
14594   if (!IsMS) {
14595     if (VaListType->isArrayType()) {
14596       // Deal with implicit array decay; for example, on x86-64,
14597       // va_list is an array, but it's supposed to decay to
14598       // a pointer for va_arg.
14599       VaListType = Context.getArrayDecayedType(VaListType);
14600       // Make sure the input expression also decays appropriately.
14601       ExprResult Result = UsualUnaryConversions(E);
14602       if (Result.isInvalid())
14603         return ExprError();
14604       E = Result.get();
14605     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14606       // If va_list is a record type and we are compiling in C++ mode,
14607       // check the argument using reference binding.
14608       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14609           Context, Context.getLValueReferenceType(VaListType), false);
14610       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14611       if (Init.isInvalid())
14612         return ExprError();
14613       E = Init.getAs<Expr>();
14614     } else {
14615       // Otherwise, the va_list argument must be an l-value because
14616       // it is modified by va_arg.
14617       if (!E->isTypeDependent() &&
14618           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14619         return ExprError();
14620     }
14621   }
14622 
14623   if (!IsMS && !E->isTypeDependent() &&
14624       !Context.hasSameType(VaListType, E->getType()))
14625     return ExprError(
14626         Diag(E->getBeginLoc(),
14627              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14628         << OrigExpr->getType() << E->getSourceRange());
14629 
14630   if (!TInfo->getType()->isDependentType()) {
14631     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14632                             diag::err_second_parameter_to_va_arg_incomplete,
14633                             TInfo->getTypeLoc()))
14634       return ExprError();
14635 
14636     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14637                                TInfo->getType(),
14638                                diag::err_second_parameter_to_va_arg_abstract,
14639                                TInfo->getTypeLoc()))
14640       return ExprError();
14641 
14642     if (!TInfo->getType().isPODType(Context)) {
14643       Diag(TInfo->getTypeLoc().getBeginLoc(),
14644            TInfo->getType()->isObjCLifetimeType()
14645              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14646              : diag::warn_second_parameter_to_va_arg_not_pod)
14647         << TInfo->getType()
14648         << TInfo->getTypeLoc().getSourceRange();
14649     }
14650 
14651     // Check for va_arg where arguments of the given type will be promoted
14652     // (i.e. this va_arg is guaranteed to have undefined behavior).
14653     QualType PromoteType;
14654     if (TInfo->getType()->isPromotableIntegerType()) {
14655       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14656       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14657         PromoteType = QualType();
14658     }
14659     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14660       PromoteType = Context.DoubleTy;
14661     if (!PromoteType.isNull())
14662       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14663                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14664                           << TInfo->getType()
14665                           << PromoteType
14666                           << TInfo->getTypeLoc().getSourceRange());
14667   }
14668 
14669   QualType T = TInfo->getType().getNonLValueExprType(Context);
14670   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14671 }
14672 
14673 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14674   // The type of __null will be int or long, depending on the size of
14675   // pointers on the target.
14676   QualType Ty;
14677   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14678   if (pw == Context.getTargetInfo().getIntWidth())
14679     Ty = Context.IntTy;
14680   else if (pw == Context.getTargetInfo().getLongWidth())
14681     Ty = Context.LongTy;
14682   else if (pw == Context.getTargetInfo().getLongLongWidth())
14683     Ty = Context.LongLongTy;
14684   else {
14685     llvm_unreachable("I don't know size of pointer!");
14686   }
14687 
14688   return new (Context) GNUNullExpr(Ty, TokenLoc);
14689 }
14690 
14691 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14692                                     SourceLocation BuiltinLoc,
14693                                     SourceLocation RPLoc) {
14694   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14695 }
14696 
14697 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14698                                     SourceLocation BuiltinLoc,
14699                                     SourceLocation RPLoc,
14700                                     DeclContext *ParentContext) {
14701   return new (Context)
14702       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14703 }
14704 
14705 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14706                                               bool Diagnose) {
14707   if (!getLangOpts().ObjC)
14708     return false;
14709 
14710   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14711   if (!PT)
14712     return false;
14713 
14714   if (!PT->isObjCIdType()) {
14715     // Check if the destination is the 'NSString' interface.
14716     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14717     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14718       return false;
14719   }
14720 
14721   // Ignore any parens, implicit casts (should only be
14722   // array-to-pointer decays), and not-so-opaque values.  The last is
14723   // important for making this trigger for property assignments.
14724   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14725   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14726     if (OV->getSourceExpr())
14727       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14728 
14729   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14730   if (!SL || !SL->isAscii())
14731     return false;
14732   if (Diagnose) {
14733     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14734         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14735     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14736   }
14737   return true;
14738 }
14739 
14740 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14741                                               const Expr *SrcExpr) {
14742   if (!DstType->isFunctionPointerType() ||
14743       !SrcExpr->getType()->isFunctionType())
14744     return false;
14745 
14746   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14747   if (!DRE)
14748     return false;
14749 
14750   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14751   if (!FD)
14752     return false;
14753 
14754   return !S.checkAddressOfFunctionIsAvailable(FD,
14755                                               /*Complain=*/true,
14756                                               SrcExpr->getBeginLoc());
14757 }
14758 
14759 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14760                                     SourceLocation Loc,
14761                                     QualType DstType, QualType SrcType,
14762                                     Expr *SrcExpr, AssignmentAction Action,
14763                                     bool *Complained) {
14764   if (Complained)
14765     *Complained = false;
14766 
14767   // Decode the result (notice that AST's are still created for extensions).
14768   bool CheckInferredResultType = false;
14769   bool isInvalid = false;
14770   unsigned DiagKind = 0;
14771   FixItHint Hint;
14772   ConversionFixItGenerator ConvHints;
14773   bool MayHaveConvFixit = false;
14774   bool MayHaveFunctionDiff = false;
14775   const ObjCInterfaceDecl *IFace = nullptr;
14776   const ObjCProtocolDecl *PDecl = nullptr;
14777 
14778   switch (ConvTy) {
14779   case Compatible:
14780       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14781       return false;
14782 
14783   case PointerToInt:
14784     DiagKind = diag::ext_typecheck_convert_pointer_int;
14785     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14786     MayHaveConvFixit = true;
14787     break;
14788   case IntToPointer:
14789     DiagKind = diag::ext_typecheck_convert_int_pointer;
14790     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14791     MayHaveConvFixit = true;
14792     break;
14793   case IncompatiblePointer:
14794     if (Action == AA_Passing_CFAudited)
14795       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14796     else if (SrcType->isFunctionPointerType() &&
14797              DstType->isFunctionPointerType())
14798       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14799     else
14800       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14801 
14802     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14803       SrcType->isObjCObjectPointerType();
14804     if (Hint.isNull() && !CheckInferredResultType) {
14805       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14806     }
14807     else if (CheckInferredResultType) {
14808       SrcType = SrcType.getUnqualifiedType();
14809       DstType = DstType.getUnqualifiedType();
14810     }
14811     MayHaveConvFixit = true;
14812     break;
14813   case IncompatiblePointerSign:
14814     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14815     break;
14816   case FunctionVoidPointer:
14817     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14818     break;
14819   case IncompatiblePointerDiscardsQualifiers: {
14820     // Perform array-to-pointer decay if necessary.
14821     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14822 
14823     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14824     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14825     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14826       DiagKind = diag::err_typecheck_incompatible_address_space;
14827       break;
14828 
14829     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14830       DiagKind = diag::err_typecheck_incompatible_ownership;
14831       break;
14832     }
14833 
14834     llvm_unreachable("unknown error case for discarding qualifiers!");
14835     // fallthrough
14836   }
14837   case CompatiblePointerDiscardsQualifiers:
14838     // If the qualifiers lost were because we were applying the
14839     // (deprecated) C++ conversion from a string literal to a char*
14840     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14841     // Ideally, this check would be performed in
14842     // checkPointerTypesForAssignment. However, that would require a
14843     // bit of refactoring (so that the second argument is an
14844     // expression, rather than a type), which should be done as part
14845     // of a larger effort to fix checkPointerTypesForAssignment for
14846     // C++ semantics.
14847     if (getLangOpts().CPlusPlus &&
14848         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14849       return false;
14850     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14851     break;
14852   case IncompatibleNestedPointerQualifiers:
14853     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14854     break;
14855   case IncompatibleNestedPointerAddressSpaceMismatch:
14856     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14857     break;
14858   case IntToBlockPointer:
14859     DiagKind = diag::err_int_to_block_pointer;
14860     break;
14861   case IncompatibleBlockPointer:
14862     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14863     break;
14864   case IncompatibleObjCQualifiedId: {
14865     if (SrcType->isObjCQualifiedIdType()) {
14866       const ObjCObjectPointerType *srcOPT =
14867                 SrcType->castAs<ObjCObjectPointerType>();
14868       for (auto *srcProto : srcOPT->quals()) {
14869         PDecl = srcProto;
14870         break;
14871       }
14872       if (const ObjCInterfaceType *IFaceT =
14873             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14874         IFace = IFaceT->getDecl();
14875     }
14876     else if (DstType->isObjCQualifiedIdType()) {
14877       const ObjCObjectPointerType *dstOPT =
14878         DstType->castAs<ObjCObjectPointerType>();
14879       for (auto *dstProto : dstOPT->quals()) {
14880         PDecl = dstProto;
14881         break;
14882       }
14883       if (const ObjCInterfaceType *IFaceT =
14884             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14885         IFace = IFaceT->getDecl();
14886     }
14887     DiagKind = diag::warn_incompatible_qualified_id;
14888     break;
14889   }
14890   case IncompatibleVectors:
14891     DiagKind = diag::warn_incompatible_vectors;
14892     break;
14893   case IncompatibleObjCWeakRef:
14894     DiagKind = diag::err_arc_weak_unavailable_assign;
14895     break;
14896   case Incompatible:
14897     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14898       if (Complained)
14899         *Complained = true;
14900       return true;
14901     }
14902 
14903     DiagKind = diag::err_typecheck_convert_incompatible;
14904     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14905     MayHaveConvFixit = true;
14906     isInvalid = true;
14907     MayHaveFunctionDiff = true;
14908     break;
14909   }
14910 
14911   QualType FirstType, SecondType;
14912   switch (Action) {
14913   case AA_Assigning:
14914   case AA_Initializing:
14915     // The destination type comes first.
14916     FirstType = DstType;
14917     SecondType = SrcType;
14918     break;
14919 
14920   case AA_Returning:
14921   case AA_Passing:
14922   case AA_Passing_CFAudited:
14923   case AA_Converting:
14924   case AA_Sending:
14925   case AA_Casting:
14926     // The source type comes first.
14927     FirstType = SrcType;
14928     SecondType = DstType;
14929     break;
14930   }
14931 
14932   PartialDiagnostic FDiag = PDiag(DiagKind);
14933   if (Action == AA_Passing_CFAudited)
14934     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14935   else
14936     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14937 
14938   // If we can fix the conversion, suggest the FixIts.
14939   assert(ConvHints.isNull() || Hint.isNull());
14940   if (!ConvHints.isNull()) {
14941     for (FixItHint &H : ConvHints.Hints)
14942       FDiag << H;
14943   } else {
14944     FDiag << Hint;
14945   }
14946   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14947 
14948   if (MayHaveFunctionDiff)
14949     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14950 
14951   Diag(Loc, FDiag);
14952   if (DiagKind == diag::warn_incompatible_qualified_id &&
14953       PDecl && IFace && !IFace->hasDefinition())
14954       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14955         << IFace << PDecl;
14956 
14957   if (SecondType == Context.OverloadTy)
14958     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14959                               FirstType, /*TakingAddress=*/true);
14960 
14961   if (CheckInferredResultType)
14962     EmitRelatedResultTypeNote(SrcExpr);
14963 
14964   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14965     EmitRelatedResultTypeNoteForReturn(DstType);
14966 
14967   if (Complained)
14968     *Complained = true;
14969   return isInvalid;
14970 }
14971 
14972 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14973                                                  llvm::APSInt *Result) {
14974   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14975   public:
14976     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14977       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14978     }
14979   } Diagnoser;
14980 
14981   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14982 }
14983 
14984 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14985                                                  llvm::APSInt *Result,
14986                                                  unsigned DiagID,
14987                                                  bool AllowFold) {
14988   class IDDiagnoser : public VerifyICEDiagnoser {
14989     unsigned DiagID;
14990 
14991   public:
14992     IDDiagnoser(unsigned DiagID)
14993       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14994 
14995     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14996       S.Diag(Loc, DiagID) << SR;
14997     }
14998   } Diagnoser(DiagID);
14999 
15000   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15001 }
15002 
15003 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15004                                             SourceRange SR) {
15005   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15006 }
15007 
15008 ExprResult
15009 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15010                                       VerifyICEDiagnoser &Diagnoser,
15011                                       bool AllowFold) {
15012   SourceLocation DiagLoc = E->getBeginLoc();
15013 
15014   if (getLangOpts().CPlusPlus11) {
15015     // C++11 [expr.const]p5:
15016     //   If an expression of literal class type is used in a context where an
15017     //   integral constant expression is required, then that class type shall
15018     //   have a single non-explicit conversion function to an integral or
15019     //   unscoped enumeration type
15020     ExprResult Converted;
15021     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15022     public:
15023       CXX11ConvertDiagnoser(bool Silent)
15024           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15025                                 Silent, true) {}
15026 
15027       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15028                                            QualType T) override {
15029         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15030       }
15031 
15032       SemaDiagnosticBuilder diagnoseIncomplete(
15033           Sema &S, SourceLocation Loc, QualType T) override {
15034         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15035       }
15036 
15037       SemaDiagnosticBuilder diagnoseExplicitConv(
15038           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15039         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15040       }
15041 
15042       SemaDiagnosticBuilder noteExplicitConv(
15043           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15044         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15045                  << ConvTy->isEnumeralType() << ConvTy;
15046       }
15047 
15048       SemaDiagnosticBuilder diagnoseAmbiguous(
15049           Sema &S, SourceLocation Loc, QualType T) override {
15050         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15051       }
15052 
15053       SemaDiagnosticBuilder noteAmbiguous(
15054           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15055         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15056                  << ConvTy->isEnumeralType() << ConvTy;
15057       }
15058 
15059       SemaDiagnosticBuilder diagnoseConversion(
15060           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15061         llvm_unreachable("conversion functions are permitted");
15062       }
15063     } ConvertDiagnoser(Diagnoser.Suppress);
15064 
15065     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15066                                                     ConvertDiagnoser);
15067     if (Converted.isInvalid())
15068       return Converted;
15069     E = Converted.get();
15070     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15071       return ExprError();
15072   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15073     // An ICE must be of integral or unscoped enumeration type.
15074     if (!Diagnoser.Suppress)
15075       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15076     return ExprError();
15077   }
15078 
15079   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15080   // in the non-ICE case.
15081   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15082     if (Result)
15083       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15084     if (!isa<ConstantExpr>(E))
15085       E = ConstantExpr::Create(Context, E);
15086     return E;
15087   }
15088 
15089   Expr::EvalResult EvalResult;
15090   SmallVector<PartialDiagnosticAt, 8> Notes;
15091   EvalResult.Diag = &Notes;
15092 
15093   // Try to evaluate the expression, and produce diagnostics explaining why it's
15094   // not a constant expression as a side-effect.
15095   bool Folded =
15096       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15097       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15098 
15099   if (!isa<ConstantExpr>(E))
15100     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15101 
15102   // In C++11, we can rely on diagnostics being produced for any expression
15103   // which is not a constant expression. If no diagnostics were produced, then
15104   // this is a constant expression.
15105   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15106     if (Result)
15107       *Result = EvalResult.Val.getInt();
15108     return E;
15109   }
15110 
15111   // If our only note is the usual "invalid subexpression" note, just point
15112   // the caret at its location rather than producing an essentially
15113   // redundant note.
15114   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15115         diag::note_invalid_subexpr_in_const_expr) {
15116     DiagLoc = Notes[0].first;
15117     Notes.clear();
15118   }
15119 
15120   if (!Folded || !AllowFold) {
15121     if (!Diagnoser.Suppress) {
15122       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15123       for (const PartialDiagnosticAt &Note : Notes)
15124         Diag(Note.first, Note.second);
15125     }
15126 
15127     return ExprError();
15128   }
15129 
15130   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15131   for (const PartialDiagnosticAt &Note : Notes)
15132     Diag(Note.first, Note.second);
15133 
15134   if (Result)
15135     *Result = EvalResult.Val.getInt();
15136   return E;
15137 }
15138 
15139 namespace {
15140   // Handle the case where we conclude a expression which we speculatively
15141   // considered to be unevaluated is actually evaluated.
15142   class TransformToPE : public TreeTransform<TransformToPE> {
15143     typedef TreeTransform<TransformToPE> BaseTransform;
15144 
15145   public:
15146     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15147 
15148     // Make sure we redo semantic analysis
15149     bool AlwaysRebuild() { return true; }
15150     bool ReplacingOriginal() { return true; }
15151 
15152     // We need to special-case DeclRefExprs referring to FieldDecls which
15153     // are not part of a member pointer formation; normal TreeTransforming
15154     // doesn't catch this case because of the way we represent them in the AST.
15155     // FIXME: This is a bit ugly; is it really the best way to handle this
15156     // case?
15157     //
15158     // Error on DeclRefExprs referring to FieldDecls.
15159     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15160       if (isa<FieldDecl>(E->getDecl()) &&
15161           !SemaRef.isUnevaluatedContext())
15162         return SemaRef.Diag(E->getLocation(),
15163                             diag::err_invalid_non_static_member_use)
15164             << E->getDecl() << E->getSourceRange();
15165 
15166       return BaseTransform::TransformDeclRefExpr(E);
15167     }
15168 
15169     // Exception: filter out member pointer formation
15170     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15171       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15172         return E;
15173 
15174       return BaseTransform::TransformUnaryOperator(E);
15175     }
15176 
15177     // The body of a lambda-expression is in a separate expression evaluation
15178     // context so never needs to be transformed.
15179     // FIXME: Ideally we wouldn't transform the closure type either, and would
15180     // just recreate the capture expressions and lambda expression.
15181     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15182       return SkipLambdaBody(E, Body);
15183     }
15184   };
15185 }
15186 
15187 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15188   assert(isUnevaluatedContext() &&
15189          "Should only transform unevaluated expressions");
15190   ExprEvalContexts.back().Context =
15191       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15192   if (isUnevaluatedContext())
15193     return E;
15194   return TransformToPE(*this).TransformExpr(E);
15195 }
15196 
15197 void
15198 Sema::PushExpressionEvaluationContext(
15199     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15200     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15201   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15202                                 LambdaContextDecl, ExprContext);
15203   Cleanup.reset();
15204   if (!MaybeODRUseExprs.empty())
15205     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15206 }
15207 
15208 void
15209 Sema::PushExpressionEvaluationContext(
15210     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15211     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15212   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15213   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15214 }
15215 
15216 namespace {
15217 
15218 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15219   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15220   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15221     if (E->getOpcode() == UO_Deref)
15222       return CheckPossibleDeref(S, E->getSubExpr());
15223   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15224     return CheckPossibleDeref(S, E->getBase());
15225   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15226     return CheckPossibleDeref(S, E->getBase());
15227   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15228     QualType Inner;
15229     QualType Ty = E->getType();
15230     if (const auto *Ptr = Ty->getAs<PointerType>())
15231       Inner = Ptr->getPointeeType();
15232     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15233       Inner = Arr->getElementType();
15234     else
15235       return nullptr;
15236 
15237     if (Inner->hasAttr(attr::NoDeref))
15238       return E;
15239   }
15240   return nullptr;
15241 }
15242 
15243 } // namespace
15244 
15245 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15246   for (const Expr *E : Rec.PossibleDerefs) {
15247     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15248     if (DeclRef) {
15249       const ValueDecl *Decl = DeclRef->getDecl();
15250       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15251           << Decl->getName() << E->getSourceRange();
15252       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15253     } else {
15254       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15255           << E->getSourceRange();
15256     }
15257   }
15258   Rec.PossibleDerefs.clear();
15259 }
15260 
15261 /// Check whether E, which is either a discarded-value expression or an
15262 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15263 /// and if so, remove it from the list of volatile-qualified assignments that
15264 /// we are going to warn are deprecated.
15265 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15266   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15267     return;
15268 
15269   // Note: ignoring parens here is not justified by the standard rules, but
15270   // ignoring parentheses seems like a more reasonable approach, and this only
15271   // drives a deprecation warning so doesn't affect conformance.
15272   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15273     if (BO->getOpcode() == BO_Assign) {
15274       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15275       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15276                  LHSs.end());
15277     }
15278   }
15279 }
15280 
15281 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15282   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15283       RebuildingImmediateInvocation)
15284     return E;
15285 
15286   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15287   /// It's OK if this fails; we'll also remove this in
15288   /// HandleImmediateInvocations, but catching it here allows us to avoid
15289   /// walking the AST looking for it in simple cases.
15290   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15291     if (auto *DeclRef =
15292             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15293       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15294 
15295   E = MaybeCreateExprWithCleanups(E);
15296 
15297   ConstantExpr *Res = ConstantExpr::Create(
15298       getASTContext(), E.get(),
15299       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15300                                    getASTContext()),
15301       /*IsImmediateInvocation*/ true);
15302   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15303   return Res;
15304 }
15305 
15306 static void EvaluateAndDiagnoseImmediateInvocation(
15307     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15308   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15309   Expr::EvalResult Eval;
15310   Eval.Diag = &Notes;
15311   ConstantExpr *CE = Candidate.getPointer();
15312   if (!CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15313                                   SemaRef.getASTContext(), true)) {
15314     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15315     FunctionDecl *FD = nullptr;
15316     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15317       FD = cast<FunctionDecl>(Call->getCalleeDecl());
15318     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15319       FD = Call->getConstructor();
15320     else
15321       llvm_unreachable("unhandled decl kind");
15322     assert(FD->isConsteval());
15323     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15324     for (auto &Note : Notes)
15325       SemaRef.Diag(Note.first, Note.second);
15326     return;
15327   }
15328   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15329 }
15330 
15331 static void RemoveNestedImmediateInvocation(
15332     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15333     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15334   struct ComplexRemove : TreeTransform<ComplexRemove> {
15335     using Base = TreeTransform<ComplexRemove>;
15336     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15337     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15338     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15339         CurrentII;
15340     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15341                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15342                   SmallVector<Sema::ImmediateInvocationCandidate,
15343                               4>::reverse_iterator Current)
15344         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15345     void RemoveImmediateInvocation(ConstantExpr* E) {
15346       auto It = std::find_if(CurrentII, IISet.rend(),
15347                              [E](Sema::ImmediateInvocationCandidate Elem) {
15348                                return Elem.getPointer() == E;
15349                              });
15350       assert(It != IISet.rend() &&
15351              "ConstantExpr marked IsImmediateInvocation should "
15352              "be present");
15353       It->setInt(1); // Mark as deleted
15354     }
15355     ExprResult TransformConstantExpr(ConstantExpr *E) {
15356       if (!E->isImmediateInvocation())
15357         return Base::TransformConstantExpr(E);
15358       RemoveImmediateInvocation(E);
15359       return Base::TransformExpr(E->getSubExpr());
15360     }
15361     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15362     /// we need to remove its DeclRefExpr from the DRSet.
15363     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15364       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15365       return Base::TransformCXXOperatorCallExpr(E);
15366     }
15367     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15368     /// here.
15369     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15370       if (!Init)
15371         return Init;
15372       /// ConstantExpr are the first layer of implicit node to be removed so if
15373       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15374       if (auto *CE = dyn_cast<ConstantExpr>(Init))
15375         if (CE->isImmediateInvocation())
15376           RemoveImmediateInvocation(CE);
15377       return Base::TransformInitializer(Init, NotCopyInit);
15378     }
15379     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15380       DRSet.erase(E);
15381       return E;
15382     }
15383     bool AlwaysRebuild() { return false; }
15384     bool ReplacingOriginal() { return true; }
15385   } Transformer(SemaRef, Rec.ReferenceToConsteval,
15386                 Rec.ImmediateInvocationCandidates, It);
15387   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
15388   assert(Res.isUsable());
15389   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
15390   It->getPointer()->setSubExpr(Res.get());
15391 }
15392 
15393 static void
15394 HandleImmediateInvocations(Sema &SemaRef,
15395                            Sema::ExpressionEvaluationContextRecord &Rec) {
15396   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
15397        Rec.ReferenceToConsteval.size() == 0) ||
15398       SemaRef.RebuildingImmediateInvocation)
15399     return;
15400 
15401   /// When we have more then 1 ImmediateInvocationCandidates we need to check
15402   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
15403   /// need to remove ReferenceToConsteval in the immediate invocation.
15404   if (Rec.ImmediateInvocationCandidates.size() > 1) {
15405 
15406     /// Prevent sema calls during the tree transform from adding pointers that
15407     /// are already in the sets.
15408     llvm::SaveAndRestore<bool> DisableIITracking(
15409         SemaRef.RebuildingImmediateInvocation, true);
15410 
15411     /// Prevent diagnostic during tree transfrom as they are duplicates
15412     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
15413 
15414     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
15415          It != Rec.ImmediateInvocationCandidates.rend(); It++)
15416       if (!It->getInt())
15417         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
15418   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
15419              Rec.ReferenceToConsteval.size()) {
15420     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
15421       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15422       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
15423       bool VisitDeclRefExpr(DeclRefExpr *E) {
15424         DRSet.erase(E);
15425         return DRSet.size();
15426       }
15427     } Visitor(Rec.ReferenceToConsteval);
15428     Visitor.TraverseStmt(
15429         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
15430   }
15431   for (auto CE : Rec.ImmediateInvocationCandidates)
15432     if (!CE.getInt())
15433       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
15434   for (auto DR : Rec.ReferenceToConsteval) {
15435     auto *FD = cast<FunctionDecl>(DR->getDecl());
15436     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
15437         << FD;
15438     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
15439   }
15440 }
15441 
15442 void Sema::PopExpressionEvaluationContext() {
15443   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15444   unsigned NumTypos = Rec.NumTypos;
15445 
15446   if (!Rec.Lambdas.empty()) {
15447     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15448     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15449         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15450       unsigned D;
15451       if (Rec.isUnevaluated()) {
15452         // C++11 [expr.prim.lambda]p2:
15453         //   A lambda-expression shall not appear in an unevaluated operand
15454         //   (Clause 5).
15455         D = diag::err_lambda_unevaluated_operand;
15456       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15457         // C++1y [expr.const]p2:
15458         //   A conditional-expression e is a core constant expression unless the
15459         //   evaluation of e, following the rules of the abstract machine, would
15460         //   evaluate [...] a lambda-expression.
15461         D = diag::err_lambda_in_constant_expression;
15462       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15463         // C++17 [expr.prim.lamda]p2:
15464         // A lambda-expression shall not appear [...] in a template-argument.
15465         D = diag::err_lambda_in_invalid_context;
15466       } else
15467         llvm_unreachable("Couldn't infer lambda error message.");
15468 
15469       for (const auto *L : Rec.Lambdas)
15470         Diag(L->getBeginLoc(), D);
15471     }
15472   }
15473 
15474   WarnOnPendingNoDerefs(Rec);
15475   HandleImmediateInvocations(*this, Rec);
15476 
15477   // Warn on any volatile-qualified simple-assignments that are not discarded-
15478   // value expressions nor unevaluated operands (those cases get removed from
15479   // this list by CheckUnusedVolatileAssignment).
15480   for (auto *BO : Rec.VolatileAssignmentLHSs)
15481     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15482         << BO->getType();
15483 
15484   // When are coming out of an unevaluated context, clear out any
15485   // temporaries that we may have created as part of the evaluation of
15486   // the expression in that context: they aren't relevant because they
15487   // will never be constructed.
15488   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15489     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15490                              ExprCleanupObjects.end());
15491     Cleanup = Rec.ParentCleanup;
15492     CleanupVarDeclMarking();
15493     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15494   // Otherwise, merge the contexts together.
15495   } else {
15496     Cleanup.mergeFrom(Rec.ParentCleanup);
15497     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15498                             Rec.SavedMaybeODRUseExprs.end());
15499   }
15500 
15501   // Pop the current expression evaluation context off the stack.
15502   ExprEvalContexts.pop_back();
15503 
15504   // The global expression evaluation context record is never popped.
15505   ExprEvalContexts.back().NumTypos += NumTypos;
15506 }
15507 
15508 void Sema::DiscardCleanupsInEvaluationContext() {
15509   ExprCleanupObjects.erase(
15510          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15511          ExprCleanupObjects.end());
15512   Cleanup.reset();
15513   MaybeODRUseExprs.clear();
15514 }
15515 
15516 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15517   ExprResult Result = CheckPlaceholderExpr(E);
15518   if (Result.isInvalid())
15519     return ExprError();
15520   E = Result.get();
15521   if (!E->getType()->isVariablyModifiedType())
15522     return E;
15523   return TransformToPotentiallyEvaluated(E);
15524 }
15525 
15526 /// Are we in a context that is potentially constant evaluated per C++20
15527 /// [expr.const]p12?
15528 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15529   /// C++2a [expr.const]p12:
15530   //   An expression or conversion is potentially constant evaluated if it is
15531   switch (SemaRef.ExprEvalContexts.back().Context) {
15532     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15533       // -- a manifestly constant-evaluated expression,
15534     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15535     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15536     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15537       // -- a potentially-evaluated expression,
15538     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15539       // -- an immediate subexpression of a braced-init-list,
15540 
15541       // -- [FIXME] an expression of the form & cast-expression that occurs
15542       //    within a templated entity
15543       // -- a subexpression of one of the above that is not a subexpression of
15544       // a nested unevaluated operand.
15545       return true;
15546 
15547     case Sema::ExpressionEvaluationContext::Unevaluated:
15548     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15549       // Expressions in this context are never evaluated.
15550       return false;
15551   }
15552   llvm_unreachable("Invalid context");
15553 }
15554 
15555 /// Return true if this function has a calling convention that requires mangling
15556 /// in the size of the parameter pack.
15557 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15558   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15559   // we don't need parameter type sizes.
15560   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15561   if (!TT.isOSWindows() || !TT.isX86())
15562     return false;
15563 
15564   // If this is C++ and this isn't an extern "C" function, parameters do not
15565   // need to be complete. In this case, C++ mangling will apply, which doesn't
15566   // use the size of the parameters.
15567   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15568     return false;
15569 
15570   // Stdcall, fastcall, and vectorcall need this special treatment.
15571   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15572   switch (CC) {
15573   case CC_X86StdCall:
15574   case CC_X86FastCall:
15575   case CC_X86VectorCall:
15576     return true;
15577   default:
15578     break;
15579   }
15580   return false;
15581 }
15582 
15583 /// Require that all of the parameter types of function be complete. Normally,
15584 /// parameter types are only required to be complete when a function is called
15585 /// or defined, but to mangle functions with certain calling conventions, the
15586 /// mangler needs to know the size of the parameter list. In this situation,
15587 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15588 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15589 /// result in a linker error. Clang doesn't implement this behavior, and instead
15590 /// attempts to error at compile time.
15591 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15592                                                   SourceLocation Loc) {
15593   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15594     FunctionDecl *FD;
15595     ParmVarDecl *Param;
15596 
15597   public:
15598     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15599         : FD(FD), Param(Param) {}
15600 
15601     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15602       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15603       StringRef CCName;
15604       switch (CC) {
15605       case CC_X86StdCall:
15606         CCName = "stdcall";
15607         break;
15608       case CC_X86FastCall:
15609         CCName = "fastcall";
15610         break;
15611       case CC_X86VectorCall:
15612         CCName = "vectorcall";
15613         break;
15614       default:
15615         llvm_unreachable("CC does not need mangling");
15616       }
15617 
15618       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15619           << Param->getDeclName() << FD->getDeclName() << CCName;
15620     }
15621   };
15622 
15623   for (ParmVarDecl *Param : FD->parameters()) {
15624     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15625     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15626   }
15627 }
15628 
15629 namespace {
15630 enum class OdrUseContext {
15631   /// Declarations in this context are not odr-used.
15632   None,
15633   /// Declarations in this context are formally odr-used, but this is a
15634   /// dependent context.
15635   Dependent,
15636   /// Declarations in this context are odr-used but not actually used (yet).
15637   FormallyOdrUsed,
15638   /// Declarations in this context are used.
15639   Used
15640 };
15641 }
15642 
15643 /// Are we within a context in which references to resolved functions or to
15644 /// variables result in odr-use?
15645 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15646   OdrUseContext Result;
15647 
15648   switch (SemaRef.ExprEvalContexts.back().Context) {
15649     case Sema::ExpressionEvaluationContext::Unevaluated:
15650     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15651     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15652       return OdrUseContext::None;
15653 
15654     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15655     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15656       Result = OdrUseContext::Used;
15657       break;
15658 
15659     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15660       Result = OdrUseContext::FormallyOdrUsed;
15661       break;
15662 
15663     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15664       // A default argument formally results in odr-use, but doesn't actually
15665       // result in a use in any real sense until it itself is used.
15666       Result = OdrUseContext::FormallyOdrUsed;
15667       break;
15668   }
15669 
15670   if (SemaRef.CurContext->isDependentContext())
15671     return OdrUseContext::Dependent;
15672 
15673   return Result;
15674 }
15675 
15676 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15677   return Func->isConstexpr() &&
15678          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
15679 }
15680 
15681 /// Mark a function referenced, and check whether it is odr-used
15682 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15683 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15684                                   bool MightBeOdrUse) {
15685   assert(Func && "No function?");
15686 
15687   Func->setReferenced();
15688 
15689   // Recursive functions aren't really used until they're used from some other
15690   // context.
15691   bool IsRecursiveCall = CurContext == Func;
15692 
15693   // C++11 [basic.def.odr]p3:
15694   //   A function whose name appears as a potentially-evaluated expression is
15695   //   odr-used if it is the unique lookup result or the selected member of a
15696   //   set of overloaded functions [...].
15697   //
15698   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15699   // can just check that here.
15700   OdrUseContext OdrUse =
15701       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15702   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15703     OdrUse = OdrUseContext::FormallyOdrUsed;
15704 
15705   // Trivial default constructors and destructors are never actually used.
15706   // FIXME: What about other special members?
15707   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15708       OdrUse == OdrUseContext::Used) {
15709     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15710       if (Constructor->isDefaultConstructor())
15711         OdrUse = OdrUseContext::FormallyOdrUsed;
15712     if (isa<CXXDestructorDecl>(Func))
15713       OdrUse = OdrUseContext::FormallyOdrUsed;
15714   }
15715 
15716   // C++20 [expr.const]p12:
15717   //   A function [...] is needed for constant evaluation if it is [...] a
15718   //   constexpr function that is named by an expression that is potentially
15719   //   constant evaluated
15720   bool NeededForConstantEvaluation =
15721       isPotentiallyConstantEvaluatedContext(*this) &&
15722       isImplicitlyDefinableConstexprFunction(Func);
15723 
15724   // Determine whether we require a function definition to exist, per
15725   // C++11 [temp.inst]p3:
15726   //   Unless a function template specialization has been explicitly
15727   //   instantiated or explicitly specialized, the function template
15728   //   specialization is implicitly instantiated when the specialization is
15729   //   referenced in a context that requires a function definition to exist.
15730   // C++20 [temp.inst]p7:
15731   //   The existence of a definition of a [...] function is considered to
15732   //   affect the semantics of the program if the [...] function is needed for
15733   //   constant evaluation by an expression
15734   // C++20 [basic.def.odr]p10:
15735   //   Every program shall contain exactly one definition of every non-inline
15736   //   function or variable that is odr-used in that program outside of a
15737   //   discarded statement
15738   // C++20 [special]p1:
15739   //   The implementation will implicitly define [defaulted special members]
15740   //   if they are odr-used or needed for constant evaluation.
15741   //
15742   // Note that we skip the implicit instantiation of templates that are only
15743   // used in unused default arguments or by recursive calls to themselves.
15744   // This is formally non-conforming, but seems reasonable in practice.
15745   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15746                                              NeededForConstantEvaluation);
15747 
15748   // C++14 [temp.expl.spec]p6:
15749   //   If a template [...] is explicitly specialized then that specialization
15750   //   shall be declared before the first use of that specialization that would
15751   //   cause an implicit instantiation to take place, in every translation unit
15752   //   in which such a use occurs
15753   if (NeedDefinition &&
15754       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15755        Func->getMemberSpecializationInfo()))
15756     checkSpecializationVisibility(Loc, Func);
15757 
15758   if (getLangOpts().CUDA)
15759     CheckCUDACall(Loc, Func);
15760 
15761   // If we need a definition, try to create one.
15762   if (NeedDefinition && !Func->getBody()) {
15763     runWithSufficientStackSpace(Loc, [&] {
15764       if (CXXConstructorDecl *Constructor =
15765               dyn_cast<CXXConstructorDecl>(Func)) {
15766         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15767         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15768           if (Constructor->isDefaultConstructor()) {
15769             if (Constructor->isTrivial() &&
15770                 !Constructor->hasAttr<DLLExportAttr>())
15771               return;
15772             DefineImplicitDefaultConstructor(Loc, Constructor);
15773           } else if (Constructor->isCopyConstructor()) {
15774             DefineImplicitCopyConstructor(Loc, Constructor);
15775           } else if (Constructor->isMoveConstructor()) {
15776             DefineImplicitMoveConstructor(Loc, Constructor);
15777           }
15778         } else if (Constructor->getInheritedConstructor()) {
15779           DefineInheritingConstructor(Loc, Constructor);
15780         }
15781       } else if (CXXDestructorDecl *Destructor =
15782                      dyn_cast<CXXDestructorDecl>(Func)) {
15783         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15784         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15785           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15786             return;
15787           DefineImplicitDestructor(Loc, Destructor);
15788         }
15789         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15790           MarkVTableUsed(Loc, Destructor->getParent());
15791       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15792         if (MethodDecl->isOverloadedOperator() &&
15793             MethodDecl->getOverloadedOperator() == OO_Equal) {
15794           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15795           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15796             if (MethodDecl->isCopyAssignmentOperator())
15797               DefineImplicitCopyAssignment(Loc, MethodDecl);
15798             else if (MethodDecl->isMoveAssignmentOperator())
15799               DefineImplicitMoveAssignment(Loc, MethodDecl);
15800           }
15801         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15802                    MethodDecl->getParent()->isLambda()) {
15803           CXXConversionDecl *Conversion =
15804               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15805           if (Conversion->isLambdaToBlockPointerConversion())
15806             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15807           else
15808             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15809         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15810           MarkVTableUsed(Loc, MethodDecl->getParent());
15811       }
15812 
15813       if (Func->isDefaulted() && !Func->isDeleted()) {
15814         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
15815         if (DCK != DefaultedComparisonKind::None)
15816           DefineDefaultedComparison(Loc, Func, DCK);
15817       }
15818 
15819       // Implicit instantiation of function templates and member functions of
15820       // class templates.
15821       if (Func->isImplicitlyInstantiable()) {
15822         TemplateSpecializationKind TSK =
15823             Func->getTemplateSpecializationKindForInstantiation();
15824         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15825         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15826         if (FirstInstantiation) {
15827           PointOfInstantiation = Loc;
15828           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15829         } else if (TSK != TSK_ImplicitInstantiation) {
15830           // Use the point of use as the point of instantiation, instead of the
15831           // point of explicit instantiation (which we track as the actual point
15832           // of instantiation). This gives better backtraces in diagnostics.
15833           PointOfInstantiation = Loc;
15834         }
15835 
15836         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15837             Func->isConstexpr()) {
15838           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15839               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15840               CodeSynthesisContexts.size())
15841             PendingLocalImplicitInstantiations.push_back(
15842                 std::make_pair(Func, PointOfInstantiation));
15843           else if (Func->isConstexpr())
15844             // Do not defer instantiations of constexpr functions, to avoid the
15845             // expression evaluator needing to call back into Sema if it sees a
15846             // call to such a function.
15847             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15848           else {
15849             Func->setInstantiationIsPending(true);
15850             PendingInstantiations.push_back(
15851                 std::make_pair(Func, PointOfInstantiation));
15852             // Notify the consumer that a function was implicitly instantiated.
15853             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15854           }
15855         }
15856       } else {
15857         // Walk redefinitions, as some of them may be instantiable.
15858         for (auto i : Func->redecls()) {
15859           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15860             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15861         }
15862       }
15863     });
15864   }
15865 
15866   // C++14 [except.spec]p17:
15867   //   An exception-specification is considered to be needed when:
15868   //   - the function is odr-used or, if it appears in an unevaluated operand,
15869   //     would be odr-used if the expression were potentially-evaluated;
15870   //
15871   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15872   // function is a pure virtual function we're calling, and in that case the
15873   // function was selected by overload resolution and we need to resolve its
15874   // exception specification for a different reason.
15875   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15876   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15877     ResolveExceptionSpec(Loc, FPT);
15878 
15879   // If this is the first "real" use, act on that.
15880   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15881     // Keep track of used but undefined functions.
15882     if (!Func->isDefined()) {
15883       if (mightHaveNonExternalLinkage(Func))
15884         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15885       else if (Func->getMostRecentDecl()->isInlined() &&
15886                !LangOpts.GNUInline &&
15887                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15888         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15889       else if (isExternalWithNoLinkageType(Func))
15890         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15891     }
15892 
15893     // Some x86 Windows calling conventions mangle the size of the parameter
15894     // pack into the name. Computing the size of the parameters requires the
15895     // parameter types to be complete. Check that now.
15896     if (funcHasParameterSizeMangling(*this, Func))
15897       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15898 
15899     Func->markUsed(Context);
15900   }
15901 
15902   if (LangOpts.OpenMP)
15903     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15904 }
15905 
15906 /// Directly mark a variable odr-used. Given a choice, prefer to use
15907 /// MarkVariableReferenced since it does additional checks and then
15908 /// calls MarkVarDeclODRUsed.
15909 /// If the variable must be captured:
15910 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15911 ///  - else capture it in the DeclContext that maps to the
15912 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15913 static void
15914 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15915                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15916   // Keep track of used but undefined variables.
15917   // FIXME: We shouldn't suppress this warning for static data members.
15918   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15919       (!Var->isExternallyVisible() || Var->isInline() ||
15920        SemaRef.isExternalWithNoLinkageType(Var)) &&
15921       !(Var->isStaticDataMember() && Var->hasInit())) {
15922     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15923     if (old.isInvalid())
15924       old = Loc;
15925   }
15926   QualType CaptureType, DeclRefType;
15927   if (SemaRef.LangOpts.OpenMP)
15928     SemaRef.tryCaptureOpenMPLambdas(Var);
15929   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15930     /*EllipsisLoc*/ SourceLocation(),
15931     /*BuildAndDiagnose*/ true,
15932     CaptureType, DeclRefType,
15933     FunctionScopeIndexToStopAt);
15934 
15935   Var->markUsed(SemaRef.Context);
15936 }
15937 
15938 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15939                                              SourceLocation Loc,
15940                                              unsigned CapturingScopeIndex) {
15941   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15942 }
15943 
15944 static void
15945 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15946                                    ValueDecl *var, DeclContext *DC) {
15947   DeclContext *VarDC = var->getDeclContext();
15948 
15949   //  If the parameter still belongs to the translation unit, then
15950   //  we're actually just using one parameter in the declaration of
15951   //  the next.
15952   if (isa<ParmVarDecl>(var) &&
15953       isa<TranslationUnitDecl>(VarDC))
15954     return;
15955 
15956   // For C code, don't diagnose about capture if we're not actually in code
15957   // right now; it's impossible to write a non-constant expression outside of
15958   // function context, so we'll get other (more useful) diagnostics later.
15959   //
15960   // For C++, things get a bit more nasty... it would be nice to suppress this
15961   // diagnostic for certain cases like using a local variable in an array bound
15962   // for a member of a local class, but the correct predicate is not obvious.
15963   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15964     return;
15965 
15966   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15967   unsigned ContextKind = 3; // unknown
15968   if (isa<CXXMethodDecl>(VarDC) &&
15969       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15970     ContextKind = 2;
15971   } else if (isa<FunctionDecl>(VarDC)) {
15972     ContextKind = 0;
15973   } else if (isa<BlockDecl>(VarDC)) {
15974     ContextKind = 1;
15975   }
15976 
15977   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15978     << var << ValueKind << ContextKind << VarDC;
15979   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15980       << var;
15981 
15982   // FIXME: Add additional diagnostic info about class etc. which prevents
15983   // capture.
15984 }
15985 
15986 
15987 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15988                                       bool &SubCapturesAreNested,
15989                                       QualType &CaptureType,
15990                                       QualType &DeclRefType) {
15991    // Check whether we've already captured it.
15992   if (CSI->CaptureMap.count(Var)) {
15993     // If we found a capture, any subcaptures are nested.
15994     SubCapturesAreNested = true;
15995 
15996     // Retrieve the capture type for this variable.
15997     CaptureType = CSI->getCapture(Var).getCaptureType();
15998 
15999     // Compute the type of an expression that refers to this variable.
16000     DeclRefType = CaptureType.getNonReferenceType();
16001 
16002     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16003     // are mutable in the sense that user can change their value - they are
16004     // private instances of the captured declarations.
16005     const Capture &Cap = CSI->getCapture(Var);
16006     if (Cap.isCopyCapture() &&
16007         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16008         !(isa<CapturedRegionScopeInfo>(CSI) &&
16009           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16010       DeclRefType.addConst();
16011     return true;
16012   }
16013   return false;
16014 }
16015 
16016 // Only block literals, captured statements, and lambda expressions can
16017 // capture; other scopes don't work.
16018 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16019                                  SourceLocation Loc,
16020                                  const bool Diagnose, Sema &S) {
16021   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16022     return getLambdaAwareParentOfDeclContext(DC);
16023   else if (Var->hasLocalStorage()) {
16024     if (Diagnose)
16025        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16026   }
16027   return nullptr;
16028 }
16029 
16030 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16031 // certain types of variables (unnamed, variably modified types etc.)
16032 // so check for eligibility.
16033 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16034                                  SourceLocation Loc,
16035                                  const bool Diagnose, Sema &S) {
16036 
16037   bool IsBlock = isa<BlockScopeInfo>(CSI);
16038   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16039 
16040   // Lambdas are not allowed to capture unnamed variables
16041   // (e.g. anonymous unions).
16042   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16043   // assuming that's the intent.
16044   if (IsLambda && !Var->getDeclName()) {
16045     if (Diagnose) {
16046       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16047       S.Diag(Var->getLocation(), diag::note_declared_at);
16048     }
16049     return false;
16050   }
16051 
16052   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16053   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16054     if (Diagnose) {
16055       S.Diag(Loc, diag::err_ref_vm_type);
16056       S.Diag(Var->getLocation(), diag::note_previous_decl)
16057         << Var->getDeclName();
16058     }
16059     return false;
16060   }
16061   // Prohibit structs with flexible array members too.
16062   // We cannot capture what is in the tail end of the struct.
16063   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16064     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16065       if (Diagnose) {
16066         if (IsBlock)
16067           S.Diag(Loc, diag::err_ref_flexarray_type);
16068         else
16069           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16070             << Var->getDeclName();
16071         S.Diag(Var->getLocation(), diag::note_previous_decl)
16072           << Var->getDeclName();
16073       }
16074       return false;
16075     }
16076   }
16077   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16078   // Lambdas and captured statements are not allowed to capture __block
16079   // variables; they don't support the expected semantics.
16080   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16081     if (Diagnose) {
16082       S.Diag(Loc, diag::err_capture_block_variable)
16083         << Var->getDeclName() << !IsLambda;
16084       S.Diag(Var->getLocation(), diag::note_previous_decl)
16085         << Var->getDeclName();
16086     }
16087     return false;
16088   }
16089   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16090   if (S.getLangOpts().OpenCL && IsBlock &&
16091       Var->getType()->isBlockPointerType()) {
16092     if (Diagnose)
16093       S.Diag(Loc, diag::err_opencl_block_ref_block);
16094     return false;
16095   }
16096 
16097   return true;
16098 }
16099 
16100 // Returns true if the capture by block was successful.
16101 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16102                                  SourceLocation Loc,
16103                                  const bool BuildAndDiagnose,
16104                                  QualType &CaptureType,
16105                                  QualType &DeclRefType,
16106                                  const bool Nested,
16107                                  Sema &S, bool Invalid) {
16108   bool ByRef = false;
16109 
16110   // Blocks are not allowed to capture arrays, excepting OpenCL.
16111   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16112   // (decayed to pointers).
16113   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16114     if (BuildAndDiagnose) {
16115       S.Diag(Loc, diag::err_ref_array_type);
16116       S.Diag(Var->getLocation(), diag::note_previous_decl)
16117       << Var->getDeclName();
16118       Invalid = true;
16119     } else {
16120       return false;
16121     }
16122   }
16123 
16124   // Forbid the block-capture of autoreleasing variables.
16125   if (!Invalid &&
16126       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16127     if (BuildAndDiagnose) {
16128       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16129         << /*block*/ 0;
16130       S.Diag(Var->getLocation(), diag::note_previous_decl)
16131         << Var->getDeclName();
16132       Invalid = true;
16133     } else {
16134       return false;
16135     }
16136   }
16137 
16138   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16139   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16140     QualType PointeeTy = PT->getPointeeType();
16141 
16142     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16143         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16144         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16145       if (BuildAndDiagnose) {
16146         SourceLocation VarLoc = Var->getLocation();
16147         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16148         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16149       }
16150     }
16151   }
16152 
16153   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16154   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16155       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16156     // Block capture by reference does not change the capture or
16157     // declaration reference types.
16158     ByRef = true;
16159   } else {
16160     // Block capture by copy introduces 'const'.
16161     CaptureType = CaptureType.getNonReferenceType().withConst();
16162     DeclRefType = CaptureType;
16163   }
16164 
16165   // Actually capture the variable.
16166   if (BuildAndDiagnose)
16167     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16168                     CaptureType, Invalid);
16169 
16170   return !Invalid;
16171 }
16172 
16173 
16174 /// Capture the given variable in the captured region.
16175 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16176                                     VarDecl *Var,
16177                                     SourceLocation Loc,
16178                                     const bool BuildAndDiagnose,
16179                                     QualType &CaptureType,
16180                                     QualType &DeclRefType,
16181                                     const bool RefersToCapturedVariable,
16182                                     Sema &S, bool Invalid) {
16183   // By default, capture variables by reference.
16184   bool ByRef = true;
16185   // Using an LValue reference type is consistent with Lambdas (see below).
16186   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16187     if (S.isOpenMPCapturedDecl(Var)) {
16188       bool HasConst = DeclRefType.isConstQualified();
16189       DeclRefType = DeclRefType.getUnqualifiedType();
16190       // Don't lose diagnostics about assignments to const.
16191       if (HasConst)
16192         DeclRefType.addConst();
16193     }
16194     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16195                                     RSI->OpenMPCaptureLevel);
16196   }
16197 
16198   if (ByRef)
16199     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16200   else
16201     CaptureType = DeclRefType;
16202 
16203   // Actually capture the variable.
16204   if (BuildAndDiagnose)
16205     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16206                     Loc, SourceLocation(), CaptureType, Invalid);
16207 
16208   return !Invalid;
16209 }
16210 
16211 /// Capture the given variable in the lambda.
16212 static bool captureInLambda(LambdaScopeInfo *LSI,
16213                             VarDecl *Var,
16214                             SourceLocation Loc,
16215                             const bool BuildAndDiagnose,
16216                             QualType &CaptureType,
16217                             QualType &DeclRefType,
16218                             const bool RefersToCapturedVariable,
16219                             const Sema::TryCaptureKind Kind,
16220                             SourceLocation EllipsisLoc,
16221                             const bool IsTopScope,
16222                             Sema &S, bool Invalid) {
16223   // Determine whether we are capturing by reference or by value.
16224   bool ByRef = false;
16225   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16226     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16227   } else {
16228     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16229   }
16230 
16231   // Compute the type of the field that will capture this variable.
16232   if (ByRef) {
16233     // C++11 [expr.prim.lambda]p15:
16234     //   An entity is captured by reference if it is implicitly or
16235     //   explicitly captured but not captured by copy. It is
16236     //   unspecified whether additional unnamed non-static data
16237     //   members are declared in the closure type for entities
16238     //   captured by reference.
16239     //
16240     // FIXME: It is not clear whether we want to build an lvalue reference
16241     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16242     // to do the former, while EDG does the latter. Core issue 1249 will
16243     // clarify, but for now we follow GCC because it's a more permissive and
16244     // easily defensible position.
16245     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16246   } else {
16247     // C++11 [expr.prim.lambda]p14:
16248     //   For each entity captured by copy, an unnamed non-static
16249     //   data member is declared in the closure type. The
16250     //   declaration order of these members is unspecified. The type
16251     //   of such a data member is the type of the corresponding
16252     //   captured entity if the entity is not a reference to an
16253     //   object, or the referenced type otherwise. [Note: If the
16254     //   captured entity is a reference to a function, the
16255     //   corresponding data member is also a reference to a
16256     //   function. - end note ]
16257     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16258       if (!RefType->getPointeeType()->isFunctionType())
16259         CaptureType = RefType->getPointeeType();
16260     }
16261 
16262     // Forbid the lambda copy-capture of autoreleasing variables.
16263     if (!Invalid &&
16264         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16265       if (BuildAndDiagnose) {
16266         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16267         S.Diag(Var->getLocation(), diag::note_previous_decl)
16268           << Var->getDeclName();
16269         Invalid = true;
16270       } else {
16271         return false;
16272       }
16273     }
16274 
16275     // Make sure that by-copy captures are of a complete and non-abstract type.
16276     if (!Invalid && BuildAndDiagnose) {
16277       if (!CaptureType->isDependentType() &&
16278           S.RequireCompleteType(Loc, CaptureType,
16279                                 diag::err_capture_of_incomplete_type,
16280                                 Var->getDeclName()))
16281         Invalid = true;
16282       else if (S.RequireNonAbstractType(Loc, CaptureType,
16283                                         diag::err_capture_of_abstract_type))
16284         Invalid = true;
16285     }
16286   }
16287 
16288   // Compute the type of a reference to this captured variable.
16289   if (ByRef)
16290     DeclRefType = CaptureType.getNonReferenceType();
16291   else {
16292     // C++ [expr.prim.lambda]p5:
16293     //   The closure type for a lambda-expression has a public inline
16294     //   function call operator [...]. This function call operator is
16295     //   declared const (9.3.1) if and only if the lambda-expression's
16296     //   parameter-declaration-clause is not followed by mutable.
16297     DeclRefType = CaptureType.getNonReferenceType();
16298     if (!LSI->Mutable && !CaptureType->isReferenceType())
16299       DeclRefType.addConst();
16300   }
16301 
16302   // Add the capture.
16303   if (BuildAndDiagnose)
16304     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16305                     Loc, EllipsisLoc, CaptureType, Invalid);
16306 
16307   return !Invalid;
16308 }
16309 
16310 bool Sema::tryCaptureVariable(
16311     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16312     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16313     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16314   // An init-capture is notionally from the context surrounding its
16315   // declaration, but its parent DC is the lambda class.
16316   DeclContext *VarDC = Var->getDeclContext();
16317   if (Var->isInitCapture())
16318     VarDC = VarDC->getParent();
16319 
16320   DeclContext *DC = CurContext;
16321   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16322       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16323   // We need to sync up the Declaration Context with the
16324   // FunctionScopeIndexToStopAt
16325   if (FunctionScopeIndexToStopAt) {
16326     unsigned FSIndex = FunctionScopes.size() - 1;
16327     while (FSIndex != MaxFunctionScopesIndex) {
16328       DC = getLambdaAwareParentOfDeclContext(DC);
16329       --FSIndex;
16330     }
16331   }
16332 
16333 
16334   // If the variable is declared in the current context, there is no need to
16335   // capture it.
16336   if (VarDC == DC) return true;
16337 
16338   // Capture global variables if it is required to use private copy of this
16339   // variable.
16340   bool IsGlobal = !Var->hasLocalStorage();
16341   if (IsGlobal &&
16342       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16343                                                 MaxFunctionScopesIndex)))
16344     return true;
16345   Var = Var->getCanonicalDecl();
16346 
16347   // Walk up the stack to determine whether we can capture the variable,
16348   // performing the "simple" checks that don't depend on type. We stop when
16349   // we've either hit the declared scope of the variable or find an existing
16350   // capture of that variable.  We start from the innermost capturing-entity
16351   // (the DC) and ensure that all intervening capturing-entities
16352   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16353   // declcontext can either capture the variable or have already captured
16354   // the variable.
16355   CaptureType = Var->getType();
16356   DeclRefType = CaptureType.getNonReferenceType();
16357   bool Nested = false;
16358   bool Explicit = (Kind != TryCapture_Implicit);
16359   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16360   do {
16361     // Only block literals, captured statements, and lambda expressions can
16362     // capture; other scopes don't work.
16363     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16364                                                               ExprLoc,
16365                                                               BuildAndDiagnose,
16366                                                               *this);
16367     // We need to check for the parent *first* because, if we *have*
16368     // private-captured a global variable, we need to recursively capture it in
16369     // intermediate blocks, lambdas, etc.
16370     if (!ParentDC) {
16371       if (IsGlobal) {
16372         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16373         break;
16374       }
16375       return true;
16376     }
16377 
16378     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16379     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16380 
16381 
16382     // Check whether we've already captured it.
16383     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16384                                              DeclRefType)) {
16385       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16386       break;
16387     }
16388     // If we are instantiating a generic lambda call operator body,
16389     // we do not want to capture new variables.  What was captured
16390     // during either a lambdas transformation or initial parsing
16391     // should be used.
16392     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16393       if (BuildAndDiagnose) {
16394         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16395         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16396           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16397           Diag(Var->getLocation(), diag::note_previous_decl)
16398              << Var->getDeclName();
16399           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16400         } else
16401           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16402       }
16403       return true;
16404     }
16405 
16406     // Try to capture variable-length arrays types.
16407     if (Var->getType()->isVariablyModifiedType()) {
16408       // We're going to walk down into the type and look for VLA
16409       // expressions.
16410       QualType QTy = Var->getType();
16411       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16412         QTy = PVD->getOriginalType();
16413       captureVariablyModifiedType(Context, QTy, CSI);
16414     }
16415 
16416     if (getLangOpts().OpenMP) {
16417       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16418         // OpenMP private variables should not be captured in outer scope, so
16419         // just break here. Similarly, global variables that are captured in a
16420         // target region should not be captured outside the scope of the region.
16421         if (RSI->CapRegionKind == CR_OpenMP) {
16422           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16423           // If the variable is private (i.e. not captured) and has variably
16424           // modified type, we still need to capture the type for correct
16425           // codegen in all regions, associated with the construct. Currently,
16426           // it is captured in the innermost captured region only.
16427           if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16428             QualType QTy = Var->getType();
16429             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16430               QTy = PVD->getOriginalType();
16431             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16432                  I < E; ++I) {
16433               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16434                   FunctionScopes[FunctionScopesIndex - I]);
16435               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16436                      "Wrong number of captured regions associated with the "
16437                      "OpenMP construct.");
16438               captureVariablyModifiedType(Context, QTy, OuterRSI);
16439             }
16440           }
16441           bool IsTargetCap =
16442               !IsOpenMPPrivateDecl &&
16443               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
16444                                          RSI->OpenMPCaptureLevel);
16445           // When we detect target captures we are looking from inside the
16446           // target region, therefore we need to propagate the capture from the
16447           // enclosing region. Therefore, the capture is not initially nested.
16448           if (IsTargetCap)
16449             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16450 
16451           if (IsTargetCap || IsOpenMPPrivateDecl) {
16452             Nested = !IsTargetCap;
16453             DeclRefType = DeclRefType.getUnqualifiedType();
16454             CaptureType = Context.getLValueReferenceType(DeclRefType);
16455             break;
16456           }
16457         }
16458       }
16459     }
16460     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16461       // No capture-default, and this is not an explicit capture
16462       // so cannot capture this variable.
16463       if (BuildAndDiagnose) {
16464         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16465         Diag(Var->getLocation(), diag::note_previous_decl)
16466           << Var->getDeclName();
16467         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16468           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16469                diag::note_lambda_decl);
16470         // FIXME: If we error out because an outer lambda can not implicitly
16471         // capture a variable that an inner lambda explicitly captures, we
16472         // should have the inner lambda do the explicit capture - because
16473         // it makes for cleaner diagnostics later.  This would purely be done
16474         // so that the diagnostic does not misleadingly claim that a variable
16475         // can not be captured by a lambda implicitly even though it is captured
16476         // explicitly.  Suggestion:
16477         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16478         //    at the function head
16479         //  - cache the StartingDeclContext - this must be a lambda
16480         //  - captureInLambda in the innermost lambda the variable.
16481       }
16482       return true;
16483     }
16484 
16485     FunctionScopesIndex--;
16486     DC = ParentDC;
16487     Explicit = false;
16488   } while (!VarDC->Equals(DC));
16489 
16490   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16491   // computing the type of the capture at each step, checking type-specific
16492   // requirements, and adding captures if requested.
16493   // If the variable had already been captured previously, we start capturing
16494   // at the lambda nested within that one.
16495   bool Invalid = false;
16496   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16497        ++I) {
16498     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16499 
16500     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16501     // certain types of variables (unnamed, variably modified types etc.)
16502     // so check for eligibility.
16503     if (!Invalid)
16504       Invalid =
16505           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16506 
16507     // After encountering an error, if we're actually supposed to capture, keep
16508     // capturing in nested contexts to suppress any follow-on diagnostics.
16509     if (Invalid && !BuildAndDiagnose)
16510       return true;
16511 
16512     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16513       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16514                                DeclRefType, Nested, *this, Invalid);
16515       Nested = true;
16516     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16517       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16518                                          CaptureType, DeclRefType, Nested,
16519                                          *this, Invalid);
16520       Nested = true;
16521     } else {
16522       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16523       Invalid =
16524           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16525                            DeclRefType, Nested, Kind, EllipsisLoc,
16526                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16527       Nested = true;
16528     }
16529 
16530     if (Invalid && !BuildAndDiagnose)
16531       return true;
16532   }
16533   return Invalid;
16534 }
16535 
16536 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16537                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16538   QualType CaptureType;
16539   QualType DeclRefType;
16540   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16541                             /*BuildAndDiagnose=*/true, CaptureType,
16542                             DeclRefType, nullptr);
16543 }
16544 
16545 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16546   QualType CaptureType;
16547   QualType DeclRefType;
16548   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16549                              /*BuildAndDiagnose=*/false, CaptureType,
16550                              DeclRefType, nullptr);
16551 }
16552 
16553 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16554   QualType CaptureType;
16555   QualType DeclRefType;
16556 
16557   // Determine whether we can capture this variable.
16558   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16559                          /*BuildAndDiagnose=*/false, CaptureType,
16560                          DeclRefType, nullptr))
16561     return QualType();
16562 
16563   return DeclRefType;
16564 }
16565 
16566 namespace {
16567 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16568 // The produced TemplateArgumentListInfo* points to data stored within this
16569 // object, so should only be used in contexts where the pointer will not be
16570 // used after the CopiedTemplateArgs object is destroyed.
16571 class CopiedTemplateArgs {
16572   bool HasArgs;
16573   TemplateArgumentListInfo TemplateArgStorage;
16574 public:
16575   template<typename RefExpr>
16576   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16577     if (HasArgs)
16578       E->copyTemplateArgumentsInto(TemplateArgStorage);
16579   }
16580   operator TemplateArgumentListInfo*()
16581 #ifdef __has_cpp_attribute
16582 #if __has_cpp_attribute(clang::lifetimebound)
16583   [[clang::lifetimebound]]
16584 #endif
16585 #endif
16586   {
16587     return HasArgs ? &TemplateArgStorage : nullptr;
16588   }
16589 };
16590 }
16591 
16592 /// Walk the set of potential results of an expression and mark them all as
16593 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16594 ///
16595 /// \return A new expression if we found any potential results, ExprEmpty() if
16596 ///         not, and ExprError() if we diagnosed an error.
16597 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16598                                                       NonOdrUseReason NOUR) {
16599   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16600   // an object that satisfies the requirements for appearing in a
16601   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16602   // is immediately applied."  This function handles the lvalue-to-rvalue
16603   // conversion part.
16604   //
16605   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16606   // transform it into the relevant kind of non-odr-use node and rebuild the
16607   // tree of nodes leading to it.
16608   //
16609   // This is a mini-TreeTransform that only transforms a restricted subset of
16610   // nodes (and only certain operands of them).
16611 
16612   // Rebuild a subexpression.
16613   auto Rebuild = [&](Expr *Sub) {
16614     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16615   };
16616 
16617   // Check whether a potential result satisfies the requirements of NOUR.
16618   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16619     // Any entity other than a VarDecl is always odr-used whenever it's named
16620     // in a potentially-evaluated expression.
16621     auto *VD = dyn_cast<VarDecl>(D);
16622     if (!VD)
16623       return true;
16624 
16625     // C++2a [basic.def.odr]p4:
16626     //   A variable x whose name appears as a potentially-evalauted expression
16627     //   e is odr-used by e unless
16628     //   -- x is a reference that is usable in constant expressions, or
16629     //   -- x is a variable of non-reference type that is usable in constant
16630     //      expressions and has no mutable subobjects, and e is an element of
16631     //      the set of potential results of an expression of
16632     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16633     //      conversion is applied, or
16634     //   -- x is a variable of non-reference type, and e is an element of the
16635     //      set of potential results of a discarded-value expression to which
16636     //      the lvalue-to-rvalue conversion is not applied
16637     //
16638     // We check the first bullet and the "potentially-evaluated" condition in
16639     // BuildDeclRefExpr. We check the type requirements in the second bullet
16640     // in CheckLValueToRValueConversionOperand below.
16641     switch (NOUR) {
16642     case NOUR_None:
16643     case NOUR_Unevaluated:
16644       llvm_unreachable("unexpected non-odr-use-reason");
16645 
16646     case NOUR_Constant:
16647       // Constant references were handled when they were built.
16648       if (VD->getType()->isReferenceType())
16649         return true;
16650       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16651         if (RD->hasMutableFields())
16652           return true;
16653       if (!VD->isUsableInConstantExpressions(S.Context))
16654         return true;
16655       break;
16656 
16657     case NOUR_Discarded:
16658       if (VD->getType()->isReferenceType())
16659         return true;
16660       break;
16661     }
16662     return false;
16663   };
16664 
16665   // Mark that this expression does not constitute an odr-use.
16666   auto MarkNotOdrUsed = [&] {
16667     S.MaybeODRUseExprs.erase(E);
16668     if (LambdaScopeInfo *LSI = S.getCurLambda())
16669       LSI->markVariableExprAsNonODRUsed(E);
16670   };
16671 
16672   // C++2a [basic.def.odr]p2:
16673   //   The set of potential results of an expression e is defined as follows:
16674   switch (E->getStmtClass()) {
16675   //   -- If e is an id-expression, ...
16676   case Expr::DeclRefExprClass: {
16677     auto *DRE = cast<DeclRefExpr>(E);
16678     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16679       break;
16680 
16681     // Rebuild as a non-odr-use DeclRefExpr.
16682     MarkNotOdrUsed();
16683     return DeclRefExpr::Create(
16684         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16685         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16686         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16687         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16688   }
16689 
16690   case Expr::FunctionParmPackExprClass: {
16691     auto *FPPE = cast<FunctionParmPackExpr>(E);
16692     // If any of the declarations in the pack is odr-used, then the expression
16693     // as a whole constitutes an odr-use.
16694     for (VarDecl *D : *FPPE)
16695       if (IsPotentialResultOdrUsed(D))
16696         return ExprEmpty();
16697 
16698     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16699     // nothing cares about whether we marked this as an odr-use, but it might
16700     // be useful for non-compiler tools.
16701     MarkNotOdrUsed();
16702     break;
16703   }
16704 
16705   //   -- If e is a subscripting operation with an array operand...
16706   case Expr::ArraySubscriptExprClass: {
16707     auto *ASE = cast<ArraySubscriptExpr>(E);
16708     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16709     if (!OldBase->getType()->isArrayType())
16710       break;
16711     ExprResult Base = Rebuild(OldBase);
16712     if (!Base.isUsable())
16713       return Base;
16714     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16715     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16716     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16717     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16718                                      ASE->getRBracketLoc());
16719   }
16720 
16721   case Expr::MemberExprClass: {
16722     auto *ME = cast<MemberExpr>(E);
16723     // -- If e is a class member access expression [...] naming a non-static
16724     //    data member...
16725     if (isa<FieldDecl>(ME->getMemberDecl())) {
16726       ExprResult Base = Rebuild(ME->getBase());
16727       if (!Base.isUsable())
16728         return Base;
16729       return MemberExpr::Create(
16730           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16731           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16732           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16733           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16734           ME->getObjectKind(), ME->isNonOdrUse());
16735     }
16736 
16737     if (ME->getMemberDecl()->isCXXInstanceMember())
16738       break;
16739 
16740     // -- If e is a class member access expression naming a static data member,
16741     //    ...
16742     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16743       break;
16744 
16745     // Rebuild as a non-odr-use MemberExpr.
16746     MarkNotOdrUsed();
16747     return MemberExpr::Create(
16748         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16749         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16750         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16751         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16752     return ExprEmpty();
16753   }
16754 
16755   case Expr::BinaryOperatorClass: {
16756     auto *BO = cast<BinaryOperator>(E);
16757     Expr *LHS = BO->getLHS();
16758     Expr *RHS = BO->getRHS();
16759     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16760     if (BO->getOpcode() == BO_PtrMemD) {
16761       ExprResult Sub = Rebuild(LHS);
16762       if (!Sub.isUsable())
16763         return Sub;
16764       LHS = Sub.get();
16765     //   -- If e is a comma expression, ...
16766     } else if (BO->getOpcode() == BO_Comma) {
16767       ExprResult Sub = Rebuild(RHS);
16768       if (!Sub.isUsable())
16769         return Sub;
16770       RHS = Sub.get();
16771     } else {
16772       break;
16773     }
16774     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16775                         LHS, RHS);
16776   }
16777 
16778   //   -- If e has the form (e1)...
16779   case Expr::ParenExprClass: {
16780     auto *PE = cast<ParenExpr>(E);
16781     ExprResult Sub = Rebuild(PE->getSubExpr());
16782     if (!Sub.isUsable())
16783       return Sub;
16784     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16785   }
16786 
16787   //   -- If e is a glvalue conditional expression, ...
16788   // We don't apply this to a binary conditional operator. FIXME: Should we?
16789   case Expr::ConditionalOperatorClass: {
16790     auto *CO = cast<ConditionalOperator>(E);
16791     ExprResult LHS = Rebuild(CO->getLHS());
16792     if (LHS.isInvalid())
16793       return ExprError();
16794     ExprResult RHS = Rebuild(CO->getRHS());
16795     if (RHS.isInvalid())
16796       return ExprError();
16797     if (!LHS.isUsable() && !RHS.isUsable())
16798       return ExprEmpty();
16799     if (!LHS.isUsable())
16800       LHS = CO->getLHS();
16801     if (!RHS.isUsable())
16802       RHS = CO->getRHS();
16803     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16804                                 CO->getCond(), LHS.get(), RHS.get());
16805   }
16806 
16807   // [Clang extension]
16808   //   -- If e has the form __extension__ e1...
16809   case Expr::UnaryOperatorClass: {
16810     auto *UO = cast<UnaryOperator>(E);
16811     if (UO->getOpcode() != UO_Extension)
16812       break;
16813     ExprResult Sub = Rebuild(UO->getSubExpr());
16814     if (!Sub.isUsable())
16815       return Sub;
16816     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16817                           Sub.get());
16818   }
16819 
16820   // [Clang extension]
16821   //   -- If e has the form _Generic(...), the set of potential results is the
16822   //      union of the sets of potential results of the associated expressions.
16823   case Expr::GenericSelectionExprClass: {
16824     auto *GSE = cast<GenericSelectionExpr>(E);
16825 
16826     SmallVector<Expr *, 4> AssocExprs;
16827     bool AnyChanged = false;
16828     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16829       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16830       if (AssocExpr.isInvalid())
16831         return ExprError();
16832       if (AssocExpr.isUsable()) {
16833         AssocExprs.push_back(AssocExpr.get());
16834         AnyChanged = true;
16835       } else {
16836         AssocExprs.push_back(OrigAssocExpr);
16837       }
16838     }
16839 
16840     return AnyChanged ? S.CreateGenericSelectionExpr(
16841                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16842                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16843                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16844                       : ExprEmpty();
16845   }
16846 
16847   // [Clang extension]
16848   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16849   //      results is the union of the sets of potential results of the
16850   //      second and third subexpressions.
16851   case Expr::ChooseExprClass: {
16852     auto *CE = cast<ChooseExpr>(E);
16853 
16854     ExprResult LHS = Rebuild(CE->getLHS());
16855     if (LHS.isInvalid())
16856       return ExprError();
16857 
16858     ExprResult RHS = Rebuild(CE->getLHS());
16859     if (RHS.isInvalid())
16860       return ExprError();
16861 
16862     if (!LHS.get() && !RHS.get())
16863       return ExprEmpty();
16864     if (!LHS.isUsable())
16865       LHS = CE->getLHS();
16866     if (!RHS.isUsable())
16867       RHS = CE->getRHS();
16868 
16869     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16870                              RHS.get(), CE->getRParenLoc());
16871   }
16872 
16873   // Step through non-syntactic nodes.
16874   case Expr::ConstantExprClass: {
16875     auto *CE = cast<ConstantExpr>(E);
16876     ExprResult Sub = Rebuild(CE->getSubExpr());
16877     if (!Sub.isUsable())
16878       return Sub;
16879     return ConstantExpr::Create(S.Context, Sub.get());
16880   }
16881 
16882   // We could mostly rely on the recursive rebuilding to rebuild implicit
16883   // casts, but not at the top level, so rebuild them here.
16884   case Expr::ImplicitCastExprClass: {
16885     auto *ICE = cast<ImplicitCastExpr>(E);
16886     // Only step through the narrow set of cast kinds we expect to encounter.
16887     // Anything else suggests we've left the region in which potential results
16888     // can be found.
16889     switch (ICE->getCastKind()) {
16890     case CK_NoOp:
16891     case CK_DerivedToBase:
16892     case CK_UncheckedDerivedToBase: {
16893       ExprResult Sub = Rebuild(ICE->getSubExpr());
16894       if (!Sub.isUsable())
16895         return Sub;
16896       CXXCastPath Path(ICE->path());
16897       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16898                                  ICE->getValueKind(), &Path);
16899     }
16900 
16901     default:
16902       break;
16903     }
16904     break;
16905   }
16906 
16907   default:
16908     break;
16909   }
16910 
16911   // Can't traverse through this node. Nothing to do.
16912   return ExprEmpty();
16913 }
16914 
16915 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16916   // Check whether the operand is or contains an object of non-trivial C union
16917   // type.
16918   if (E->getType().isVolatileQualified() &&
16919       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16920        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16921     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16922                           Sema::NTCUC_LValueToRValueVolatile,
16923                           NTCUK_Destruct|NTCUK_Copy);
16924 
16925   // C++2a [basic.def.odr]p4:
16926   //   [...] an expression of non-volatile-qualified non-class type to which
16927   //   the lvalue-to-rvalue conversion is applied [...]
16928   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16929     return E;
16930 
16931   ExprResult Result =
16932       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16933   if (Result.isInvalid())
16934     return ExprError();
16935   return Result.get() ? Result : E;
16936 }
16937 
16938 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16939   Res = CorrectDelayedTyposInExpr(Res);
16940 
16941   if (!Res.isUsable())
16942     return Res;
16943 
16944   // If a constant-expression is a reference to a variable where we delay
16945   // deciding whether it is an odr-use, just assume we will apply the
16946   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16947   // (a non-type template argument), we have special handling anyway.
16948   return CheckLValueToRValueConversionOperand(Res.get());
16949 }
16950 
16951 void Sema::CleanupVarDeclMarking() {
16952   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16953   // call.
16954   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16955   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16956 
16957   for (Expr *E : LocalMaybeODRUseExprs) {
16958     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16959       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16960                          DRE->getLocation(), *this);
16961     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16962       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16963                          *this);
16964     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16965       for (VarDecl *VD : *FP)
16966         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16967     } else {
16968       llvm_unreachable("Unexpected expression");
16969     }
16970   }
16971 
16972   assert(MaybeODRUseExprs.empty() &&
16973          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16974 }
16975 
16976 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16977                                     VarDecl *Var, Expr *E) {
16978   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16979           isa<FunctionParmPackExpr>(E)) &&
16980          "Invalid Expr argument to DoMarkVarDeclReferenced");
16981   Var->setReferenced();
16982 
16983   if (Var->isInvalidDecl())
16984     return;
16985 
16986   auto *MSI = Var->getMemberSpecializationInfo();
16987   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16988                                        : Var->getTemplateSpecializationKind();
16989 
16990   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16991   bool UsableInConstantExpr =
16992       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16993 
16994   // C++20 [expr.const]p12:
16995   //   A variable [...] is needed for constant evaluation if it is [...] a
16996   //   variable whose name appears as a potentially constant evaluated
16997   //   expression that is either a contexpr variable or is of non-volatile
16998   //   const-qualified integral type or of reference type
16999   bool NeededForConstantEvaluation =
17000       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17001 
17002   bool NeedDefinition =
17003       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17004 
17005   VarTemplateSpecializationDecl *VarSpec =
17006       dyn_cast<VarTemplateSpecializationDecl>(Var);
17007   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17008          "Can't instantiate a partial template specialization.");
17009 
17010   // If this might be a member specialization of a static data member, check
17011   // the specialization is visible. We already did the checks for variable
17012   // template specializations when we created them.
17013   if (NeedDefinition && TSK != TSK_Undeclared &&
17014       !isa<VarTemplateSpecializationDecl>(Var))
17015     SemaRef.checkSpecializationVisibility(Loc, Var);
17016 
17017   // Perform implicit instantiation of static data members, static data member
17018   // templates of class templates, and variable template specializations. Delay
17019   // instantiations of variable templates, except for those that could be used
17020   // in a constant expression.
17021   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17022     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17023     // instantiation declaration if a variable is usable in a constant
17024     // expression (among other cases).
17025     bool TryInstantiating =
17026         TSK == TSK_ImplicitInstantiation ||
17027         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17028 
17029     if (TryInstantiating) {
17030       SourceLocation PointOfInstantiation =
17031           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17032       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17033       if (FirstInstantiation) {
17034         PointOfInstantiation = Loc;
17035         if (MSI)
17036           MSI->setPointOfInstantiation(PointOfInstantiation);
17037         else
17038           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17039       }
17040 
17041       bool InstantiationDependent = false;
17042       bool IsNonDependent =
17043           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17044                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17045                   : true;
17046 
17047       // Do not instantiate specializations that are still type-dependent.
17048       if (IsNonDependent) {
17049         if (UsableInConstantExpr) {
17050           // Do not defer instantiations of variables that could be used in a
17051           // constant expression.
17052           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17053             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17054           });
17055         } else if (FirstInstantiation ||
17056                    isa<VarTemplateSpecializationDecl>(Var)) {
17057           // FIXME: For a specialization of a variable template, we don't
17058           // distinguish between "declaration and type implicitly instantiated"
17059           // and "implicit instantiation of definition requested", so we have
17060           // no direct way to avoid enqueueing the pending instantiation
17061           // multiple times.
17062           SemaRef.PendingInstantiations
17063               .push_back(std::make_pair(Var, PointOfInstantiation));
17064         }
17065       }
17066     }
17067   }
17068 
17069   // C++2a [basic.def.odr]p4:
17070   //   A variable x whose name appears as a potentially-evaluated expression e
17071   //   is odr-used by e unless
17072   //   -- x is a reference that is usable in constant expressions
17073   //   -- x is a variable of non-reference type that is usable in constant
17074   //      expressions and has no mutable subobjects [FIXME], and e is an
17075   //      element of the set of potential results of an expression of
17076   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17077   //      conversion is applied
17078   //   -- x is a variable of non-reference type, and e is an element of the set
17079   //      of potential results of a discarded-value expression to which the
17080   //      lvalue-to-rvalue conversion is not applied [FIXME]
17081   //
17082   // We check the first part of the second bullet here, and
17083   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17084   // FIXME: To get the third bullet right, we need to delay this even for
17085   // variables that are not usable in constant expressions.
17086 
17087   // If we already know this isn't an odr-use, there's nothing more to do.
17088   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17089     if (DRE->isNonOdrUse())
17090       return;
17091   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17092     if (ME->isNonOdrUse())
17093       return;
17094 
17095   switch (OdrUse) {
17096   case OdrUseContext::None:
17097     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17098            "missing non-odr-use marking for unevaluated decl ref");
17099     break;
17100 
17101   case OdrUseContext::FormallyOdrUsed:
17102     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17103     // behavior.
17104     break;
17105 
17106   case OdrUseContext::Used:
17107     // If we might later find that this expression isn't actually an odr-use,
17108     // delay the marking.
17109     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17110       SemaRef.MaybeODRUseExprs.insert(E);
17111     else
17112       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17113     break;
17114 
17115   case OdrUseContext::Dependent:
17116     // If this is a dependent context, we don't need to mark variables as
17117     // odr-used, but we may still need to track them for lambda capture.
17118     // FIXME: Do we also need to do this inside dependent typeid expressions
17119     // (which are modeled as unevaluated at this point)?
17120     const bool RefersToEnclosingScope =
17121         (SemaRef.CurContext != Var->getDeclContext() &&
17122          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17123     if (RefersToEnclosingScope) {
17124       LambdaScopeInfo *const LSI =
17125           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17126       if (LSI && (!LSI->CallOperator ||
17127                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17128         // If a variable could potentially be odr-used, defer marking it so
17129         // until we finish analyzing the full expression for any
17130         // lvalue-to-rvalue
17131         // or discarded value conversions that would obviate odr-use.
17132         // Add it to the list of potential captures that will be analyzed
17133         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17134         // unless the variable is a reference that was initialized by a constant
17135         // expression (this will never need to be captured or odr-used).
17136         //
17137         // FIXME: We can simplify this a lot after implementing P0588R1.
17138         assert(E && "Capture variable should be used in an expression.");
17139         if (!Var->getType()->isReferenceType() ||
17140             !Var->isUsableInConstantExpressions(SemaRef.Context))
17141           LSI->addPotentialCapture(E->IgnoreParens());
17142       }
17143     }
17144     break;
17145   }
17146 }
17147 
17148 /// Mark a variable referenced, and check whether it is odr-used
17149 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17150 /// used directly for normal expressions referring to VarDecl.
17151 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17152   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17153 }
17154 
17155 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17156                                Decl *D, Expr *E, bool MightBeOdrUse) {
17157   if (SemaRef.isInOpenMPDeclareTargetContext())
17158     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17159 
17160   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17161     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17162     return;
17163   }
17164 
17165   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17166 
17167   // If this is a call to a method via a cast, also mark the method in the
17168   // derived class used in case codegen can devirtualize the call.
17169   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17170   if (!ME)
17171     return;
17172   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17173   if (!MD)
17174     return;
17175   // Only attempt to devirtualize if this is truly a virtual call.
17176   bool IsVirtualCall = MD->isVirtual() &&
17177                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17178   if (!IsVirtualCall)
17179     return;
17180 
17181   // If it's possible to devirtualize the call, mark the called function
17182   // referenced.
17183   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17184       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17185   if (DM)
17186     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17187 }
17188 
17189 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17190 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17191   // TODO: update this with DR# once a defect report is filed.
17192   // C++11 defect. The address of a pure member should not be an ODR use, even
17193   // if it's a qualified reference.
17194   bool OdrUse = true;
17195   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17196     if (Method->isVirtual() &&
17197         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17198       OdrUse = false;
17199 
17200   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17201     if (!isConstantEvaluated() && FD->isConsteval() &&
17202         !RebuildingImmediateInvocation)
17203       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17204   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17205 }
17206 
17207 /// Perform reference-marking and odr-use handling for a MemberExpr.
17208 void Sema::MarkMemberReferenced(MemberExpr *E) {
17209   // C++11 [basic.def.odr]p2:
17210   //   A non-overloaded function whose name appears as a potentially-evaluated
17211   //   expression or a member of a set of candidate functions, if selected by
17212   //   overload resolution when referred to from a potentially-evaluated
17213   //   expression, is odr-used, unless it is a pure virtual function and its
17214   //   name is not explicitly qualified.
17215   bool MightBeOdrUse = true;
17216   if (E->performsVirtualDispatch(getLangOpts())) {
17217     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17218       if (Method->isPure())
17219         MightBeOdrUse = false;
17220   }
17221   SourceLocation Loc =
17222       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17223   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17224 }
17225 
17226 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17227 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17228   for (VarDecl *VD : *E)
17229     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17230 }
17231 
17232 /// Perform marking for a reference to an arbitrary declaration.  It
17233 /// marks the declaration referenced, and performs odr-use checking for
17234 /// functions and variables. This method should not be used when building a
17235 /// normal expression which refers to a variable.
17236 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17237                                  bool MightBeOdrUse) {
17238   if (MightBeOdrUse) {
17239     if (auto *VD = dyn_cast<VarDecl>(D)) {
17240       MarkVariableReferenced(Loc, VD);
17241       return;
17242     }
17243   }
17244   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17245     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17246     return;
17247   }
17248   D->setReferenced();
17249 }
17250 
17251 namespace {
17252   // Mark all of the declarations used by a type as referenced.
17253   // FIXME: Not fully implemented yet! We need to have a better understanding
17254   // of when we're entering a context we should not recurse into.
17255   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17256   // TreeTransforms rebuilding the type in a new context. Rather than
17257   // duplicating the TreeTransform logic, we should consider reusing it here.
17258   // Currently that causes problems when rebuilding LambdaExprs.
17259   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17260     Sema &S;
17261     SourceLocation Loc;
17262 
17263   public:
17264     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17265 
17266     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17267 
17268     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17269   };
17270 }
17271 
17272 bool MarkReferencedDecls::TraverseTemplateArgument(
17273     const TemplateArgument &Arg) {
17274   {
17275     // A non-type template argument is a constant-evaluated context.
17276     EnterExpressionEvaluationContext Evaluated(
17277         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17278     if (Arg.getKind() == TemplateArgument::Declaration) {
17279       if (Decl *D = Arg.getAsDecl())
17280         S.MarkAnyDeclReferenced(Loc, D, true);
17281     } else if (Arg.getKind() == TemplateArgument::Expression) {
17282       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17283     }
17284   }
17285 
17286   return Inherited::TraverseTemplateArgument(Arg);
17287 }
17288 
17289 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17290   MarkReferencedDecls Marker(*this, Loc);
17291   Marker.TraverseType(T);
17292 }
17293 
17294 namespace {
17295 /// Helper class that marks all of the declarations referenced by
17296 /// potentially-evaluated subexpressions as "referenced".
17297 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
17298 public:
17299   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
17300   bool SkipLocalVariables;
17301 
17302   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17303       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
17304 
17305   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17306     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
17307   }
17308 
17309   void VisitDeclRefExpr(DeclRefExpr *E) {
17310     // If we were asked not to visit local variables, don't.
17311     if (SkipLocalVariables) {
17312       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17313         if (VD->hasLocalStorage())
17314           return;
17315     }
17316     S.MarkDeclRefReferenced(E);
17317   }
17318 
17319   void VisitMemberExpr(MemberExpr *E) { S.MarkMemberReferenced(E); }
17320 };
17321 } // namespace
17322 
17323 /// Mark any declarations that appear within this expression or any
17324 /// potentially-evaluated subexpressions as "referenced".
17325 ///
17326 /// \param SkipLocalVariables If true, don't mark local variables as
17327 /// 'referenced'.
17328 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17329                                             bool SkipLocalVariables) {
17330   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17331 }
17332 
17333 /// Emit a diagnostic that describes an effect on the run-time behavior
17334 /// of the program being compiled.
17335 ///
17336 /// This routine emits the given diagnostic when the code currently being
17337 /// type-checked is "potentially evaluated", meaning that there is a
17338 /// possibility that the code will actually be executable. Code in sizeof()
17339 /// expressions, code used only during overload resolution, etc., are not
17340 /// potentially evaluated. This routine will suppress such diagnostics or,
17341 /// in the absolutely nutty case of potentially potentially evaluated
17342 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17343 /// later.
17344 ///
17345 /// This routine should be used for all diagnostics that describe the run-time
17346 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17347 /// Failure to do so will likely result in spurious diagnostics or failures
17348 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17349 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17350                                const PartialDiagnostic &PD) {
17351   switch (ExprEvalContexts.back().Context) {
17352   case ExpressionEvaluationContext::Unevaluated:
17353   case ExpressionEvaluationContext::UnevaluatedList:
17354   case ExpressionEvaluationContext::UnevaluatedAbstract:
17355   case ExpressionEvaluationContext::DiscardedStatement:
17356     // The argument will never be evaluated, so don't complain.
17357     break;
17358 
17359   case ExpressionEvaluationContext::ConstantEvaluated:
17360     // Relevant diagnostics should be produced by constant evaluation.
17361     break;
17362 
17363   case ExpressionEvaluationContext::PotentiallyEvaluated:
17364   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17365     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17366       FunctionScopes.back()->PossiblyUnreachableDiags.
17367         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17368       return true;
17369     }
17370 
17371     // The initializer of a constexpr variable or of the first declaration of a
17372     // static data member is not syntactically a constant evaluated constant,
17373     // but nonetheless is always required to be a constant expression, so we
17374     // can skip diagnosing.
17375     // FIXME: Using the mangling context here is a hack.
17376     if (auto *VD = dyn_cast_or_null<VarDecl>(
17377             ExprEvalContexts.back().ManglingContextDecl)) {
17378       if (VD->isConstexpr() ||
17379           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17380         break;
17381       // FIXME: For any other kind of variable, we should build a CFG for its
17382       // initializer and check whether the context in question is reachable.
17383     }
17384 
17385     Diag(Loc, PD);
17386     return true;
17387   }
17388 
17389   return false;
17390 }
17391 
17392 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17393                                const PartialDiagnostic &PD) {
17394   return DiagRuntimeBehavior(
17395       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17396 }
17397 
17398 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17399                                CallExpr *CE, FunctionDecl *FD) {
17400   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17401     return false;
17402 
17403   // If we're inside a decltype's expression, don't check for a valid return
17404   // type or construct temporaries until we know whether this is the last call.
17405   if (ExprEvalContexts.back().ExprContext ==
17406       ExpressionEvaluationContextRecord::EK_Decltype) {
17407     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17408     return false;
17409   }
17410 
17411   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17412     FunctionDecl *FD;
17413     CallExpr *CE;
17414 
17415   public:
17416     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17417       : FD(FD), CE(CE) { }
17418 
17419     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17420       if (!FD) {
17421         S.Diag(Loc, diag::err_call_incomplete_return)
17422           << T << CE->getSourceRange();
17423         return;
17424       }
17425 
17426       S.Diag(Loc, diag::err_call_function_incomplete_return)
17427         << CE->getSourceRange() << FD->getDeclName() << T;
17428       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17429           << FD->getDeclName();
17430     }
17431   } Diagnoser(FD, CE);
17432 
17433   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17434     return true;
17435 
17436   return false;
17437 }
17438 
17439 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17440 // will prevent this condition from triggering, which is what we want.
17441 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17442   SourceLocation Loc;
17443 
17444   unsigned diagnostic = diag::warn_condition_is_assignment;
17445   bool IsOrAssign = false;
17446 
17447   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17448     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17449       return;
17450 
17451     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17452 
17453     // Greylist some idioms by putting them into a warning subcategory.
17454     if (ObjCMessageExpr *ME
17455           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17456       Selector Sel = ME->getSelector();
17457 
17458       // self = [<foo> init...]
17459       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17460         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17461 
17462       // <foo> = [<bar> nextObject]
17463       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17464         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17465     }
17466 
17467     Loc = Op->getOperatorLoc();
17468   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17469     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17470       return;
17471 
17472     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17473     Loc = Op->getOperatorLoc();
17474   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17475     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17476   else {
17477     // Not an assignment.
17478     return;
17479   }
17480 
17481   Diag(Loc, diagnostic) << E->getSourceRange();
17482 
17483   SourceLocation Open = E->getBeginLoc();
17484   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17485   Diag(Loc, diag::note_condition_assign_silence)
17486         << FixItHint::CreateInsertion(Open, "(")
17487         << FixItHint::CreateInsertion(Close, ")");
17488 
17489   if (IsOrAssign)
17490     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17491       << FixItHint::CreateReplacement(Loc, "!=");
17492   else
17493     Diag(Loc, diag::note_condition_assign_to_comparison)
17494       << FixItHint::CreateReplacement(Loc, "==");
17495 }
17496 
17497 /// Redundant parentheses over an equality comparison can indicate
17498 /// that the user intended an assignment used as condition.
17499 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17500   // Don't warn if the parens came from a macro.
17501   SourceLocation parenLoc = ParenE->getBeginLoc();
17502   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17503     return;
17504   // Don't warn for dependent expressions.
17505   if (ParenE->isTypeDependent())
17506     return;
17507 
17508   Expr *E = ParenE->IgnoreParens();
17509 
17510   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17511     if (opE->getOpcode() == BO_EQ &&
17512         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17513                                                            == Expr::MLV_Valid) {
17514       SourceLocation Loc = opE->getOperatorLoc();
17515 
17516       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17517       SourceRange ParenERange = ParenE->getSourceRange();
17518       Diag(Loc, diag::note_equality_comparison_silence)
17519         << FixItHint::CreateRemoval(ParenERange.getBegin())
17520         << FixItHint::CreateRemoval(ParenERange.getEnd());
17521       Diag(Loc, diag::note_equality_comparison_to_assign)
17522         << FixItHint::CreateReplacement(Loc, "=");
17523     }
17524 }
17525 
17526 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17527                                        bool IsConstexpr) {
17528   DiagnoseAssignmentAsCondition(E);
17529   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17530     DiagnoseEqualityWithExtraParens(parenE);
17531 
17532   ExprResult result = CheckPlaceholderExpr(E);
17533   if (result.isInvalid()) return ExprError();
17534   E = result.get();
17535 
17536   if (!E->isTypeDependent()) {
17537     if (getLangOpts().CPlusPlus)
17538       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17539 
17540     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17541     if (ERes.isInvalid())
17542       return ExprError();
17543     E = ERes.get();
17544 
17545     QualType T = E->getType();
17546     if (!T->isScalarType()) { // C99 6.8.4.1p1
17547       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17548         << T << E->getSourceRange();
17549       return ExprError();
17550     }
17551     CheckBoolLikeConversion(E, Loc);
17552   }
17553 
17554   return E;
17555 }
17556 
17557 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17558                                            Expr *SubExpr, ConditionKind CK) {
17559   // Empty conditions are valid in for-statements.
17560   if (!SubExpr)
17561     return ConditionResult();
17562 
17563   ExprResult Cond;
17564   switch (CK) {
17565   case ConditionKind::Boolean:
17566     Cond = CheckBooleanCondition(Loc, SubExpr);
17567     break;
17568 
17569   case ConditionKind::ConstexprIf:
17570     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17571     break;
17572 
17573   case ConditionKind::Switch:
17574     Cond = CheckSwitchCondition(Loc, SubExpr);
17575     break;
17576   }
17577   if (Cond.isInvalid())
17578     return ConditionError();
17579 
17580   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17581   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17582   if (!FullExpr.get())
17583     return ConditionError();
17584 
17585   return ConditionResult(*this, nullptr, FullExpr,
17586                          CK == ConditionKind::ConstexprIf);
17587 }
17588 
17589 namespace {
17590   /// A visitor for rebuilding a call to an __unknown_any expression
17591   /// to have an appropriate type.
17592   struct RebuildUnknownAnyFunction
17593     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17594 
17595     Sema &S;
17596 
17597     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17598 
17599     ExprResult VisitStmt(Stmt *S) {
17600       llvm_unreachable("unexpected statement!");
17601     }
17602 
17603     ExprResult VisitExpr(Expr *E) {
17604       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17605         << E->getSourceRange();
17606       return ExprError();
17607     }
17608 
17609     /// Rebuild an expression which simply semantically wraps another
17610     /// expression which it shares the type and value kind of.
17611     template <class T> ExprResult rebuildSugarExpr(T *E) {
17612       ExprResult SubResult = Visit(E->getSubExpr());
17613       if (SubResult.isInvalid()) return ExprError();
17614 
17615       Expr *SubExpr = SubResult.get();
17616       E->setSubExpr(SubExpr);
17617       E->setType(SubExpr->getType());
17618       E->setValueKind(SubExpr->getValueKind());
17619       assert(E->getObjectKind() == OK_Ordinary);
17620       return E;
17621     }
17622 
17623     ExprResult VisitParenExpr(ParenExpr *E) {
17624       return rebuildSugarExpr(E);
17625     }
17626 
17627     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17628       return rebuildSugarExpr(E);
17629     }
17630 
17631     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17632       ExprResult SubResult = Visit(E->getSubExpr());
17633       if (SubResult.isInvalid()) return ExprError();
17634 
17635       Expr *SubExpr = SubResult.get();
17636       E->setSubExpr(SubExpr);
17637       E->setType(S.Context.getPointerType(SubExpr->getType()));
17638       assert(E->getValueKind() == VK_RValue);
17639       assert(E->getObjectKind() == OK_Ordinary);
17640       return E;
17641     }
17642 
17643     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17644       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17645 
17646       E->setType(VD->getType());
17647 
17648       assert(E->getValueKind() == VK_RValue);
17649       if (S.getLangOpts().CPlusPlus &&
17650           !(isa<CXXMethodDecl>(VD) &&
17651             cast<CXXMethodDecl>(VD)->isInstance()))
17652         E->setValueKind(VK_LValue);
17653 
17654       return E;
17655     }
17656 
17657     ExprResult VisitMemberExpr(MemberExpr *E) {
17658       return resolveDecl(E, E->getMemberDecl());
17659     }
17660 
17661     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17662       return resolveDecl(E, E->getDecl());
17663     }
17664   };
17665 }
17666 
17667 /// Given a function expression of unknown-any type, try to rebuild it
17668 /// to have a function type.
17669 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17670   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17671   if (Result.isInvalid()) return ExprError();
17672   return S.DefaultFunctionArrayConversion(Result.get());
17673 }
17674 
17675 namespace {
17676   /// A visitor for rebuilding an expression of type __unknown_anytype
17677   /// into one which resolves the type directly on the referring
17678   /// expression.  Strict preservation of the original source
17679   /// structure is not a goal.
17680   struct RebuildUnknownAnyExpr
17681     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17682 
17683     Sema &S;
17684 
17685     /// The current destination type.
17686     QualType DestType;
17687 
17688     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17689       : S(S), DestType(CastType) {}
17690 
17691     ExprResult VisitStmt(Stmt *S) {
17692       llvm_unreachable("unexpected statement!");
17693     }
17694 
17695     ExprResult VisitExpr(Expr *E) {
17696       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17697         << E->getSourceRange();
17698       return ExprError();
17699     }
17700 
17701     ExprResult VisitCallExpr(CallExpr *E);
17702     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17703 
17704     /// Rebuild an expression which simply semantically wraps another
17705     /// expression which it shares the type and value kind of.
17706     template <class T> ExprResult rebuildSugarExpr(T *E) {
17707       ExprResult SubResult = Visit(E->getSubExpr());
17708       if (SubResult.isInvalid()) return ExprError();
17709       Expr *SubExpr = SubResult.get();
17710       E->setSubExpr(SubExpr);
17711       E->setType(SubExpr->getType());
17712       E->setValueKind(SubExpr->getValueKind());
17713       assert(E->getObjectKind() == OK_Ordinary);
17714       return E;
17715     }
17716 
17717     ExprResult VisitParenExpr(ParenExpr *E) {
17718       return rebuildSugarExpr(E);
17719     }
17720 
17721     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17722       return rebuildSugarExpr(E);
17723     }
17724 
17725     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17726       const PointerType *Ptr = DestType->getAs<PointerType>();
17727       if (!Ptr) {
17728         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17729           << E->getSourceRange();
17730         return ExprError();
17731       }
17732 
17733       if (isa<CallExpr>(E->getSubExpr())) {
17734         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17735           << E->getSourceRange();
17736         return ExprError();
17737       }
17738 
17739       assert(E->getValueKind() == VK_RValue);
17740       assert(E->getObjectKind() == OK_Ordinary);
17741       E->setType(DestType);
17742 
17743       // Build the sub-expression as if it were an object of the pointee type.
17744       DestType = Ptr->getPointeeType();
17745       ExprResult SubResult = Visit(E->getSubExpr());
17746       if (SubResult.isInvalid()) return ExprError();
17747       E->setSubExpr(SubResult.get());
17748       return E;
17749     }
17750 
17751     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17752 
17753     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17754 
17755     ExprResult VisitMemberExpr(MemberExpr *E) {
17756       return resolveDecl(E, E->getMemberDecl());
17757     }
17758 
17759     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17760       return resolveDecl(E, E->getDecl());
17761     }
17762   };
17763 }
17764 
17765 /// Rebuilds a call expression which yielded __unknown_anytype.
17766 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17767   Expr *CalleeExpr = E->getCallee();
17768 
17769   enum FnKind {
17770     FK_MemberFunction,
17771     FK_FunctionPointer,
17772     FK_BlockPointer
17773   };
17774 
17775   FnKind Kind;
17776   QualType CalleeType = CalleeExpr->getType();
17777   if (CalleeType == S.Context.BoundMemberTy) {
17778     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17779     Kind = FK_MemberFunction;
17780     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17781   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17782     CalleeType = Ptr->getPointeeType();
17783     Kind = FK_FunctionPointer;
17784   } else {
17785     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17786     Kind = FK_BlockPointer;
17787   }
17788   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17789 
17790   // Verify that this is a legal result type of a function.
17791   if (DestType->isArrayType() || DestType->isFunctionType()) {
17792     unsigned diagID = diag::err_func_returning_array_function;
17793     if (Kind == FK_BlockPointer)
17794       diagID = diag::err_block_returning_array_function;
17795 
17796     S.Diag(E->getExprLoc(), diagID)
17797       << DestType->isFunctionType() << DestType;
17798     return ExprError();
17799   }
17800 
17801   // Otherwise, go ahead and set DestType as the call's result.
17802   E->setType(DestType.getNonLValueExprType(S.Context));
17803   E->setValueKind(Expr::getValueKindForType(DestType));
17804   assert(E->getObjectKind() == OK_Ordinary);
17805 
17806   // Rebuild the function type, replacing the result type with DestType.
17807   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17808   if (Proto) {
17809     // __unknown_anytype(...) is a special case used by the debugger when
17810     // it has no idea what a function's signature is.
17811     //
17812     // We want to build this call essentially under the K&R
17813     // unprototyped rules, but making a FunctionNoProtoType in C++
17814     // would foul up all sorts of assumptions.  However, we cannot
17815     // simply pass all arguments as variadic arguments, nor can we
17816     // portably just call the function under a non-variadic type; see
17817     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17818     // However, it turns out that in practice it is generally safe to
17819     // call a function declared as "A foo(B,C,D);" under the prototype
17820     // "A foo(B,C,D,...);".  The only known exception is with the
17821     // Windows ABI, where any variadic function is implicitly cdecl
17822     // regardless of its normal CC.  Therefore we change the parameter
17823     // types to match the types of the arguments.
17824     //
17825     // This is a hack, but it is far superior to moving the
17826     // corresponding target-specific code from IR-gen to Sema/AST.
17827 
17828     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17829     SmallVector<QualType, 8> ArgTypes;
17830     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17831       ArgTypes.reserve(E->getNumArgs());
17832       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17833         Expr *Arg = E->getArg(i);
17834         QualType ArgType = Arg->getType();
17835         if (E->isLValue()) {
17836           ArgType = S.Context.getLValueReferenceType(ArgType);
17837         } else if (E->isXValue()) {
17838           ArgType = S.Context.getRValueReferenceType(ArgType);
17839         }
17840         ArgTypes.push_back(ArgType);
17841       }
17842       ParamTypes = ArgTypes;
17843     }
17844     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17845                                          Proto->getExtProtoInfo());
17846   } else {
17847     DestType = S.Context.getFunctionNoProtoType(DestType,
17848                                                 FnType->getExtInfo());
17849   }
17850 
17851   // Rebuild the appropriate pointer-to-function type.
17852   switch (Kind) {
17853   case FK_MemberFunction:
17854     // Nothing to do.
17855     break;
17856 
17857   case FK_FunctionPointer:
17858     DestType = S.Context.getPointerType(DestType);
17859     break;
17860 
17861   case FK_BlockPointer:
17862     DestType = S.Context.getBlockPointerType(DestType);
17863     break;
17864   }
17865 
17866   // Finally, we can recurse.
17867   ExprResult CalleeResult = Visit(CalleeExpr);
17868   if (!CalleeResult.isUsable()) return ExprError();
17869   E->setCallee(CalleeResult.get());
17870 
17871   // Bind a temporary if necessary.
17872   return S.MaybeBindToTemporary(E);
17873 }
17874 
17875 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17876   // Verify that this is a legal result type of a call.
17877   if (DestType->isArrayType() || DestType->isFunctionType()) {
17878     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17879       << DestType->isFunctionType() << DestType;
17880     return ExprError();
17881   }
17882 
17883   // Rewrite the method result type if available.
17884   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17885     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17886     Method->setReturnType(DestType);
17887   }
17888 
17889   // Change the type of the message.
17890   E->setType(DestType.getNonReferenceType());
17891   E->setValueKind(Expr::getValueKindForType(DestType));
17892 
17893   return S.MaybeBindToTemporary(E);
17894 }
17895 
17896 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17897   // The only case we should ever see here is a function-to-pointer decay.
17898   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17899     assert(E->getValueKind() == VK_RValue);
17900     assert(E->getObjectKind() == OK_Ordinary);
17901 
17902     E->setType(DestType);
17903 
17904     // Rebuild the sub-expression as the pointee (function) type.
17905     DestType = DestType->castAs<PointerType>()->getPointeeType();
17906 
17907     ExprResult Result = Visit(E->getSubExpr());
17908     if (!Result.isUsable()) return ExprError();
17909 
17910     E->setSubExpr(Result.get());
17911     return E;
17912   } else if (E->getCastKind() == CK_LValueToRValue) {
17913     assert(E->getValueKind() == VK_RValue);
17914     assert(E->getObjectKind() == OK_Ordinary);
17915 
17916     assert(isa<BlockPointerType>(E->getType()));
17917 
17918     E->setType(DestType);
17919 
17920     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17921     DestType = S.Context.getLValueReferenceType(DestType);
17922 
17923     ExprResult Result = Visit(E->getSubExpr());
17924     if (!Result.isUsable()) return ExprError();
17925 
17926     E->setSubExpr(Result.get());
17927     return E;
17928   } else {
17929     llvm_unreachable("Unhandled cast type!");
17930   }
17931 }
17932 
17933 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17934   ExprValueKind ValueKind = VK_LValue;
17935   QualType Type = DestType;
17936 
17937   // We know how to make this work for certain kinds of decls:
17938 
17939   //  - functions
17940   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17941     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17942       DestType = Ptr->getPointeeType();
17943       ExprResult Result = resolveDecl(E, VD);
17944       if (Result.isInvalid()) return ExprError();
17945       return S.ImpCastExprToType(Result.get(), Type,
17946                                  CK_FunctionToPointerDecay, VK_RValue);
17947     }
17948 
17949     if (!Type->isFunctionType()) {
17950       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17951         << VD << E->getSourceRange();
17952       return ExprError();
17953     }
17954     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17955       // We must match the FunctionDecl's type to the hack introduced in
17956       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17957       // type. See the lengthy commentary in that routine.
17958       QualType FDT = FD->getType();
17959       const FunctionType *FnType = FDT->castAs<FunctionType>();
17960       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17961       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17962       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17963         SourceLocation Loc = FD->getLocation();
17964         FunctionDecl *NewFD = FunctionDecl::Create(
17965             S.Context, FD->getDeclContext(), Loc, Loc,
17966             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17967             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17968             /*ConstexprKind*/ CSK_unspecified);
17969 
17970         if (FD->getQualifier())
17971           NewFD->setQualifierInfo(FD->getQualifierLoc());
17972 
17973         SmallVector<ParmVarDecl*, 16> Params;
17974         for (const auto &AI : FT->param_types()) {
17975           ParmVarDecl *Param =
17976             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17977           Param->setScopeInfo(0, Params.size());
17978           Params.push_back(Param);
17979         }
17980         NewFD->setParams(Params);
17981         DRE->setDecl(NewFD);
17982         VD = DRE->getDecl();
17983       }
17984     }
17985 
17986     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17987       if (MD->isInstance()) {
17988         ValueKind = VK_RValue;
17989         Type = S.Context.BoundMemberTy;
17990       }
17991 
17992     // Function references aren't l-values in C.
17993     if (!S.getLangOpts().CPlusPlus)
17994       ValueKind = VK_RValue;
17995 
17996   //  - variables
17997   } else if (isa<VarDecl>(VD)) {
17998     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17999       Type = RefTy->getPointeeType();
18000     } else if (Type->isFunctionType()) {
18001       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18002         << VD << E->getSourceRange();
18003       return ExprError();
18004     }
18005 
18006   //  - nothing else
18007   } else {
18008     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18009       << VD << E->getSourceRange();
18010     return ExprError();
18011   }
18012 
18013   // Modifying the declaration like this is friendly to IR-gen but
18014   // also really dangerous.
18015   VD->setType(DestType);
18016   E->setType(Type);
18017   E->setValueKind(ValueKind);
18018   return E;
18019 }
18020 
18021 /// Check a cast of an unknown-any type.  We intentionally only
18022 /// trigger this for C-style casts.
18023 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18024                                      Expr *CastExpr, CastKind &CastKind,
18025                                      ExprValueKind &VK, CXXCastPath &Path) {
18026   // The type we're casting to must be either void or complete.
18027   if (!CastType->isVoidType() &&
18028       RequireCompleteType(TypeRange.getBegin(), CastType,
18029                           diag::err_typecheck_cast_to_incomplete))
18030     return ExprError();
18031 
18032   // Rewrite the casted expression from scratch.
18033   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18034   if (!result.isUsable()) return ExprError();
18035 
18036   CastExpr = result.get();
18037   VK = CastExpr->getValueKind();
18038   CastKind = CK_NoOp;
18039 
18040   return CastExpr;
18041 }
18042 
18043 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18044   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18045 }
18046 
18047 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18048                                     Expr *arg, QualType &paramType) {
18049   // If the syntactic form of the argument is not an explicit cast of
18050   // any sort, just do default argument promotion.
18051   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18052   if (!castArg) {
18053     ExprResult result = DefaultArgumentPromotion(arg);
18054     if (result.isInvalid()) return ExprError();
18055     paramType = result.get()->getType();
18056     return result;
18057   }
18058 
18059   // Otherwise, use the type that was written in the explicit cast.
18060   assert(!arg->hasPlaceholderType());
18061   paramType = castArg->getTypeAsWritten();
18062 
18063   // Copy-initialize a parameter of that type.
18064   InitializedEntity entity =
18065     InitializedEntity::InitializeParameter(Context, paramType,
18066                                            /*consumed*/ false);
18067   return PerformCopyInitialization(entity, callLoc, arg);
18068 }
18069 
18070 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18071   Expr *orig = E;
18072   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18073   while (true) {
18074     E = E->IgnoreParenImpCasts();
18075     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18076       E = call->getCallee();
18077       diagID = diag::err_uncasted_call_of_unknown_any;
18078     } else {
18079       break;
18080     }
18081   }
18082 
18083   SourceLocation loc;
18084   NamedDecl *d;
18085   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18086     loc = ref->getLocation();
18087     d = ref->getDecl();
18088   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18089     loc = mem->getMemberLoc();
18090     d = mem->getMemberDecl();
18091   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18092     diagID = diag::err_uncasted_call_of_unknown_any;
18093     loc = msg->getSelectorStartLoc();
18094     d = msg->getMethodDecl();
18095     if (!d) {
18096       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18097         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18098         << orig->getSourceRange();
18099       return ExprError();
18100     }
18101   } else {
18102     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18103       << E->getSourceRange();
18104     return ExprError();
18105   }
18106 
18107   S.Diag(loc, diagID) << d << orig->getSourceRange();
18108 
18109   // Never recoverable.
18110   return ExprError();
18111 }
18112 
18113 /// Check for operands with placeholder types and complain if found.
18114 /// Returns ExprError() if there was an error and no recovery was possible.
18115 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18116   if (!getLangOpts().CPlusPlus) {
18117     // C cannot handle TypoExpr nodes on either side of a binop because it
18118     // doesn't handle dependent types properly, so make sure any TypoExprs have
18119     // been dealt with before checking the operands.
18120     ExprResult Result = CorrectDelayedTyposInExpr(E);
18121     if (!Result.isUsable()) return ExprError();
18122     E = Result.get();
18123   }
18124 
18125   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18126   if (!placeholderType) return E;
18127 
18128   switch (placeholderType->getKind()) {
18129 
18130   // Overloaded expressions.
18131   case BuiltinType::Overload: {
18132     // Try to resolve a single function template specialization.
18133     // This is obligatory.
18134     ExprResult Result = E;
18135     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18136       return Result;
18137 
18138     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18139     // leaves Result unchanged on failure.
18140     Result = E;
18141     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18142       return Result;
18143 
18144     // If that failed, try to recover with a call.
18145     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18146                          /*complain*/ true);
18147     return Result;
18148   }
18149 
18150   // Bound member functions.
18151   case BuiltinType::BoundMember: {
18152     ExprResult result = E;
18153     const Expr *BME = E->IgnoreParens();
18154     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18155     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18156     if (isa<CXXPseudoDestructorExpr>(BME)) {
18157       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18158     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18159       if (ME->getMemberNameInfo().getName().getNameKind() ==
18160           DeclarationName::CXXDestructorName)
18161         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18162     }
18163     tryToRecoverWithCall(result, PD,
18164                          /*complain*/ true);
18165     return result;
18166   }
18167 
18168   // ARC unbridged casts.
18169   case BuiltinType::ARCUnbridgedCast: {
18170     Expr *realCast = stripARCUnbridgedCast(E);
18171     diagnoseARCUnbridgedCast(realCast);
18172     return realCast;
18173   }
18174 
18175   // Expressions of unknown type.
18176   case BuiltinType::UnknownAny:
18177     return diagnoseUnknownAnyExpr(*this, E);
18178 
18179   // Pseudo-objects.
18180   case BuiltinType::PseudoObject:
18181     return checkPseudoObjectRValue(E);
18182 
18183   case BuiltinType::BuiltinFn: {
18184     // Accept __noop without parens by implicitly converting it to a call expr.
18185     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18186     if (DRE) {
18187       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18188       if (FD->getBuiltinID() == Builtin::BI__noop) {
18189         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18190                               CK_BuiltinFnToFnPtr)
18191                 .get();
18192         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18193                                 VK_RValue, SourceLocation());
18194       }
18195     }
18196 
18197     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18198     return ExprError();
18199   }
18200 
18201   // Expressions of unknown type.
18202   case BuiltinType::OMPArraySection:
18203     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18204     return ExprError();
18205 
18206   // Everything else should be impossible.
18207 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18208   case BuiltinType::Id:
18209 #include "clang/Basic/OpenCLImageTypes.def"
18210 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18211   case BuiltinType::Id:
18212 #include "clang/Basic/OpenCLExtensionTypes.def"
18213 #define SVE_TYPE(Name, Id, SingletonId) \
18214   case BuiltinType::Id:
18215 #include "clang/Basic/AArch64SVEACLETypes.def"
18216 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18217 #define PLACEHOLDER_TYPE(Id, SingletonId)
18218 #include "clang/AST/BuiltinTypes.def"
18219     break;
18220   }
18221 
18222   llvm_unreachable("invalid placeholder type!");
18223 }
18224 
18225 bool Sema::CheckCaseExpression(Expr *E) {
18226   if (E->isTypeDependent())
18227     return true;
18228   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18229     return E->getType()->isIntegralOrEnumerationType();
18230   return false;
18231 }
18232 
18233 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18234 ExprResult
18235 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18236   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18237          "Unknown Objective-C Boolean value!");
18238   QualType BoolT = Context.ObjCBuiltinBoolTy;
18239   if (!Context.getBOOLDecl()) {
18240     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18241                         Sema::LookupOrdinaryName);
18242     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18243       NamedDecl *ND = Result.getFoundDecl();
18244       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18245         Context.setBOOLDecl(TD);
18246     }
18247   }
18248   if (Context.getBOOLDecl())
18249     BoolT = Context.getBOOLType();
18250   return new (Context)
18251       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18252 }
18253 
18254 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18255     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18256     SourceLocation RParen) {
18257 
18258   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18259 
18260   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18261     return Spec.getPlatform() == Platform;
18262   });
18263 
18264   VersionTuple Version;
18265   if (Spec != AvailSpecs.end())
18266     Version = Spec->getVersion();
18267 
18268   // The use of `@available` in the enclosing function should be analyzed to
18269   // warn when it's used inappropriately (i.e. not if(@available)).
18270   if (getCurFunctionOrMethodDecl())
18271     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18272   else if (getCurBlock() || getCurLambda())
18273     getCurFunction()->HasPotentialAvailabilityViolations = true;
18274 
18275   return new (Context)
18276       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18277 }
18278 
18279 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18280   assert(E->isTypeDependent());
18281   return isa<UnresolvedLookupExpr>(E);
18282 }
18283