xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp (revision 0b37c1590418417c894529d371800dfac71ef887)
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 "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/FixedPoint.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51 
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55   // See if this is an auto-typed variable whose initializer we are parsing.
56   if (ParsingInitForAutoVars.count(D))
57     return false;
58 
59   // See if this is a deleted function.
60   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61     if (FD->isDeleted())
62       return false;
63 
64     // If the function has a deduced return type, and we can't deduce it,
65     // then we can't use it either.
66     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68       return false;
69 
70     // See if this is an aligned allocation/deallocation function that is
71     // unavailable.
72     if (TreatUnavailableAsInvalid &&
73         isUnavailableAlignedAllocationFunction(*FD))
74       return false;
75   }
76 
77   // See if this function is unavailable.
78   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
79       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
80     return false;
81 
82   return true;
83 }
84 
85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
86   // Warn if this is used but marked unused.
87   if (const auto *A = D->getAttr<UnusedAttr>()) {
88     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
89     // should diagnose them.
90     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
91         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
92       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
93       if (DC && !DC->hasAttr<UnusedAttr>())
94         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
95     }
96   }
97 }
98 
99 /// Emit a note explaining that this function is deleted.
100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
101   assert(Decl && Decl->isDeleted());
102 
103   if (Decl->isDefaulted()) {
104     // If the method was explicitly defaulted, point at that declaration.
105     if (!Decl->isImplicit())
106       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
107 
108     // Try to diagnose why this special member function was implicitly
109     // deleted. This might fail, if that reason no longer applies.
110     DiagnoseDeletedDefaultedFunction(Decl);
111     return;
112   }
113 
114   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
115   if (Ctor && Ctor->isInheritingConstructor())
116     return NoteDeletedInheritingConstructor(Ctor);
117 
118   Diag(Decl->getLocation(), diag::note_availability_specified_here)
119     << Decl << 1;
120 }
121 
122 /// Determine whether a FunctionDecl was ever declared with an
123 /// explicit storage class.
124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
125   for (auto I : D->redecls()) {
126     if (I->getStorageClass() != SC_None)
127       return true;
128   }
129   return false;
130 }
131 
132 /// Check whether we're in an extern inline function and referring to a
133 /// variable or function with internal linkage (C11 6.7.4p3).
134 ///
135 /// This is only a warning because we used to silently accept this code, but
136 /// in many cases it will not behave correctly. This is not enabled in C++ mode
137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
138 /// and so while there may still be user mistakes, most of the time we can't
139 /// prove that there are errors.
140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
141                                                       const NamedDecl *D,
142                                                       SourceLocation Loc) {
143   // This is disabled under C++; there are too many ways for this to fire in
144   // contexts where the warning is a false positive, or where it is technically
145   // correct but benign.
146   if (S.getLangOpts().CPlusPlus)
147     return;
148 
149   // Check if this is an inlined function or method.
150   FunctionDecl *Current = S.getCurFunctionDecl();
151   if (!Current)
152     return;
153   if (!Current->isInlined())
154     return;
155   if (!Current->isExternallyVisible())
156     return;
157 
158   // Check if the decl has internal linkage.
159   if (D->getFormalLinkage() != InternalLinkage)
160     return;
161 
162   // Downgrade from ExtWarn to Extension if
163   //  (1) the supposedly external inline function is in the main file,
164   //      and probably won't be included anywhere else.
165   //  (2) the thing we're referencing is a pure function.
166   //  (3) the thing we're referencing is another inline function.
167   // This last can give us false negatives, but it's better than warning on
168   // wrappers for simple C library functions.
169   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
170   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
171   if (!DowngradeWarning && UsedFn)
172     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
173 
174   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
175                                : diag::ext_internal_in_extern_inline)
176     << /*IsVar=*/!UsedFn << D;
177 
178   S.MaybeSuggestAddingStaticToDecl(Current);
179 
180   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
181       << D;
182 }
183 
184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
185   const FunctionDecl *First = Cur->getFirstDecl();
186 
187   // Suggest "static" on the function, if possible.
188   if (!hasAnyExplicitStorageClass(First)) {
189     SourceLocation DeclBegin = First->getSourceRange().getBegin();
190     Diag(DeclBegin, diag::note_convert_inline_to_static)
191       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
192   }
193 }
194 
195 /// Determine whether the use of this declaration is valid, and
196 /// emit any corresponding diagnostics.
197 ///
198 /// This routine diagnoses various problems with referencing
199 /// declarations that can occur when using a declaration. For example,
200 /// it might warn if a deprecated or unavailable declaration is being
201 /// used, or produce an error (and return true) if a C++0x deleted
202 /// function is being used.
203 ///
204 /// \returns true if there was an error (this declaration cannot be
205 /// referenced), false otherwise.
206 ///
207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
208                              const ObjCInterfaceDecl *UnknownObjCClass,
209                              bool ObjCPropertyAccess,
210                              bool AvoidPartialAvailabilityChecks,
211                              ObjCInterfaceDecl *ClassReceiver) {
212   SourceLocation Loc = Locs.front();
213   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
214     // If there were any diagnostics suppressed by template argument deduction,
215     // emit them now.
216     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
217     if (Pos != SuppressedDiagnostics.end()) {
218       for (const PartialDiagnosticAt &Suppressed : Pos->second)
219         Diag(Suppressed.first, Suppressed.second);
220 
221       // Clear out the list of suppressed diagnostics, so that we don't emit
222       // them again for this specialization. However, we don't obsolete this
223       // entry from the table, because we want to avoid ever emitting these
224       // diagnostics again.
225       Pos->second.clear();
226     }
227 
228     // C++ [basic.start.main]p3:
229     //   The function 'main' shall not be used within a program.
230     if (cast<FunctionDecl>(D)->isMain())
231       Diag(Loc, diag::ext_main_used);
232 
233     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
234   }
235 
236   // See if this is an auto-typed variable whose initializer we are parsing.
237   if (ParsingInitForAutoVars.count(D)) {
238     if (isa<BindingDecl>(D)) {
239       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
240         << D->getDeclName();
241     } else {
242       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
243         << D->getDeclName() << cast<VarDecl>(D)->getType();
244     }
245     return true;
246   }
247 
248   // See if this is a deleted function.
249   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
250     if (FD->isDeleted()) {
251       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
252       if (Ctor && Ctor->isInheritingConstructor())
253         Diag(Loc, diag::err_deleted_inherited_ctor_use)
254             << Ctor->getParent()
255             << Ctor->getInheritedConstructor().getConstructor()->getParent();
256       else
257         Diag(Loc, diag::err_deleted_function_use);
258       NoteDeletedFunction(FD);
259       return true;
260     }
261 
262     // If the function has a deduced return type, and we can't deduce it,
263     // then we can't use it either.
264     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
265         DeduceReturnType(FD, Loc))
266       return true;
267 
268     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
269       return true;
270   }
271 
272   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
273     // Lambdas are only default-constructible or assignable in C++2a onwards.
274     if (MD->getParent()->isLambda() &&
275         ((isa<CXXConstructorDecl>(MD) &&
276           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
277          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
278       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
279         << !isa<CXXConstructorDecl>(MD);
280     }
281   }
282 
283   auto getReferencedObjCProp = [](const NamedDecl *D) ->
284                                       const ObjCPropertyDecl * {
285     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
286       return MD->findPropertyDecl();
287     return nullptr;
288   };
289   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
290     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
291       return true;
292   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
293       return true;
294   }
295 
296   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
297   // Only the variables omp_in and omp_out are allowed in the combiner.
298   // Only the variables omp_priv and omp_orig are allowed in the
299   // initializer-clause.
300   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
301   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
302       isa<VarDecl>(D)) {
303     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
304         << getCurFunction()->HasOMPDeclareReductionCombiner;
305     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
306     return true;
307   }
308 
309   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
310   //  List-items in map clauses on this construct may only refer to the declared
311   //  variable var and entities that could be referenced by a procedure defined
312   //  at the same location
313   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
314   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
315       isa<VarDecl>(D)) {
316     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
317         << DMD->getVarName().getAsString();
318     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
319     return true;
320   }
321 
322   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
323                              AvoidPartialAvailabilityChecks, ClassReceiver);
324 
325   DiagnoseUnusedOfDecl(*this, D, Loc);
326 
327   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
328 
329   // [expr.prim.id]p4
330   //   A program that refers explicitly or implicitly to a function with a
331   //   trailing requires-clause whose constraint-expression is not satisfied,
332   //   other than to declare it, is ill-formed. [...]
333   //
334   // See if this is a function with constraints that need to be satisfied.
335   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
336     if (Expr *RC = FD->getTrailingRequiresClause()) {
337       ConstraintSatisfaction Satisfaction;
338       bool Failed = CheckConstraintSatisfaction(RC, Satisfaction);
339       if (Failed)
340         // A diagnostic will have already been generated (non-constant
341         // constraint expression, for example)
342         return true;
343       if (!Satisfaction.IsSatisfied) {
344         Diag(Loc,
345              diag::err_reference_to_function_with_unsatisfied_constraints)
346             << D;
347         DiagnoseUnsatisfiedConstraint(Satisfaction);
348         return true;
349       }
350     }
351   }
352 
353   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
354       !isUnevaluatedContext()) {
355     // C++ [expr.prim.req.nested] p3
356     //   A local parameter shall only appear as an unevaluated operand
357     //   (Clause 8) within the constraint-expression.
358     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
359         << D;
360     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361     return true;
362   }
363 
364   return false;
365 }
366 
367 /// DiagnoseSentinelCalls - This routine checks whether a call or
368 /// message-send is to a declaration with the sentinel attribute, and
369 /// if so, it checks that the requirements of the sentinel are
370 /// satisfied.
371 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
372                                  ArrayRef<Expr *> Args) {
373   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
374   if (!attr)
375     return;
376 
377   // The number of formal parameters of the declaration.
378   unsigned numFormalParams;
379 
380   // The kind of declaration.  This is also an index into a %select in
381   // the diagnostic.
382   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
383 
384   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
385     numFormalParams = MD->param_size();
386     calleeType = CT_Method;
387   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
388     numFormalParams = FD->param_size();
389     calleeType = CT_Function;
390   } else if (isa<VarDecl>(D)) {
391     QualType type = cast<ValueDecl>(D)->getType();
392     const FunctionType *fn = nullptr;
393     if (const PointerType *ptr = type->getAs<PointerType>()) {
394       fn = ptr->getPointeeType()->getAs<FunctionType>();
395       if (!fn) return;
396       calleeType = CT_Function;
397     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
398       fn = ptr->getPointeeType()->castAs<FunctionType>();
399       calleeType = CT_Block;
400     } else {
401       return;
402     }
403 
404     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
405       numFormalParams = proto->getNumParams();
406     } else {
407       numFormalParams = 0;
408     }
409   } else {
410     return;
411   }
412 
413   // "nullPos" is the number of formal parameters at the end which
414   // effectively count as part of the variadic arguments.  This is
415   // useful if you would prefer to not have *any* formal parameters,
416   // but the language forces you to have at least one.
417   unsigned nullPos = attr->getNullPos();
418   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
419   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
420 
421   // The number of arguments which should follow the sentinel.
422   unsigned numArgsAfterSentinel = attr->getSentinel();
423 
424   // If there aren't enough arguments for all the formal parameters,
425   // the sentinel, and the args after the sentinel, complain.
426   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
427     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
428     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429     return;
430   }
431 
432   // Otherwise, find the sentinel expression.
433   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
434   if (!sentinelExpr) return;
435   if (sentinelExpr->isValueDependent()) return;
436   if (Context.isSentinelNullExpr(sentinelExpr)) return;
437 
438   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
439   // or 'NULL' if those are actually defined in the context.  Only use
440   // 'nil' for ObjC methods, where it's much more likely that the
441   // variadic arguments form a list of object pointers.
442   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
443   std::string NullValue;
444   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
445     NullValue = "nil";
446   else if (getLangOpts().CPlusPlus11)
447     NullValue = "nullptr";
448   else if (PP.isMacroDefined("NULL"))
449     NullValue = "NULL";
450   else
451     NullValue = "(void*) 0";
452 
453   if (MissingNilLoc.isInvalid())
454     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
455   else
456     Diag(MissingNilLoc, diag::warn_missing_sentinel)
457       << int(calleeType)
458       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
459   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460 }
461 
462 SourceRange Sema::getExprRange(Expr *E) const {
463   return E ? E->getSourceRange() : SourceRange();
464 }
465 
466 //===----------------------------------------------------------------------===//
467 //  Standard Promotions and Conversions
468 //===----------------------------------------------------------------------===//
469 
470 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
471 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
472   // Handle any placeholder expressions which made it here.
473   if (E->getType()->isPlaceholderType()) {
474     ExprResult result = CheckPlaceholderExpr(E);
475     if (result.isInvalid()) return ExprError();
476     E = result.get();
477   }
478 
479   QualType Ty = E->getType();
480   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
481 
482   if (Ty->isFunctionType()) {
483     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
484       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
485         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
486           return ExprError();
487 
488     E = ImpCastExprToType(E, Context.getPointerType(Ty),
489                           CK_FunctionToPointerDecay).get();
490   } else if (Ty->isArrayType()) {
491     // In C90 mode, arrays only promote to pointers if the array expression is
492     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
493     // type 'array of type' is converted to an expression that has type 'pointer
494     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
495     // that has type 'array of type' ...".  The relevant change is "an lvalue"
496     // (C90) to "an expression" (C99).
497     //
498     // C++ 4.2p1:
499     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
500     // T" can be converted to an rvalue of type "pointer to T".
501     //
502     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
503       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
504                             CK_ArrayToPointerDecay).get();
505   }
506   return E;
507 }
508 
509 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
510   // Check to see if we are dereferencing a null pointer.  If so,
511   // and if not volatile-qualified, this is undefined behavior that the
512   // optimizer will delete, so warn about it.  People sometimes try to use this
513   // to get a deterministic trap and are surprised by clang's behavior.  This
514   // only handles the pattern "*null", which is a very syntactic check.
515   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
516   if (UO && UO->getOpcode() == UO_Deref &&
517       UO->getSubExpr()->getType()->isPointerType()) {
518     const LangAS AS =
519         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
520     if ((!isTargetAddressSpace(AS) ||
521          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
522         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
523             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
524         !UO->getType().isVolatileQualified()) {
525       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
526                             S.PDiag(diag::warn_indirection_through_null)
527                                 << UO->getSubExpr()->getSourceRange());
528       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
529                             S.PDiag(diag::note_indirection_through_null));
530     }
531   }
532 }
533 
534 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
535                                     SourceLocation AssignLoc,
536                                     const Expr* RHS) {
537   const ObjCIvarDecl *IV = OIRE->getDecl();
538   if (!IV)
539     return;
540 
541   DeclarationName MemberName = IV->getDeclName();
542   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
543   if (!Member || !Member->isStr("isa"))
544     return;
545 
546   const Expr *Base = OIRE->getBase();
547   QualType BaseType = Base->getType();
548   if (OIRE->isArrow())
549     BaseType = BaseType->getPointeeType();
550   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
551     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
552       ObjCInterfaceDecl *ClassDeclared = nullptr;
553       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
554       if (!ClassDeclared->getSuperClass()
555           && (*ClassDeclared->ivar_begin()) == IV) {
556         if (RHS) {
557           NamedDecl *ObjectSetClass =
558             S.LookupSingleName(S.TUScope,
559                                &S.Context.Idents.get("object_setClass"),
560                                SourceLocation(), S.LookupOrdinaryName);
561           if (ObjectSetClass) {
562             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
563             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
564                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
565                                               "object_setClass(")
566                 << FixItHint::CreateReplacement(
567                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
568                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
569           }
570           else
571             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
572         } else {
573           NamedDecl *ObjectGetClass =
574             S.LookupSingleName(S.TUScope,
575                                &S.Context.Idents.get("object_getClass"),
576                                SourceLocation(), S.LookupOrdinaryName);
577           if (ObjectGetClass)
578             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
579                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580                                               "object_getClass(")
581                 << FixItHint::CreateReplacement(
582                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
583           else
584             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
585         }
586         S.Diag(IV->getLocation(), diag::note_ivar_decl);
587       }
588     }
589 }
590 
591 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
592   // Handle any placeholder expressions which made it here.
593   if (E->getType()->isPlaceholderType()) {
594     ExprResult result = CheckPlaceholderExpr(E);
595     if (result.isInvalid()) return ExprError();
596     E = result.get();
597   }
598 
599   // C++ [conv.lval]p1:
600   //   A glvalue of a non-function, non-array type T can be
601   //   converted to a prvalue.
602   if (!E->isGLValue()) return E;
603 
604   QualType T = E->getType();
605   assert(!T.isNull() && "r-value conversion on typeless expression?");
606 
607   // We don't want to throw lvalue-to-rvalue casts on top of
608   // expressions of certain types in C++.
609   if (getLangOpts().CPlusPlus &&
610       (E->getType() == Context.OverloadTy ||
611        T->isDependentType() ||
612        T->isRecordType()))
613     return E;
614 
615   // The C standard is actually really unclear on this point, and
616   // DR106 tells us what the result should be but not why.  It's
617   // generally best to say that void types just doesn't undergo
618   // lvalue-to-rvalue at all.  Note that expressions of unqualified
619   // 'void' type are never l-values, but qualified void can be.
620   if (T->isVoidType())
621     return E;
622 
623   // OpenCL usually rejects direct accesses to values of 'half' type.
624   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
625       T->isHalfType()) {
626     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
627       << 0 << T;
628     return ExprError();
629   }
630 
631   CheckForNullPointerDereference(*this, E);
632   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
633     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
634                                      &Context.Idents.get("object_getClass"),
635                                      SourceLocation(), LookupOrdinaryName);
636     if (ObjectGetClass)
637       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
638           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
639           << FixItHint::CreateReplacement(
640                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
641     else
642       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
643   }
644   else if (const ObjCIvarRefExpr *OIRE =
645             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
646     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
647 
648   // C++ [conv.lval]p1:
649   //   [...] If T is a non-class type, the type of the prvalue is the
650   //   cv-unqualified version of T. Otherwise, the type of the
651   //   rvalue is T.
652   //
653   // C99 6.3.2.1p2:
654   //   If the lvalue has qualified type, the value has the unqualified
655   //   version of the type of the lvalue; otherwise, the value has the
656   //   type of the lvalue.
657   if (T.hasQualifiers())
658     T = T.getUnqualifiedType();
659 
660   // Under the MS ABI, lock down the inheritance model now.
661   if (T->isMemberPointerType() &&
662       Context.getTargetInfo().getCXXABI().isMicrosoft())
663     (void)isCompleteType(E->getExprLoc(), T);
664 
665   ExprResult Res = CheckLValueToRValueConversionOperand(E);
666   if (Res.isInvalid())
667     return Res;
668   E = Res.get();
669 
670   // Loading a __weak object implicitly retains the value, so we need a cleanup to
671   // balance that.
672   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
673     Cleanup.setExprNeedsCleanups(true);
674 
675   // C++ [conv.lval]p3:
676   //   If T is cv std::nullptr_t, the result is a null pointer constant.
677   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
678   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
679 
680   // C11 6.3.2.1p2:
681   //   ... if the lvalue has atomic type, the value has the non-atomic version
682   //   of the type of the lvalue ...
683   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
684     T = Atomic->getValueType().getUnqualifiedType();
685     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
686                                    nullptr, VK_RValue);
687   }
688 
689   return Res;
690 }
691 
692 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
693   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
694   if (Res.isInvalid())
695     return ExprError();
696   Res = DefaultLvalueConversion(Res.get());
697   if (Res.isInvalid())
698     return ExprError();
699   return Res;
700 }
701 
702 /// CallExprUnaryConversions - a special case of an unary conversion
703 /// performed on a function designator of a call expression.
704 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
705   QualType Ty = E->getType();
706   ExprResult Res = E;
707   // Only do implicit cast for a function type, but not for a pointer
708   // to function type.
709   if (Ty->isFunctionType()) {
710     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
711                             CK_FunctionToPointerDecay).get();
712     if (Res.isInvalid())
713       return ExprError();
714   }
715   Res = DefaultLvalueConversion(Res.get());
716   if (Res.isInvalid())
717     return ExprError();
718   return Res.get();
719 }
720 
721 /// UsualUnaryConversions - Performs various conversions that are common to most
722 /// operators (C99 6.3). The conversions of array and function types are
723 /// sometimes suppressed. For example, the array->pointer conversion doesn't
724 /// apply if the array is an argument to the sizeof or address (&) operators.
725 /// In these instances, this routine should *not* be called.
726 ExprResult Sema::UsualUnaryConversions(Expr *E) {
727   // First, convert to an r-value.
728   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
729   if (Res.isInvalid())
730     return ExprError();
731   E = Res.get();
732 
733   QualType Ty = E->getType();
734   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
735 
736   // Half FP have to be promoted to float unless it is natively supported
737   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
738     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
739 
740   // Try to perform integral promotions if the object has a theoretically
741   // promotable type.
742   if (Ty->isIntegralOrUnscopedEnumerationType()) {
743     // C99 6.3.1.1p2:
744     //
745     //   The following may be used in an expression wherever an int or
746     //   unsigned int may be used:
747     //     - an object or expression with an integer type whose integer
748     //       conversion rank is less than or equal to the rank of int
749     //       and unsigned int.
750     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
751     //
752     //   If an int can represent all values of the original type, the
753     //   value is converted to an int; otherwise, it is converted to an
754     //   unsigned int. These are called the integer promotions. All
755     //   other types are unchanged by the integer promotions.
756 
757     QualType PTy = Context.isPromotableBitField(E);
758     if (!PTy.isNull()) {
759       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
760       return E;
761     }
762     if (Ty->isPromotableIntegerType()) {
763       QualType PT = Context.getPromotedIntegerType(Ty);
764       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
765       return E;
766     }
767   }
768   return E;
769 }
770 
771 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
772 /// do not have a prototype. Arguments that have type float or __fp16
773 /// are promoted to double. All other argument types are converted by
774 /// UsualUnaryConversions().
775 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
776   QualType Ty = E->getType();
777   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
778 
779   ExprResult Res = UsualUnaryConversions(E);
780   if (Res.isInvalid())
781     return ExprError();
782   E = Res.get();
783 
784   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
785   // promote to double.
786   // Note that default argument promotion applies only to float (and
787   // half/fp16); it does not apply to _Float16.
788   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
789   if (BTy && (BTy->getKind() == BuiltinType::Half ||
790               BTy->getKind() == BuiltinType::Float)) {
791     if (getLangOpts().OpenCL &&
792         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
793         if (BTy->getKind() == BuiltinType::Half) {
794             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
795         }
796     } else {
797       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
798     }
799   }
800 
801   // C++ performs lvalue-to-rvalue conversion as a default argument
802   // promotion, even on class types, but note:
803   //   C++11 [conv.lval]p2:
804   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
805   //     operand or a subexpression thereof the value contained in the
806   //     referenced object is not accessed. Otherwise, if the glvalue
807   //     has a class type, the conversion copy-initializes a temporary
808   //     of type T from the glvalue and the result of the conversion
809   //     is a prvalue for the temporary.
810   // FIXME: add some way to gate this entire thing for correctness in
811   // potentially potentially evaluated contexts.
812   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
813     ExprResult Temp = PerformCopyInitialization(
814                        InitializedEntity::InitializeTemporary(E->getType()),
815                                                 E->getExprLoc(), E);
816     if (Temp.isInvalid())
817       return ExprError();
818     E = Temp.get();
819   }
820 
821   return E;
822 }
823 
824 /// Determine the degree of POD-ness for an expression.
825 /// Incomplete types are considered POD, since this check can be performed
826 /// when we're in an unevaluated context.
827 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
828   if (Ty->isIncompleteType()) {
829     // C++11 [expr.call]p7:
830     //   After these conversions, if the argument does not have arithmetic,
831     //   enumeration, pointer, pointer to member, or class type, the program
832     //   is ill-formed.
833     //
834     // Since we've already performed array-to-pointer and function-to-pointer
835     // decay, the only such type in C++ is cv void. This also handles
836     // initializer lists as variadic arguments.
837     if (Ty->isVoidType())
838       return VAK_Invalid;
839 
840     if (Ty->isObjCObjectType())
841       return VAK_Invalid;
842     return VAK_Valid;
843   }
844 
845   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846     return VAK_Invalid;
847 
848   if (Ty.isCXX98PODType(Context))
849     return VAK_Valid;
850 
851   // C++11 [expr.call]p7:
852   //   Passing a potentially-evaluated argument of class type (Clause 9)
853   //   having a non-trivial copy constructor, a non-trivial move constructor,
854   //   or a non-trivial destructor, with no corresponding parameter,
855   //   is conditionally-supported with implementation-defined semantics.
856   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
857     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
858       if (!Record->hasNonTrivialCopyConstructor() &&
859           !Record->hasNonTrivialMoveConstructor() &&
860           !Record->hasNonTrivialDestructor())
861         return VAK_ValidInCXX11;
862 
863   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
864     return VAK_Valid;
865 
866   if (Ty->isObjCObjectType())
867     return VAK_Invalid;
868 
869   if (getLangOpts().MSVCCompat)
870     return VAK_MSVCUndefined;
871 
872   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
873   // permitted to reject them. We should consider doing so.
874   return VAK_Undefined;
875 }
876 
877 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
878   // Don't allow one to pass an Objective-C interface to a vararg.
879   const QualType &Ty = E->getType();
880   VarArgKind VAK = isValidVarArgType(Ty);
881 
882   // Complain about passing non-POD types through varargs.
883   switch (VAK) {
884   case VAK_ValidInCXX11:
885     DiagRuntimeBehavior(
886         E->getBeginLoc(), nullptr,
887         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
888     LLVM_FALLTHROUGH;
889   case VAK_Valid:
890     if (Ty->isRecordType()) {
891       // This is unlikely to be what the user intended. If the class has a
892       // 'c_str' member function, the user probably meant to call that.
893       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
894                           PDiag(diag::warn_pass_class_arg_to_vararg)
895                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
896     }
897     break;
898 
899   case VAK_Undefined:
900   case VAK_MSVCUndefined:
901     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
902                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
903                             << getLangOpts().CPlusPlus11 << Ty << CT);
904     break;
905 
906   case VAK_Invalid:
907     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
908       Diag(E->getBeginLoc(),
909            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
910           << Ty << CT;
911     else if (Ty->isObjCObjectType())
912       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
913                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
914                               << Ty << CT);
915     else
916       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
917           << isa<InitListExpr>(E) << Ty << CT;
918     break;
919   }
920 }
921 
922 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
923 /// will create a trap if the resulting type is not a POD type.
924 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
925                                                   FunctionDecl *FDecl) {
926   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
927     // Strip the unbridged-cast placeholder expression off, if applicable.
928     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
929         (CT == VariadicMethod ||
930          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
931       E = stripARCUnbridgedCast(E);
932 
933     // Otherwise, do normal placeholder checking.
934     } else {
935       ExprResult ExprRes = CheckPlaceholderExpr(E);
936       if (ExprRes.isInvalid())
937         return ExprError();
938       E = ExprRes.get();
939     }
940   }
941 
942   ExprResult ExprRes = DefaultArgumentPromotion(E);
943   if (ExprRes.isInvalid())
944     return ExprError();
945   E = ExprRes.get();
946 
947   // Diagnostics regarding non-POD argument types are
948   // emitted along with format string checking in Sema::CheckFunctionCall().
949   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
950     // Turn this into a trap.
951     CXXScopeSpec SS;
952     SourceLocation TemplateKWLoc;
953     UnqualifiedId Name;
954     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
955                        E->getBeginLoc());
956     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
957                                           /*HasTrailingLParen=*/true,
958                                           /*IsAddressOfOperand=*/false);
959     if (TrapFn.isInvalid())
960       return ExprError();
961 
962     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
963                                     None, E->getEndLoc());
964     if (Call.isInvalid())
965       return ExprError();
966 
967     ExprResult Comma =
968         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
969     if (Comma.isInvalid())
970       return ExprError();
971     return Comma.get();
972   }
973 
974   if (!getLangOpts().CPlusPlus &&
975       RequireCompleteType(E->getExprLoc(), E->getType(),
976                           diag::err_call_incomplete_argument))
977     return ExprError();
978 
979   return E;
980 }
981 
982 /// Converts an integer to complex float type.  Helper function of
983 /// UsualArithmeticConversions()
984 ///
985 /// \return false if the integer expression is an integer type and is
986 /// successfully converted to the complex type.
987 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
988                                                   ExprResult &ComplexExpr,
989                                                   QualType IntTy,
990                                                   QualType ComplexTy,
991                                                   bool SkipCast) {
992   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
993   if (SkipCast) return false;
994   if (IntTy->isIntegerType()) {
995     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
996     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
997     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
998                                   CK_FloatingRealToComplex);
999   } else {
1000     assert(IntTy->isComplexIntegerType());
1001     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1002                                   CK_IntegralComplexToFloatingComplex);
1003   }
1004   return false;
1005 }
1006 
1007 /// Handle arithmetic conversion with complex types.  Helper function of
1008 /// UsualArithmeticConversions()
1009 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1010                                              ExprResult &RHS, QualType LHSType,
1011                                              QualType RHSType,
1012                                              bool IsCompAssign) {
1013   // if we have an integer operand, the result is the complex type.
1014   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1015                                              /*skipCast*/false))
1016     return LHSType;
1017   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1018                                              /*skipCast*/IsCompAssign))
1019     return RHSType;
1020 
1021   // This handles complex/complex, complex/float, or float/complex.
1022   // When both operands are complex, the shorter operand is converted to the
1023   // type of the longer, and that is the type of the result. This corresponds
1024   // to what is done when combining two real floating-point operands.
1025   // The fun begins when size promotion occur across type domains.
1026   // From H&S 6.3.4: When one operand is complex and the other is a real
1027   // floating-point type, the less precise type is converted, within it's
1028   // real or complex domain, to the precision of the other type. For example,
1029   // when combining a "long double" with a "double _Complex", the
1030   // "double _Complex" is promoted to "long double _Complex".
1031 
1032   // Compute the rank of the two types, regardless of whether they are complex.
1033   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1034 
1035   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1036   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1037   QualType LHSElementType =
1038       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1039   QualType RHSElementType =
1040       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1041 
1042   QualType ResultType = S.Context.getComplexType(LHSElementType);
1043   if (Order < 0) {
1044     // Promote the precision of the LHS if not an assignment.
1045     ResultType = S.Context.getComplexType(RHSElementType);
1046     if (!IsCompAssign) {
1047       if (LHSComplexType)
1048         LHS =
1049             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1050       else
1051         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1052     }
1053   } else if (Order > 0) {
1054     // Promote the precision of the RHS.
1055     if (RHSComplexType)
1056       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1057     else
1058       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1059   }
1060   return ResultType;
1061 }
1062 
1063 /// Handle arithmetic conversion from integer to float.  Helper function
1064 /// of UsualArithmeticConversions()
1065 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1066                                            ExprResult &IntExpr,
1067                                            QualType FloatTy, QualType IntTy,
1068                                            bool ConvertFloat, bool ConvertInt) {
1069   if (IntTy->isIntegerType()) {
1070     if (ConvertInt)
1071       // Convert intExpr to the lhs floating point type.
1072       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1073                                     CK_IntegralToFloating);
1074     return FloatTy;
1075   }
1076 
1077   // Convert both sides to the appropriate complex float.
1078   assert(IntTy->isComplexIntegerType());
1079   QualType result = S.Context.getComplexType(FloatTy);
1080 
1081   // _Complex int -> _Complex float
1082   if (ConvertInt)
1083     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1084                                   CK_IntegralComplexToFloatingComplex);
1085 
1086   // float -> _Complex float
1087   if (ConvertFloat)
1088     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1089                                     CK_FloatingRealToComplex);
1090 
1091   return result;
1092 }
1093 
1094 /// Handle arithmethic conversion with floating point types.  Helper
1095 /// function of UsualArithmeticConversions()
1096 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1097                                       ExprResult &RHS, QualType LHSType,
1098                                       QualType RHSType, bool IsCompAssign) {
1099   bool LHSFloat = LHSType->isRealFloatingType();
1100   bool RHSFloat = RHSType->isRealFloatingType();
1101 
1102   // If we have two real floating types, convert the smaller operand
1103   // to the bigger result.
1104   if (LHSFloat && RHSFloat) {
1105     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1106     if (order > 0) {
1107       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1108       return LHSType;
1109     }
1110 
1111     assert(order < 0 && "illegal float comparison");
1112     if (!IsCompAssign)
1113       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1114     return RHSType;
1115   }
1116 
1117   if (LHSFloat) {
1118     // Half FP has to be promoted to float unless it is natively supported
1119     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1120       LHSType = S.Context.FloatTy;
1121 
1122     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1123                                       /*ConvertFloat=*/!IsCompAssign,
1124                                       /*ConvertInt=*/ true);
1125   }
1126   assert(RHSFloat);
1127   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1128                                     /*convertInt=*/ true,
1129                                     /*convertFloat=*/!IsCompAssign);
1130 }
1131 
1132 /// Diagnose attempts to convert between __float128 and long double if
1133 /// there is no support for such conversion. Helper function of
1134 /// UsualArithmeticConversions().
1135 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1136                                       QualType RHSType) {
1137   /*  No issue converting if at least one of the types is not a floating point
1138       type or the two types have the same rank.
1139   */
1140   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1141       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1142     return false;
1143 
1144   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1145          "The remaining types must be floating point types.");
1146 
1147   auto *LHSComplex = LHSType->getAs<ComplexType>();
1148   auto *RHSComplex = RHSType->getAs<ComplexType>();
1149 
1150   QualType LHSElemType = LHSComplex ?
1151     LHSComplex->getElementType() : LHSType;
1152   QualType RHSElemType = RHSComplex ?
1153     RHSComplex->getElementType() : RHSType;
1154 
1155   // No issue if the two types have the same representation
1156   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1157       &S.Context.getFloatTypeSemantics(RHSElemType))
1158     return false;
1159 
1160   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1161                                 RHSElemType == S.Context.LongDoubleTy);
1162   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1163                             RHSElemType == S.Context.Float128Ty);
1164 
1165   // We've handled the situation where __float128 and long double have the same
1166   // representation. We allow all conversions for all possible long double types
1167   // except PPC's double double.
1168   return Float128AndLongDouble &&
1169     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1170      &llvm::APFloat::PPCDoubleDouble());
1171 }
1172 
1173 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1174 
1175 namespace {
1176 /// These helper callbacks are placed in an anonymous namespace to
1177 /// permit their use as function template parameters.
1178 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1179   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1180 }
1181 
1182 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1183   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1184                              CK_IntegralComplexCast);
1185 }
1186 }
1187 
1188 /// Handle integer arithmetic conversions.  Helper function of
1189 /// UsualArithmeticConversions()
1190 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1191 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1192                                         ExprResult &RHS, QualType LHSType,
1193                                         QualType RHSType, bool IsCompAssign) {
1194   // The rules for this case are in C99 6.3.1.8
1195   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1196   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1197   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1198   if (LHSSigned == RHSSigned) {
1199     // Same signedness; use the higher-ranked type
1200     if (order >= 0) {
1201       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1202       return LHSType;
1203     } else if (!IsCompAssign)
1204       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1205     return RHSType;
1206   } else if (order != (LHSSigned ? 1 : -1)) {
1207     // The unsigned type has greater than or equal rank to the
1208     // signed type, so use the unsigned type
1209     if (RHSSigned) {
1210       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1211       return LHSType;
1212     } else if (!IsCompAssign)
1213       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1214     return RHSType;
1215   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1216     // The two types are different widths; if we are here, that
1217     // means the signed type is larger than the unsigned type, so
1218     // use the signed type.
1219     if (LHSSigned) {
1220       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1221       return LHSType;
1222     } else if (!IsCompAssign)
1223       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1224     return RHSType;
1225   } else {
1226     // The signed type is higher-ranked than the unsigned type,
1227     // but isn't actually any bigger (like unsigned int and long
1228     // on most 32-bit systems).  Use the unsigned type corresponding
1229     // to the signed type.
1230     QualType result =
1231       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1232     RHS = (*doRHSCast)(S, RHS.get(), result);
1233     if (!IsCompAssign)
1234       LHS = (*doLHSCast)(S, LHS.get(), result);
1235     return result;
1236   }
1237 }
1238 
1239 /// Handle conversions with GCC complex int extension.  Helper function
1240 /// of UsualArithmeticConversions()
1241 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1242                                            ExprResult &RHS, QualType LHSType,
1243                                            QualType RHSType,
1244                                            bool IsCompAssign) {
1245   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1246   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1247 
1248   if (LHSComplexInt && RHSComplexInt) {
1249     QualType LHSEltType = LHSComplexInt->getElementType();
1250     QualType RHSEltType = RHSComplexInt->getElementType();
1251     QualType ScalarType =
1252       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1253         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1254 
1255     return S.Context.getComplexType(ScalarType);
1256   }
1257 
1258   if (LHSComplexInt) {
1259     QualType LHSEltType = LHSComplexInt->getElementType();
1260     QualType ScalarType =
1261       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1262         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1263     QualType ComplexType = S.Context.getComplexType(ScalarType);
1264     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1265                               CK_IntegralRealToComplex);
1266 
1267     return ComplexType;
1268   }
1269 
1270   assert(RHSComplexInt);
1271 
1272   QualType RHSEltType = RHSComplexInt->getElementType();
1273   QualType ScalarType =
1274     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1275       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1276   QualType ComplexType = S.Context.getComplexType(ScalarType);
1277 
1278   if (!IsCompAssign)
1279     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1280                               CK_IntegralRealToComplex);
1281   return ComplexType;
1282 }
1283 
1284 /// Return the rank of a given fixed point or integer type. The value itself
1285 /// doesn't matter, but the values must be increasing with proper increasing
1286 /// rank as described in N1169 4.1.1.
1287 static unsigned GetFixedPointRank(QualType Ty) {
1288   const auto *BTy = Ty->getAs<BuiltinType>();
1289   assert(BTy && "Expected a builtin type.");
1290 
1291   switch (BTy->getKind()) {
1292   case BuiltinType::ShortFract:
1293   case BuiltinType::UShortFract:
1294   case BuiltinType::SatShortFract:
1295   case BuiltinType::SatUShortFract:
1296     return 1;
1297   case BuiltinType::Fract:
1298   case BuiltinType::UFract:
1299   case BuiltinType::SatFract:
1300   case BuiltinType::SatUFract:
1301     return 2;
1302   case BuiltinType::LongFract:
1303   case BuiltinType::ULongFract:
1304   case BuiltinType::SatLongFract:
1305   case BuiltinType::SatULongFract:
1306     return 3;
1307   case BuiltinType::ShortAccum:
1308   case BuiltinType::UShortAccum:
1309   case BuiltinType::SatShortAccum:
1310   case BuiltinType::SatUShortAccum:
1311     return 4;
1312   case BuiltinType::Accum:
1313   case BuiltinType::UAccum:
1314   case BuiltinType::SatAccum:
1315   case BuiltinType::SatUAccum:
1316     return 5;
1317   case BuiltinType::LongAccum:
1318   case BuiltinType::ULongAccum:
1319   case BuiltinType::SatLongAccum:
1320   case BuiltinType::SatULongAccum:
1321     return 6;
1322   default:
1323     if (BTy->isInteger())
1324       return 0;
1325     llvm_unreachable("Unexpected fixed point or integer type");
1326   }
1327 }
1328 
1329 /// handleFixedPointConversion - Fixed point operations between fixed
1330 /// point types and integers or other fixed point types do not fall under
1331 /// usual arithmetic conversion since these conversions could result in loss
1332 /// of precsision (N1169 4.1.4). These operations should be calculated with
1333 /// the full precision of their result type (N1169 4.1.6.2.1).
1334 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1335                                            QualType RHSTy) {
1336   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1337          "Expected at least one of the operands to be a fixed point type");
1338   assert((LHSTy->isFixedPointOrIntegerType() ||
1339           RHSTy->isFixedPointOrIntegerType()) &&
1340          "Special fixed point arithmetic operation conversions are only "
1341          "applied to ints or other fixed point types");
1342 
1343   // If one operand has signed fixed-point type and the other operand has
1344   // unsigned fixed-point type, then the unsigned fixed-point operand is
1345   // converted to its corresponding signed fixed-point type and the resulting
1346   // type is the type of the converted operand.
1347   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1348     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1349   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1350     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1351 
1352   // The result type is the type with the highest rank, whereby a fixed-point
1353   // conversion rank is always greater than an integer conversion rank; if the
1354   // type of either of the operands is a saturating fixedpoint type, the result
1355   // type shall be the saturating fixed-point type corresponding to the type
1356   // with the highest rank; the resulting value is converted (taking into
1357   // account rounding and overflow) to the precision of the resulting type.
1358   // Same ranks between signed and unsigned types are resolved earlier, so both
1359   // types are either signed or both unsigned at this point.
1360   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1361   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1362 
1363   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1364 
1365   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1366     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1367 
1368   return ResultTy;
1369 }
1370 
1371 /// Check that the usual arithmetic conversions can be performed on this pair of
1372 /// expressions that might be of enumeration type.
1373 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1374                                            SourceLocation Loc,
1375                                            Sema::ArithConvKind ACK) {
1376   // C++2a [expr.arith.conv]p1:
1377   //   If one operand is of enumeration type and the other operand is of a
1378   //   different enumeration type or a floating-point type, this behavior is
1379   //   deprecated ([depr.arith.conv.enum]).
1380   //
1381   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1382   // Eventually we will presumably reject these cases (in C++23 onwards?).
1383   QualType L = LHS->getType(), R = RHS->getType();
1384   bool LEnum = L->isUnscopedEnumerationType(),
1385        REnum = R->isUnscopedEnumerationType();
1386   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1387   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1388       (REnum && L->isFloatingType())) {
1389     S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1390                     ? diag::warn_arith_conv_enum_float_cxx2a
1391                     : diag::warn_arith_conv_enum_float)
1392         << LHS->getSourceRange() << RHS->getSourceRange()
1393         << (int)ACK << LEnum << L << R;
1394   } else if (!IsCompAssign && LEnum && REnum &&
1395              !S.Context.hasSameUnqualifiedType(L, R)) {
1396     unsigned DiagID;
1397     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1398         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1399       // If either enumeration type is unnamed, it's less likely that the
1400       // user cares about this, but this situation is still deprecated in
1401       // C++2a. Use a different warning group.
1402       DiagID = S.getLangOpts().CPlusPlus2a
1403                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1404                     : diag::warn_arith_conv_mixed_anon_enum_types;
1405     } else if (ACK == Sema::ACK_Conditional) {
1406       // Conditional expressions are separated out because they have
1407       // historically had a different warning flag.
1408       DiagID = S.getLangOpts().CPlusPlus2a
1409                    ? diag::warn_conditional_mixed_enum_types_cxx2a
1410                    : diag::warn_conditional_mixed_enum_types;
1411     } else if (ACK == Sema::ACK_Comparison) {
1412       // Comparison expressions are separated out because they have
1413       // historically had a different warning flag.
1414       DiagID = S.getLangOpts().CPlusPlus2a
1415                    ? diag::warn_comparison_mixed_enum_types_cxx2a
1416                    : diag::warn_comparison_mixed_enum_types;
1417     } else {
1418       DiagID = S.getLangOpts().CPlusPlus2a
1419                    ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1420                    : diag::warn_arith_conv_mixed_enum_types;
1421     }
1422     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1423                         << (int)ACK << L << R;
1424   }
1425 }
1426 
1427 /// UsualArithmeticConversions - Performs various conversions that are common to
1428 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1429 /// routine returns the first non-arithmetic type found. The client is
1430 /// responsible for emitting appropriate error diagnostics.
1431 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1432                                           SourceLocation Loc,
1433                                           ArithConvKind ACK) {
1434   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1435 
1436   if (ACK != ACK_CompAssign) {
1437     LHS = UsualUnaryConversions(LHS.get());
1438     if (LHS.isInvalid())
1439       return QualType();
1440   }
1441 
1442   RHS = UsualUnaryConversions(RHS.get());
1443   if (RHS.isInvalid())
1444     return QualType();
1445 
1446   // For conversion purposes, we ignore any qualifiers.
1447   // For example, "const float" and "float" are equivalent.
1448   QualType LHSType =
1449     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1450   QualType RHSType =
1451     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1452 
1453   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1454   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1455     LHSType = AtomicLHS->getValueType();
1456 
1457   // If both types are identical, no conversion is needed.
1458   if (LHSType == RHSType)
1459     return LHSType;
1460 
1461   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1462   // The caller can deal with this (e.g. pointer + int).
1463   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1464     return QualType();
1465 
1466   // Apply unary and bitfield promotions to the LHS's type.
1467   QualType LHSUnpromotedType = LHSType;
1468   if (LHSType->isPromotableIntegerType())
1469     LHSType = Context.getPromotedIntegerType(LHSType);
1470   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1471   if (!LHSBitfieldPromoteTy.isNull())
1472     LHSType = LHSBitfieldPromoteTy;
1473   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1474     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1475 
1476   // If both types are identical, no conversion is needed.
1477   if (LHSType == RHSType)
1478     return LHSType;
1479 
1480   // At this point, we have two different arithmetic types.
1481 
1482   // Diagnose attempts to convert between __float128 and long double where
1483   // such conversions currently can't be handled.
1484   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1485     return QualType();
1486 
1487   // Handle complex types first (C99 6.3.1.8p1).
1488   if (LHSType->isComplexType() || RHSType->isComplexType())
1489     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1490                                         ACK == ACK_CompAssign);
1491 
1492   // Now handle "real" floating types (i.e. float, double, long double).
1493   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1494     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1495                                  ACK == ACK_CompAssign);
1496 
1497   // Handle GCC complex int extension.
1498   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1499     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1500                                       ACK == ACK_CompAssign);
1501 
1502   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1503     return handleFixedPointConversion(*this, LHSType, RHSType);
1504 
1505   // Finally, we have two differing integer types.
1506   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1507            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1508 }
1509 
1510 //===----------------------------------------------------------------------===//
1511 //  Semantic Analysis for various Expression Types
1512 //===----------------------------------------------------------------------===//
1513 
1514 
1515 ExprResult
1516 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1517                                 SourceLocation DefaultLoc,
1518                                 SourceLocation RParenLoc,
1519                                 Expr *ControllingExpr,
1520                                 ArrayRef<ParsedType> ArgTypes,
1521                                 ArrayRef<Expr *> ArgExprs) {
1522   unsigned NumAssocs = ArgTypes.size();
1523   assert(NumAssocs == ArgExprs.size());
1524 
1525   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1526   for (unsigned i = 0; i < NumAssocs; ++i) {
1527     if (ArgTypes[i])
1528       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1529     else
1530       Types[i] = nullptr;
1531   }
1532 
1533   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1534                                              ControllingExpr,
1535                                              llvm::makeArrayRef(Types, NumAssocs),
1536                                              ArgExprs);
1537   delete [] Types;
1538   return ER;
1539 }
1540 
1541 ExprResult
1542 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1543                                  SourceLocation DefaultLoc,
1544                                  SourceLocation RParenLoc,
1545                                  Expr *ControllingExpr,
1546                                  ArrayRef<TypeSourceInfo *> Types,
1547                                  ArrayRef<Expr *> Exprs) {
1548   unsigned NumAssocs = Types.size();
1549   assert(NumAssocs == Exprs.size());
1550 
1551   // Decay and strip qualifiers for the controlling expression type, and handle
1552   // placeholder type replacement. See committee discussion from WG14 DR423.
1553   {
1554     EnterExpressionEvaluationContext Unevaluated(
1555         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1556     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1557     if (R.isInvalid())
1558       return ExprError();
1559     ControllingExpr = R.get();
1560   }
1561 
1562   // The controlling expression is an unevaluated operand, so side effects are
1563   // likely unintended.
1564   if (!inTemplateInstantiation() &&
1565       ControllingExpr->HasSideEffects(Context, false))
1566     Diag(ControllingExpr->getExprLoc(),
1567          diag::warn_side_effects_unevaluated_context);
1568 
1569   bool TypeErrorFound = false,
1570        IsResultDependent = ControllingExpr->isTypeDependent(),
1571        ContainsUnexpandedParameterPack
1572          = ControllingExpr->containsUnexpandedParameterPack();
1573 
1574   for (unsigned i = 0; i < NumAssocs; ++i) {
1575     if (Exprs[i]->containsUnexpandedParameterPack())
1576       ContainsUnexpandedParameterPack = true;
1577 
1578     if (Types[i]) {
1579       if (Types[i]->getType()->containsUnexpandedParameterPack())
1580         ContainsUnexpandedParameterPack = true;
1581 
1582       if (Types[i]->getType()->isDependentType()) {
1583         IsResultDependent = true;
1584       } else {
1585         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1586         // complete object type other than a variably modified type."
1587         unsigned D = 0;
1588         if (Types[i]->getType()->isIncompleteType())
1589           D = diag::err_assoc_type_incomplete;
1590         else if (!Types[i]->getType()->isObjectType())
1591           D = diag::err_assoc_type_nonobject;
1592         else if (Types[i]->getType()->isVariablyModifiedType())
1593           D = diag::err_assoc_type_variably_modified;
1594 
1595         if (D != 0) {
1596           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1597             << Types[i]->getTypeLoc().getSourceRange()
1598             << Types[i]->getType();
1599           TypeErrorFound = true;
1600         }
1601 
1602         // C11 6.5.1.1p2 "No two generic associations in the same generic
1603         // selection shall specify compatible types."
1604         for (unsigned j = i+1; j < NumAssocs; ++j)
1605           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1606               Context.typesAreCompatible(Types[i]->getType(),
1607                                          Types[j]->getType())) {
1608             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1609                  diag::err_assoc_compatible_types)
1610               << Types[j]->getTypeLoc().getSourceRange()
1611               << Types[j]->getType()
1612               << Types[i]->getType();
1613             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1614                  diag::note_compat_assoc)
1615               << Types[i]->getTypeLoc().getSourceRange()
1616               << Types[i]->getType();
1617             TypeErrorFound = true;
1618           }
1619       }
1620     }
1621   }
1622   if (TypeErrorFound)
1623     return ExprError();
1624 
1625   // If we determined that the generic selection is result-dependent, don't
1626   // try to compute the result expression.
1627   if (IsResultDependent)
1628     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1629                                         Exprs, DefaultLoc, RParenLoc,
1630                                         ContainsUnexpandedParameterPack);
1631 
1632   SmallVector<unsigned, 1> CompatIndices;
1633   unsigned DefaultIndex = -1U;
1634   for (unsigned i = 0; i < NumAssocs; ++i) {
1635     if (!Types[i])
1636       DefaultIndex = i;
1637     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1638                                         Types[i]->getType()))
1639       CompatIndices.push_back(i);
1640   }
1641 
1642   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1643   // type compatible with at most one of the types named in its generic
1644   // association list."
1645   if (CompatIndices.size() > 1) {
1646     // We strip parens here because the controlling expression is typically
1647     // parenthesized in macro definitions.
1648     ControllingExpr = ControllingExpr->IgnoreParens();
1649     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1650         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1651         << (unsigned)CompatIndices.size();
1652     for (unsigned I : CompatIndices) {
1653       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1654            diag::note_compat_assoc)
1655         << Types[I]->getTypeLoc().getSourceRange()
1656         << Types[I]->getType();
1657     }
1658     return ExprError();
1659   }
1660 
1661   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1662   // its controlling expression shall have type compatible with exactly one of
1663   // the types named in its generic association list."
1664   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1665     // We strip parens here because the controlling expression is typically
1666     // parenthesized in macro definitions.
1667     ControllingExpr = ControllingExpr->IgnoreParens();
1668     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1669         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1670     return ExprError();
1671   }
1672 
1673   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1674   // type name that is compatible with the type of the controlling expression,
1675   // then the result expression of the generic selection is the expression
1676   // in that generic association. Otherwise, the result expression of the
1677   // generic selection is the expression in the default generic association."
1678   unsigned ResultIndex =
1679     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1680 
1681   return GenericSelectionExpr::Create(
1682       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1683       ContainsUnexpandedParameterPack, ResultIndex);
1684 }
1685 
1686 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1687 /// location of the token and the offset of the ud-suffix within it.
1688 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1689                                      unsigned Offset) {
1690   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1691                                         S.getLangOpts());
1692 }
1693 
1694 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1695 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1696 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1697                                                  IdentifierInfo *UDSuffix,
1698                                                  SourceLocation UDSuffixLoc,
1699                                                  ArrayRef<Expr*> Args,
1700                                                  SourceLocation LitEndLoc) {
1701   assert(Args.size() <= 2 && "too many arguments for literal operator");
1702 
1703   QualType ArgTy[2];
1704   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1705     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1706     if (ArgTy[ArgIdx]->isArrayType())
1707       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1708   }
1709 
1710   DeclarationName OpName =
1711     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1712   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1713   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1714 
1715   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1716   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1717                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1718                               /*AllowStringTemplate*/ false,
1719                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1720     return ExprError();
1721 
1722   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1723 }
1724 
1725 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1726 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1727 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1728 /// multiple tokens.  However, the common case is that StringToks points to one
1729 /// string.
1730 ///
1731 ExprResult
1732 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1733   assert(!StringToks.empty() && "Must have at least one string!");
1734 
1735   StringLiteralParser Literal(StringToks, PP);
1736   if (Literal.hadError)
1737     return ExprError();
1738 
1739   SmallVector<SourceLocation, 4> StringTokLocs;
1740   for (const Token &Tok : StringToks)
1741     StringTokLocs.push_back(Tok.getLocation());
1742 
1743   QualType CharTy = Context.CharTy;
1744   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1745   if (Literal.isWide()) {
1746     CharTy = Context.getWideCharType();
1747     Kind = StringLiteral::Wide;
1748   } else if (Literal.isUTF8()) {
1749     if (getLangOpts().Char8)
1750       CharTy = Context.Char8Ty;
1751     Kind = StringLiteral::UTF8;
1752   } else if (Literal.isUTF16()) {
1753     CharTy = Context.Char16Ty;
1754     Kind = StringLiteral::UTF16;
1755   } else if (Literal.isUTF32()) {
1756     CharTy = Context.Char32Ty;
1757     Kind = StringLiteral::UTF32;
1758   } else if (Literal.isPascal()) {
1759     CharTy = Context.UnsignedCharTy;
1760   }
1761 
1762   // Warn on initializing an array of char from a u8 string literal; this
1763   // becomes ill-formed in C++2a.
1764   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1765       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1766     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1767 
1768     // Create removals for all 'u8' prefixes in the string literal(s). This
1769     // ensures C++2a compatibility (but may change the program behavior when
1770     // built by non-Clang compilers for which the execution character set is
1771     // not always UTF-8).
1772     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1773     SourceLocation RemovalDiagLoc;
1774     for (const Token &Tok : StringToks) {
1775       if (Tok.getKind() == tok::utf8_string_literal) {
1776         if (RemovalDiagLoc.isInvalid())
1777           RemovalDiagLoc = Tok.getLocation();
1778         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1779             Tok.getLocation(),
1780             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1781                                            getSourceManager(), getLangOpts())));
1782       }
1783     }
1784     Diag(RemovalDiagLoc, RemovalDiag);
1785   }
1786 
1787   QualType StrTy =
1788       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1789 
1790   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1791   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1792                                              Kind, Literal.Pascal, StrTy,
1793                                              &StringTokLocs[0],
1794                                              StringTokLocs.size());
1795   if (Literal.getUDSuffix().empty())
1796     return Lit;
1797 
1798   // We're building a user-defined literal.
1799   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1800   SourceLocation UDSuffixLoc =
1801     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1802                    Literal.getUDSuffixOffset());
1803 
1804   // Make sure we're allowed user-defined literals here.
1805   if (!UDLScope)
1806     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1807 
1808   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1809   //   operator "" X (str, len)
1810   QualType SizeType = Context.getSizeType();
1811 
1812   DeclarationName OpName =
1813     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1814   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1815   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1816 
1817   QualType ArgTy[] = {
1818     Context.getArrayDecayedType(StrTy), SizeType
1819   };
1820 
1821   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1822   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1823                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1824                                 /*AllowStringTemplate*/ true,
1825                                 /*DiagnoseMissing*/ true)) {
1826 
1827   case LOLR_Cooked: {
1828     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1829     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1830                                                     StringTokLocs[0]);
1831     Expr *Args[] = { Lit, LenArg };
1832 
1833     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1834   }
1835 
1836   case LOLR_StringTemplate: {
1837     TemplateArgumentListInfo ExplicitArgs;
1838 
1839     unsigned CharBits = Context.getIntWidth(CharTy);
1840     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1841     llvm::APSInt Value(CharBits, CharIsUnsigned);
1842 
1843     TemplateArgument TypeArg(CharTy);
1844     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1845     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1846 
1847     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1848       Value = Lit->getCodeUnit(I);
1849       TemplateArgument Arg(Context, Value, CharTy);
1850       TemplateArgumentLocInfo ArgInfo;
1851       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1852     }
1853     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1854                                     &ExplicitArgs);
1855   }
1856   case LOLR_Raw:
1857   case LOLR_Template:
1858   case LOLR_ErrorNoDiagnostic:
1859     llvm_unreachable("unexpected literal operator lookup result");
1860   case LOLR_Error:
1861     return ExprError();
1862   }
1863   llvm_unreachable("unexpected literal operator lookup result");
1864 }
1865 
1866 DeclRefExpr *
1867 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1868                        SourceLocation Loc,
1869                        const CXXScopeSpec *SS) {
1870   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1871   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1872 }
1873 
1874 DeclRefExpr *
1875 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1876                        const DeclarationNameInfo &NameInfo,
1877                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1878                        SourceLocation TemplateKWLoc,
1879                        const TemplateArgumentListInfo *TemplateArgs) {
1880   NestedNameSpecifierLoc NNS =
1881       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1882   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1883                           TemplateArgs);
1884 }
1885 
1886 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1887   // A declaration named in an unevaluated operand never constitutes an odr-use.
1888   if (isUnevaluatedContext())
1889     return NOUR_Unevaluated;
1890 
1891   // C++2a [basic.def.odr]p4:
1892   //   A variable x whose name appears as a potentially-evaluated expression e
1893   //   is odr-used by e unless [...] x is a reference that is usable in
1894   //   constant expressions.
1895   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1896     if (VD->getType()->isReferenceType() &&
1897         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1898         VD->isUsableInConstantExpressions(Context))
1899       return NOUR_Constant;
1900   }
1901 
1902   // All remaining non-variable cases constitute an odr-use. For variables, we
1903   // need to wait and see how the expression is used.
1904   return NOUR_None;
1905 }
1906 
1907 /// BuildDeclRefExpr - Build an expression that references a
1908 /// declaration that does not require a closure capture.
1909 DeclRefExpr *
1910 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1911                        const DeclarationNameInfo &NameInfo,
1912                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1913                        SourceLocation TemplateKWLoc,
1914                        const TemplateArgumentListInfo *TemplateArgs) {
1915   bool RefersToCapturedVariable =
1916       isa<VarDecl>(D) &&
1917       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1918 
1919   DeclRefExpr *E = DeclRefExpr::Create(
1920       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1921       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1922   MarkDeclRefReferenced(E);
1923 
1924   // C++ [except.spec]p17:
1925   //   An exception-specification is considered to be needed when:
1926   //   - in an expression, the function is the unique lookup result or
1927   //     the selected member of a set of overloaded functions.
1928   //
1929   // We delay doing this until after we've built the function reference and
1930   // marked it as used so that:
1931   //  a) if the function is defaulted, we get errors from defining it before /
1932   //     instead of errors from computing its exception specification, and
1933   //  b) if the function is a defaulted comparison, we can use the body we
1934   //     build when defining it as input to the exception specification
1935   //     computation rather than computing a new body.
1936   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1937     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1938       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1939         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1940     }
1941   }
1942 
1943   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1944       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1945       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1946     getCurFunction()->recordUseOfWeak(E);
1947 
1948   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1949   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1950     FD = IFD->getAnonField();
1951   if (FD) {
1952     UnusedPrivateFields.remove(FD);
1953     // Just in case we're building an illegal pointer-to-member.
1954     if (FD->isBitField())
1955       E->setObjectKind(OK_BitField);
1956   }
1957 
1958   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1959   // designates a bit-field.
1960   if (auto *BD = dyn_cast<BindingDecl>(D))
1961     if (auto *BE = BD->getBinding())
1962       E->setObjectKind(BE->getObjectKind());
1963 
1964   return E;
1965 }
1966 
1967 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1968 /// possibly a list of template arguments.
1969 ///
1970 /// If this produces template arguments, it is permitted to call
1971 /// DecomposeTemplateName.
1972 ///
1973 /// This actually loses a lot of source location information for
1974 /// non-standard name kinds; we should consider preserving that in
1975 /// some way.
1976 void
1977 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1978                              TemplateArgumentListInfo &Buffer,
1979                              DeclarationNameInfo &NameInfo,
1980                              const TemplateArgumentListInfo *&TemplateArgs) {
1981   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1982     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1983     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1984 
1985     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1986                                        Id.TemplateId->NumArgs);
1987     translateTemplateArguments(TemplateArgsPtr, Buffer);
1988 
1989     TemplateName TName = Id.TemplateId->Template.get();
1990     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1991     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1992     TemplateArgs = &Buffer;
1993   } else {
1994     NameInfo = GetNameFromUnqualifiedId(Id);
1995     TemplateArgs = nullptr;
1996   }
1997 }
1998 
1999 static void emitEmptyLookupTypoDiagnostic(
2000     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2001     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2002     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2003   DeclContext *Ctx =
2004       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2005   if (!TC) {
2006     // Emit a special diagnostic for failed member lookups.
2007     // FIXME: computing the declaration context might fail here (?)
2008     if (Ctx)
2009       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2010                                                  << SS.getRange();
2011     else
2012       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2013     return;
2014   }
2015 
2016   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2017   bool DroppedSpecifier =
2018       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2019   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2020                         ? diag::note_implicit_param_decl
2021                         : diag::note_previous_decl;
2022   if (!Ctx)
2023     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2024                          SemaRef.PDiag(NoteID));
2025   else
2026     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2027                                  << Typo << Ctx << DroppedSpecifier
2028                                  << SS.getRange(),
2029                          SemaRef.PDiag(NoteID));
2030 }
2031 
2032 /// Diagnose an empty lookup.
2033 ///
2034 /// \return false if new lookup candidates were found
2035 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2036                                CorrectionCandidateCallback &CCC,
2037                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2038                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2039   DeclarationName Name = R.getLookupName();
2040 
2041   unsigned diagnostic = diag::err_undeclared_var_use;
2042   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2043   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2044       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2045       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2046     diagnostic = diag::err_undeclared_use;
2047     diagnostic_suggest = diag::err_undeclared_use_suggest;
2048   }
2049 
2050   // If the original lookup was an unqualified lookup, fake an
2051   // unqualified lookup.  This is useful when (for example) the
2052   // original lookup would not have found something because it was a
2053   // dependent name.
2054   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2055   while (DC) {
2056     if (isa<CXXRecordDecl>(DC)) {
2057       LookupQualifiedName(R, DC);
2058 
2059       if (!R.empty()) {
2060         // Don't give errors about ambiguities in this lookup.
2061         R.suppressDiagnostics();
2062 
2063         // During a default argument instantiation the CurContext points
2064         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2065         // function parameter list, hence add an explicit check.
2066         bool isDefaultArgument =
2067             !CodeSynthesisContexts.empty() &&
2068             CodeSynthesisContexts.back().Kind ==
2069                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2070         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2071         bool isInstance = CurMethod &&
2072                           CurMethod->isInstance() &&
2073                           DC == CurMethod->getParent() && !isDefaultArgument;
2074 
2075         // Give a code modification hint to insert 'this->'.
2076         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2077         // Actually quite difficult!
2078         if (getLangOpts().MSVCCompat)
2079           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2080         if (isInstance) {
2081           Diag(R.getNameLoc(), diagnostic) << Name
2082             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2083           CheckCXXThisCapture(R.getNameLoc());
2084         } else {
2085           Diag(R.getNameLoc(), diagnostic) << Name;
2086         }
2087 
2088         // Do we really want to note all of these?
2089         for (NamedDecl *D : R)
2090           Diag(D->getLocation(), diag::note_dependent_var_use);
2091 
2092         // Return true if we are inside a default argument instantiation
2093         // and the found name refers to an instance member function, otherwise
2094         // the function calling DiagnoseEmptyLookup will try to create an
2095         // implicit member call and this is wrong for default argument.
2096         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2097           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2098           return true;
2099         }
2100 
2101         // Tell the callee to try to recover.
2102         return false;
2103       }
2104 
2105       R.clear();
2106     }
2107 
2108     DC = DC->getLookupParent();
2109   }
2110 
2111   // We didn't find anything, so try to correct for a typo.
2112   TypoCorrection Corrected;
2113   if (S && Out) {
2114     SourceLocation TypoLoc = R.getNameLoc();
2115     assert(!ExplicitTemplateArgs &&
2116            "Diagnosing an empty lookup with explicit template args!");
2117     *Out = CorrectTypoDelayed(
2118         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2119         [=](const TypoCorrection &TC) {
2120           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2121                                         diagnostic, diagnostic_suggest);
2122         },
2123         nullptr, CTK_ErrorRecovery);
2124     if (*Out)
2125       return true;
2126   } else if (S &&
2127              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2128                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2129     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2130     bool DroppedSpecifier =
2131         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2132     R.setLookupName(Corrected.getCorrection());
2133 
2134     bool AcceptableWithRecovery = false;
2135     bool AcceptableWithoutRecovery = false;
2136     NamedDecl *ND = Corrected.getFoundDecl();
2137     if (ND) {
2138       if (Corrected.isOverloaded()) {
2139         OverloadCandidateSet OCS(R.getNameLoc(),
2140                                  OverloadCandidateSet::CSK_Normal);
2141         OverloadCandidateSet::iterator Best;
2142         for (NamedDecl *CD : Corrected) {
2143           if (FunctionTemplateDecl *FTD =
2144                    dyn_cast<FunctionTemplateDecl>(CD))
2145             AddTemplateOverloadCandidate(
2146                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2147                 Args, OCS);
2148           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2149             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2150               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2151                                    Args, OCS);
2152         }
2153         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2154         case OR_Success:
2155           ND = Best->FoundDecl;
2156           Corrected.setCorrectionDecl(ND);
2157           break;
2158         default:
2159           // FIXME: Arbitrarily pick the first declaration for the note.
2160           Corrected.setCorrectionDecl(ND);
2161           break;
2162         }
2163       }
2164       R.addDecl(ND);
2165       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2166         CXXRecordDecl *Record = nullptr;
2167         if (Corrected.getCorrectionSpecifier()) {
2168           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2169           Record = Ty->getAsCXXRecordDecl();
2170         }
2171         if (!Record)
2172           Record = cast<CXXRecordDecl>(
2173               ND->getDeclContext()->getRedeclContext());
2174         R.setNamingClass(Record);
2175       }
2176 
2177       auto *UnderlyingND = ND->getUnderlyingDecl();
2178       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2179                                isa<FunctionTemplateDecl>(UnderlyingND);
2180       // FIXME: If we ended up with a typo for a type name or
2181       // Objective-C class name, we're in trouble because the parser
2182       // is in the wrong place to recover. Suggest the typo
2183       // correction, but don't make it a fix-it since we're not going
2184       // to recover well anyway.
2185       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2186                                   getAsTypeTemplateDecl(UnderlyingND) ||
2187                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2188     } else {
2189       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2190       // because we aren't able to recover.
2191       AcceptableWithoutRecovery = true;
2192     }
2193 
2194     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2195       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2196                             ? diag::note_implicit_param_decl
2197                             : diag::note_previous_decl;
2198       if (SS.isEmpty())
2199         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2200                      PDiag(NoteID), AcceptableWithRecovery);
2201       else
2202         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2203                                   << Name << computeDeclContext(SS, false)
2204                                   << DroppedSpecifier << SS.getRange(),
2205                      PDiag(NoteID), AcceptableWithRecovery);
2206 
2207       // Tell the callee whether to try to recover.
2208       return !AcceptableWithRecovery;
2209     }
2210   }
2211   R.clear();
2212 
2213   // Emit a special diagnostic for failed member lookups.
2214   // FIXME: computing the declaration context might fail here (?)
2215   if (!SS.isEmpty()) {
2216     Diag(R.getNameLoc(), diag::err_no_member)
2217       << Name << computeDeclContext(SS, false)
2218       << SS.getRange();
2219     return true;
2220   }
2221 
2222   // Give up, we can't recover.
2223   Diag(R.getNameLoc(), diagnostic) << Name;
2224   return true;
2225 }
2226 
2227 /// In Microsoft mode, if we are inside a template class whose parent class has
2228 /// dependent base classes, and we can't resolve an unqualified identifier, then
2229 /// assume the identifier is a member of a dependent base class.  We can only
2230 /// recover successfully in static methods, instance methods, and other contexts
2231 /// where 'this' is available.  This doesn't precisely match MSVC's
2232 /// instantiation model, but it's close enough.
2233 static Expr *
2234 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2235                                DeclarationNameInfo &NameInfo,
2236                                SourceLocation TemplateKWLoc,
2237                                const TemplateArgumentListInfo *TemplateArgs) {
2238   // Only try to recover from lookup into dependent bases in static methods or
2239   // contexts where 'this' is available.
2240   QualType ThisType = S.getCurrentThisType();
2241   const CXXRecordDecl *RD = nullptr;
2242   if (!ThisType.isNull())
2243     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2244   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2245     RD = MD->getParent();
2246   if (!RD || !RD->hasAnyDependentBases())
2247     return nullptr;
2248 
2249   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2250   // is available, suggest inserting 'this->' as a fixit.
2251   SourceLocation Loc = NameInfo.getLoc();
2252   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2253   DB << NameInfo.getName() << RD;
2254 
2255   if (!ThisType.isNull()) {
2256     DB << FixItHint::CreateInsertion(Loc, "this->");
2257     return CXXDependentScopeMemberExpr::Create(
2258         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2259         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2260         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2261   }
2262 
2263   // Synthesize a fake NNS that points to the derived class.  This will
2264   // perform name lookup during template instantiation.
2265   CXXScopeSpec SS;
2266   auto *NNS =
2267       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2268   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2269   return DependentScopeDeclRefExpr::Create(
2270       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2271       TemplateArgs);
2272 }
2273 
2274 ExprResult
2275 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2276                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2277                         bool HasTrailingLParen, bool IsAddressOfOperand,
2278                         CorrectionCandidateCallback *CCC,
2279                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2280   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2281          "cannot be direct & operand and have a trailing lparen");
2282   if (SS.isInvalid())
2283     return ExprError();
2284 
2285   TemplateArgumentListInfo TemplateArgsBuffer;
2286 
2287   // Decompose the UnqualifiedId into the following data.
2288   DeclarationNameInfo NameInfo;
2289   const TemplateArgumentListInfo *TemplateArgs;
2290   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2291 
2292   DeclarationName Name = NameInfo.getName();
2293   IdentifierInfo *II = Name.getAsIdentifierInfo();
2294   SourceLocation NameLoc = NameInfo.getLoc();
2295 
2296   if (II && II->isEditorPlaceholder()) {
2297     // FIXME: When typed placeholders are supported we can create a typed
2298     // placeholder expression node.
2299     return ExprError();
2300   }
2301 
2302   // C++ [temp.dep.expr]p3:
2303   //   An id-expression is type-dependent if it contains:
2304   //     -- an identifier that was declared with a dependent type,
2305   //        (note: handled after lookup)
2306   //     -- a template-id that is dependent,
2307   //        (note: handled in BuildTemplateIdExpr)
2308   //     -- a conversion-function-id that specifies a dependent type,
2309   //     -- a nested-name-specifier that contains a class-name that
2310   //        names a dependent type.
2311   // Determine whether this is a member of an unknown specialization;
2312   // we need to handle these differently.
2313   bool DependentID = false;
2314   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2315       Name.getCXXNameType()->isDependentType()) {
2316     DependentID = true;
2317   } else if (SS.isSet()) {
2318     if (DeclContext *DC = computeDeclContext(SS, false)) {
2319       if (RequireCompleteDeclContext(SS, DC))
2320         return ExprError();
2321     } else {
2322       DependentID = true;
2323     }
2324   }
2325 
2326   if (DependentID)
2327     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2328                                       IsAddressOfOperand, TemplateArgs);
2329 
2330   // Perform the required lookup.
2331   LookupResult R(*this, NameInfo,
2332                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2333                      ? LookupObjCImplicitSelfParam
2334                      : LookupOrdinaryName);
2335   if (TemplateKWLoc.isValid() || TemplateArgs) {
2336     // Lookup the template name again to correctly establish the context in
2337     // which it was found. This is really unfortunate as we already did the
2338     // lookup to determine that it was a template name in the first place. If
2339     // this becomes a performance hit, we can work harder to preserve those
2340     // results until we get here but it's likely not worth it.
2341     bool MemberOfUnknownSpecialization;
2342     AssumedTemplateKind AssumedTemplate;
2343     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2344                            MemberOfUnknownSpecialization, TemplateKWLoc,
2345                            &AssumedTemplate))
2346       return ExprError();
2347 
2348     if (MemberOfUnknownSpecialization ||
2349         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2350       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2351                                         IsAddressOfOperand, TemplateArgs);
2352   } else {
2353     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2354     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2355 
2356     // If the result might be in a dependent base class, this is a dependent
2357     // id-expression.
2358     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2359       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360                                         IsAddressOfOperand, TemplateArgs);
2361 
2362     // If this reference is in an Objective-C method, then we need to do
2363     // some special Objective-C lookup, too.
2364     if (IvarLookupFollowUp) {
2365       ExprResult E(LookupInObjCMethod(R, S, II, true));
2366       if (E.isInvalid())
2367         return ExprError();
2368 
2369       if (Expr *Ex = E.getAs<Expr>())
2370         return Ex;
2371     }
2372   }
2373 
2374   if (R.isAmbiguous())
2375     return ExprError();
2376 
2377   // This could be an implicitly declared function reference (legal in C90,
2378   // extension in C99, forbidden in C++).
2379   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2380     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2381     if (D) R.addDecl(D);
2382   }
2383 
2384   // Determine whether this name might be a candidate for
2385   // argument-dependent lookup.
2386   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2387 
2388   if (R.empty() && !ADL) {
2389     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2390       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2391                                                    TemplateKWLoc, TemplateArgs))
2392         return E;
2393     }
2394 
2395     // Don't diagnose an empty lookup for inline assembly.
2396     if (IsInlineAsmIdentifier)
2397       return ExprError();
2398 
2399     // If this name wasn't predeclared and if this is not a function
2400     // call, diagnose the problem.
2401     TypoExpr *TE = nullptr;
2402     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2403                                                        : nullptr);
2404     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2405     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2406            "Typo correction callback misconfigured");
2407     if (CCC) {
2408       // Make sure the callback knows what the typo being diagnosed is.
2409       CCC->setTypoName(II);
2410       if (SS.isValid())
2411         CCC->setTypoNNS(SS.getScopeRep());
2412     }
2413     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2414     // a template name, but we happen to have always already looked up the name
2415     // before we get here if it must be a template name.
2416     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2417                             None, &TE)) {
2418       if (TE && KeywordReplacement) {
2419         auto &State = getTypoExprState(TE);
2420         auto BestTC = State.Consumer->getNextCorrection();
2421         if (BestTC.isKeyword()) {
2422           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2423           if (State.DiagHandler)
2424             State.DiagHandler(BestTC);
2425           KeywordReplacement->startToken();
2426           KeywordReplacement->setKind(II->getTokenID());
2427           KeywordReplacement->setIdentifierInfo(II);
2428           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2429           // Clean up the state associated with the TypoExpr, since it has
2430           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2431           clearDelayedTypo(TE);
2432           // Signal that a correction to a keyword was performed by returning a
2433           // valid-but-null ExprResult.
2434           return (Expr*)nullptr;
2435         }
2436         State.Consumer->resetCorrectionStream();
2437       }
2438       return TE ? TE : ExprError();
2439     }
2440 
2441     assert(!R.empty() &&
2442            "DiagnoseEmptyLookup returned false but added no results");
2443 
2444     // If we found an Objective-C instance variable, let
2445     // LookupInObjCMethod build the appropriate expression to
2446     // reference the ivar.
2447     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2448       R.clear();
2449       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2450       // In a hopelessly buggy code, Objective-C instance variable
2451       // lookup fails and no expression will be built to reference it.
2452       if (!E.isInvalid() && !E.get())
2453         return ExprError();
2454       return E;
2455     }
2456   }
2457 
2458   // This is guaranteed from this point on.
2459   assert(!R.empty() || ADL);
2460 
2461   // Check whether this might be a C++ implicit instance member access.
2462   // C++ [class.mfct.non-static]p3:
2463   //   When an id-expression that is not part of a class member access
2464   //   syntax and not used to form a pointer to member is used in the
2465   //   body of a non-static member function of class X, if name lookup
2466   //   resolves the name in the id-expression to a non-static non-type
2467   //   member of some class C, the id-expression is transformed into a
2468   //   class member access expression using (*this) as the
2469   //   postfix-expression to the left of the . operator.
2470   //
2471   // But we don't actually need to do this for '&' operands if R
2472   // resolved to a function or overloaded function set, because the
2473   // expression is ill-formed if it actually works out to be a
2474   // non-static member function:
2475   //
2476   // C++ [expr.ref]p4:
2477   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2478   //   [t]he expression can be used only as the left-hand operand of a
2479   //   member function call.
2480   //
2481   // There are other safeguards against such uses, but it's important
2482   // to get this right here so that we don't end up making a
2483   // spuriously dependent expression if we're inside a dependent
2484   // instance method.
2485   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2486     bool MightBeImplicitMember;
2487     if (!IsAddressOfOperand)
2488       MightBeImplicitMember = true;
2489     else if (!SS.isEmpty())
2490       MightBeImplicitMember = false;
2491     else if (R.isOverloadedResult())
2492       MightBeImplicitMember = false;
2493     else if (R.isUnresolvableResult())
2494       MightBeImplicitMember = true;
2495     else
2496       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2497                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2498                               isa<MSPropertyDecl>(R.getFoundDecl());
2499 
2500     if (MightBeImplicitMember)
2501       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2502                                              R, TemplateArgs, S);
2503   }
2504 
2505   if (TemplateArgs || TemplateKWLoc.isValid()) {
2506 
2507     // In C++1y, if this is a variable template id, then check it
2508     // in BuildTemplateIdExpr().
2509     // The single lookup result must be a variable template declaration.
2510     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2511         Id.TemplateId->Kind == TNK_Var_template) {
2512       assert(R.getAsSingle<VarTemplateDecl>() &&
2513              "There should only be one declaration found.");
2514     }
2515 
2516     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2517   }
2518 
2519   return BuildDeclarationNameExpr(SS, R, ADL);
2520 }
2521 
2522 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2523 /// declaration name, generally during template instantiation.
2524 /// There's a large number of things which don't need to be done along
2525 /// this path.
2526 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2527     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2528     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2529   DeclContext *DC = computeDeclContext(SS, false);
2530   if (!DC)
2531     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2532                                      NameInfo, /*TemplateArgs=*/nullptr);
2533 
2534   if (RequireCompleteDeclContext(SS, DC))
2535     return ExprError();
2536 
2537   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2538   LookupQualifiedName(R, DC);
2539 
2540   if (R.isAmbiguous())
2541     return ExprError();
2542 
2543   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2544     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2545                                      NameInfo, /*TemplateArgs=*/nullptr);
2546 
2547   if (R.empty()) {
2548     Diag(NameInfo.getLoc(), diag::err_no_member)
2549       << NameInfo.getName() << DC << SS.getRange();
2550     return ExprError();
2551   }
2552 
2553   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2554     // Diagnose a missing typename if this resolved unambiguously to a type in
2555     // a dependent context.  If we can recover with a type, downgrade this to
2556     // a warning in Microsoft compatibility mode.
2557     unsigned DiagID = diag::err_typename_missing;
2558     if (RecoveryTSI && getLangOpts().MSVCCompat)
2559       DiagID = diag::ext_typename_missing;
2560     SourceLocation Loc = SS.getBeginLoc();
2561     auto D = Diag(Loc, DiagID);
2562     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2563       << SourceRange(Loc, NameInfo.getEndLoc());
2564 
2565     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2566     // context.
2567     if (!RecoveryTSI)
2568       return ExprError();
2569 
2570     // Only issue the fixit if we're prepared to recover.
2571     D << FixItHint::CreateInsertion(Loc, "typename ");
2572 
2573     // Recover by pretending this was an elaborated type.
2574     QualType Ty = Context.getTypeDeclType(TD);
2575     TypeLocBuilder TLB;
2576     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2577 
2578     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2579     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2580     QTL.setElaboratedKeywordLoc(SourceLocation());
2581     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2582 
2583     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2584 
2585     return ExprEmpty();
2586   }
2587 
2588   // Defend against this resolving to an implicit member access. We usually
2589   // won't get here if this might be a legitimate a class member (we end up in
2590   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2591   // a pointer-to-member or in an unevaluated context in C++11.
2592   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2593     return BuildPossibleImplicitMemberExpr(SS,
2594                                            /*TemplateKWLoc=*/SourceLocation(),
2595                                            R, /*TemplateArgs=*/nullptr, S);
2596 
2597   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2598 }
2599 
2600 /// The parser has read a name in, and Sema has detected that we're currently
2601 /// inside an ObjC method. Perform some additional checks and determine if we
2602 /// should form a reference to an ivar.
2603 ///
2604 /// Ideally, most of this would be done by lookup, but there's
2605 /// actually quite a lot of extra work involved.
2606 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2607                                         IdentifierInfo *II) {
2608   SourceLocation Loc = Lookup.getNameLoc();
2609   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2610 
2611   // Check for error condition which is already reported.
2612   if (!CurMethod)
2613     return DeclResult(true);
2614 
2615   // There are two cases to handle here.  1) scoped lookup could have failed,
2616   // in which case we should look for an ivar.  2) scoped lookup could have
2617   // found a decl, but that decl is outside the current instance method (i.e.
2618   // a global variable).  In these two cases, we do a lookup for an ivar with
2619   // this name, if the lookup sucedes, we replace it our current decl.
2620 
2621   // If we're in a class method, we don't normally want to look for
2622   // ivars.  But if we don't find anything else, and there's an
2623   // ivar, that's an error.
2624   bool IsClassMethod = CurMethod->isClassMethod();
2625 
2626   bool LookForIvars;
2627   if (Lookup.empty())
2628     LookForIvars = true;
2629   else if (IsClassMethod)
2630     LookForIvars = false;
2631   else
2632     LookForIvars = (Lookup.isSingleResult() &&
2633                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2634   ObjCInterfaceDecl *IFace = nullptr;
2635   if (LookForIvars) {
2636     IFace = CurMethod->getClassInterface();
2637     ObjCInterfaceDecl *ClassDeclared;
2638     ObjCIvarDecl *IV = nullptr;
2639     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2640       // Diagnose using an ivar in a class method.
2641       if (IsClassMethod) {
2642         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2643         return DeclResult(true);
2644       }
2645 
2646       // Diagnose the use of an ivar outside of the declaring class.
2647       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2648           !declaresSameEntity(ClassDeclared, IFace) &&
2649           !getLangOpts().DebuggerSupport)
2650         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2651 
2652       // Success.
2653       return IV;
2654     }
2655   } else if (CurMethod->isInstanceMethod()) {
2656     // We should warn if a local variable hides an ivar.
2657     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2658       ObjCInterfaceDecl *ClassDeclared;
2659       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2660         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2661             declaresSameEntity(IFace, ClassDeclared))
2662           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2663       }
2664     }
2665   } else if (Lookup.isSingleResult() &&
2666              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2667     // If accessing a stand-alone ivar in a class method, this is an error.
2668     if (const ObjCIvarDecl *IV =
2669             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2670       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2671       return DeclResult(true);
2672     }
2673   }
2674 
2675   // Didn't encounter an error, didn't find an ivar.
2676   return DeclResult(false);
2677 }
2678 
2679 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2680                                   ObjCIvarDecl *IV) {
2681   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2682   assert(CurMethod && CurMethod->isInstanceMethod() &&
2683          "should not reference ivar from this context");
2684 
2685   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2686   assert(IFace && "should not reference ivar from this context");
2687 
2688   // If we're referencing an invalid decl, just return this as a silent
2689   // error node.  The error diagnostic was already emitted on the decl.
2690   if (IV->isInvalidDecl())
2691     return ExprError();
2692 
2693   // Check if referencing a field with __attribute__((deprecated)).
2694   if (DiagnoseUseOfDecl(IV, Loc))
2695     return ExprError();
2696 
2697   // FIXME: This should use a new expr for a direct reference, don't
2698   // turn this into Self->ivar, just return a BareIVarExpr or something.
2699   IdentifierInfo &II = Context.Idents.get("self");
2700   UnqualifiedId SelfName;
2701   SelfName.setIdentifier(&II, SourceLocation());
2702   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2703   CXXScopeSpec SelfScopeSpec;
2704   SourceLocation TemplateKWLoc;
2705   ExprResult SelfExpr =
2706       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2707                         /*HasTrailingLParen=*/false,
2708                         /*IsAddressOfOperand=*/false);
2709   if (SelfExpr.isInvalid())
2710     return ExprError();
2711 
2712   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2713   if (SelfExpr.isInvalid())
2714     return ExprError();
2715 
2716   MarkAnyDeclReferenced(Loc, IV, true);
2717 
2718   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2719   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2720       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2721     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2722 
2723   ObjCIvarRefExpr *Result = new (Context)
2724       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2725                       IV->getLocation(), SelfExpr.get(), true, true);
2726 
2727   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2728     if (!isUnevaluatedContext() &&
2729         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2730       getCurFunction()->recordUseOfWeak(Result);
2731   }
2732   if (getLangOpts().ObjCAutoRefCount)
2733     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2734       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2735 
2736   return Result;
2737 }
2738 
2739 /// The parser has read a name in, and Sema has detected that we're currently
2740 /// inside an ObjC method. Perform some additional checks and determine if we
2741 /// should form a reference to an ivar. If so, build an expression referencing
2742 /// that ivar.
2743 ExprResult
2744 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2745                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2746   // FIXME: Integrate this lookup step into LookupParsedName.
2747   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2748   if (Ivar.isInvalid())
2749     return ExprError();
2750   if (Ivar.isUsable())
2751     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2752                             cast<ObjCIvarDecl>(Ivar.get()));
2753 
2754   if (Lookup.empty() && II && AllowBuiltinCreation)
2755     LookupBuiltin(Lookup);
2756 
2757   // Sentinel value saying that we didn't do anything special.
2758   return ExprResult(false);
2759 }
2760 
2761 /// Cast a base object to a member's actual type.
2762 ///
2763 /// Logically this happens in three phases:
2764 ///
2765 /// * First we cast from the base type to the naming class.
2766 ///   The naming class is the class into which we were looking
2767 ///   when we found the member;  it's the qualifier type if a
2768 ///   qualifier was provided, and otherwise it's the base type.
2769 ///
2770 /// * Next we cast from the naming class to the declaring class.
2771 ///   If the member we found was brought into a class's scope by
2772 ///   a using declaration, this is that class;  otherwise it's
2773 ///   the class declaring the member.
2774 ///
2775 /// * Finally we cast from the declaring class to the "true"
2776 ///   declaring class of the member.  This conversion does not
2777 ///   obey access control.
2778 ExprResult
2779 Sema::PerformObjectMemberConversion(Expr *From,
2780                                     NestedNameSpecifier *Qualifier,
2781                                     NamedDecl *FoundDecl,
2782                                     NamedDecl *Member) {
2783   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2784   if (!RD)
2785     return From;
2786 
2787   QualType DestRecordType;
2788   QualType DestType;
2789   QualType FromRecordType;
2790   QualType FromType = From->getType();
2791   bool PointerConversions = false;
2792   if (isa<FieldDecl>(Member)) {
2793     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2794     auto FromPtrType = FromType->getAs<PointerType>();
2795     DestRecordType = Context.getAddrSpaceQualType(
2796         DestRecordType, FromPtrType
2797                             ? FromType->getPointeeType().getAddressSpace()
2798                             : FromType.getAddressSpace());
2799 
2800     if (FromPtrType) {
2801       DestType = Context.getPointerType(DestRecordType);
2802       FromRecordType = FromPtrType->getPointeeType();
2803       PointerConversions = true;
2804     } else {
2805       DestType = DestRecordType;
2806       FromRecordType = FromType;
2807     }
2808   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2809     if (Method->isStatic())
2810       return From;
2811 
2812     DestType = Method->getThisType();
2813     DestRecordType = DestType->getPointeeType();
2814 
2815     if (FromType->getAs<PointerType>()) {
2816       FromRecordType = FromType->getPointeeType();
2817       PointerConversions = true;
2818     } else {
2819       FromRecordType = FromType;
2820       DestType = DestRecordType;
2821     }
2822 
2823     LangAS FromAS = FromRecordType.getAddressSpace();
2824     LangAS DestAS = DestRecordType.getAddressSpace();
2825     if (FromAS != DestAS) {
2826       QualType FromRecordTypeWithoutAS =
2827           Context.removeAddrSpaceQualType(FromRecordType);
2828       QualType FromTypeWithDestAS =
2829           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2830       if (PointerConversions)
2831         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2832       From = ImpCastExprToType(From, FromTypeWithDestAS,
2833                                CK_AddressSpaceConversion, From->getValueKind())
2834                  .get();
2835     }
2836   } else {
2837     // No conversion necessary.
2838     return From;
2839   }
2840 
2841   if (DestType->isDependentType() || FromType->isDependentType())
2842     return From;
2843 
2844   // If the unqualified types are the same, no conversion is necessary.
2845   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2846     return From;
2847 
2848   SourceRange FromRange = From->getSourceRange();
2849   SourceLocation FromLoc = FromRange.getBegin();
2850 
2851   ExprValueKind VK = From->getValueKind();
2852 
2853   // C++ [class.member.lookup]p8:
2854   //   [...] Ambiguities can often be resolved by qualifying a name with its
2855   //   class name.
2856   //
2857   // If the member was a qualified name and the qualified referred to a
2858   // specific base subobject type, we'll cast to that intermediate type
2859   // first and then to the object in which the member is declared. That allows
2860   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2861   //
2862   //   class Base { public: int x; };
2863   //   class Derived1 : public Base { };
2864   //   class Derived2 : public Base { };
2865   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2866   //
2867   //   void VeryDerived::f() {
2868   //     x = 17; // error: ambiguous base subobjects
2869   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2870   //   }
2871   if (Qualifier && Qualifier->getAsType()) {
2872     QualType QType = QualType(Qualifier->getAsType(), 0);
2873     assert(QType->isRecordType() && "lookup done with non-record type");
2874 
2875     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2876 
2877     // In C++98, the qualifier type doesn't actually have to be a base
2878     // type of the object type, in which case we just ignore it.
2879     // Otherwise build the appropriate casts.
2880     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2881       CXXCastPath BasePath;
2882       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2883                                        FromLoc, FromRange, &BasePath))
2884         return ExprError();
2885 
2886       if (PointerConversions)
2887         QType = Context.getPointerType(QType);
2888       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2889                                VK, &BasePath).get();
2890 
2891       FromType = QType;
2892       FromRecordType = QRecordType;
2893 
2894       // If the qualifier type was the same as the destination type,
2895       // we're done.
2896       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2897         return From;
2898     }
2899   }
2900 
2901   bool IgnoreAccess = false;
2902 
2903   // If we actually found the member through a using declaration, cast
2904   // down to the using declaration's type.
2905   //
2906   // Pointer equality is fine here because only one declaration of a
2907   // class ever has member declarations.
2908   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2909     assert(isa<UsingShadowDecl>(FoundDecl));
2910     QualType URecordType = Context.getTypeDeclType(
2911                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2912 
2913     // We only need to do this if the naming-class to declaring-class
2914     // conversion is non-trivial.
2915     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2916       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2917       CXXCastPath BasePath;
2918       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2919                                        FromLoc, FromRange, &BasePath))
2920         return ExprError();
2921 
2922       QualType UType = URecordType;
2923       if (PointerConversions)
2924         UType = Context.getPointerType(UType);
2925       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2926                                VK, &BasePath).get();
2927       FromType = UType;
2928       FromRecordType = URecordType;
2929     }
2930 
2931     // We don't do access control for the conversion from the
2932     // declaring class to the true declaring class.
2933     IgnoreAccess = true;
2934   }
2935 
2936   CXXCastPath BasePath;
2937   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2938                                    FromLoc, FromRange, &BasePath,
2939                                    IgnoreAccess))
2940     return ExprError();
2941 
2942   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2943                            VK, &BasePath);
2944 }
2945 
2946 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2947                                       const LookupResult &R,
2948                                       bool HasTrailingLParen) {
2949   // Only when used directly as the postfix-expression of a call.
2950   if (!HasTrailingLParen)
2951     return false;
2952 
2953   // Never if a scope specifier was provided.
2954   if (SS.isSet())
2955     return false;
2956 
2957   // Only in C++ or ObjC++.
2958   if (!getLangOpts().CPlusPlus)
2959     return false;
2960 
2961   // Turn off ADL when we find certain kinds of declarations during
2962   // normal lookup:
2963   for (NamedDecl *D : R) {
2964     // C++0x [basic.lookup.argdep]p3:
2965     //     -- a declaration of a class member
2966     // Since using decls preserve this property, we check this on the
2967     // original decl.
2968     if (D->isCXXClassMember())
2969       return false;
2970 
2971     // C++0x [basic.lookup.argdep]p3:
2972     //     -- a block-scope function declaration that is not a
2973     //        using-declaration
2974     // NOTE: we also trigger this for function templates (in fact, we
2975     // don't check the decl type at all, since all other decl types
2976     // turn off ADL anyway).
2977     if (isa<UsingShadowDecl>(D))
2978       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2979     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2980       return false;
2981 
2982     // C++0x [basic.lookup.argdep]p3:
2983     //     -- a declaration that is neither a function or a function
2984     //        template
2985     // And also for builtin functions.
2986     if (isa<FunctionDecl>(D)) {
2987       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2988 
2989       // But also builtin functions.
2990       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2991         return false;
2992     } else if (!isa<FunctionTemplateDecl>(D))
2993       return false;
2994   }
2995 
2996   return true;
2997 }
2998 
2999 
3000 /// Diagnoses obvious problems with the use of the given declaration
3001 /// as an expression.  This is only actually called for lookups that
3002 /// were not overloaded, and it doesn't promise that the declaration
3003 /// will in fact be used.
3004 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3005   if (D->isInvalidDecl())
3006     return true;
3007 
3008   if (isa<TypedefNameDecl>(D)) {
3009     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3010     return true;
3011   }
3012 
3013   if (isa<ObjCInterfaceDecl>(D)) {
3014     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3015     return true;
3016   }
3017 
3018   if (isa<NamespaceDecl>(D)) {
3019     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3020     return true;
3021   }
3022 
3023   return false;
3024 }
3025 
3026 // Certain multiversion types should be treated as overloaded even when there is
3027 // only one result.
3028 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3029   assert(R.isSingleResult() && "Expected only a single result");
3030   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3031   return FD &&
3032          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3033 }
3034 
3035 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3036                                           LookupResult &R, bool NeedsADL,
3037                                           bool AcceptInvalidDecl) {
3038   // If this is a single, fully-resolved result and we don't need ADL,
3039   // just build an ordinary singleton decl ref.
3040   if (!NeedsADL && R.isSingleResult() &&
3041       !R.getAsSingle<FunctionTemplateDecl>() &&
3042       !ShouldLookupResultBeMultiVersionOverload(R))
3043     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3044                                     R.getRepresentativeDecl(), nullptr,
3045                                     AcceptInvalidDecl);
3046 
3047   // We only need to check the declaration if there's exactly one
3048   // result, because in the overloaded case the results can only be
3049   // functions and function templates.
3050   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3051       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3052     return ExprError();
3053 
3054   // Otherwise, just build an unresolved lookup expression.  Suppress
3055   // any lookup-related diagnostics; we'll hash these out later, when
3056   // we've picked a target.
3057   R.suppressDiagnostics();
3058 
3059   UnresolvedLookupExpr *ULE
3060     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3061                                    SS.getWithLocInContext(Context),
3062                                    R.getLookupNameInfo(),
3063                                    NeedsADL, R.isOverloadedResult(),
3064                                    R.begin(), R.end());
3065 
3066   return ULE;
3067 }
3068 
3069 static void
3070 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3071                                    ValueDecl *var, DeclContext *DC);
3072 
3073 /// Complete semantic analysis for a reference to the given declaration.
3074 ExprResult Sema::BuildDeclarationNameExpr(
3075     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3076     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3077     bool AcceptInvalidDecl) {
3078   assert(D && "Cannot refer to a NULL declaration");
3079   assert(!isa<FunctionTemplateDecl>(D) &&
3080          "Cannot refer unambiguously to a function template");
3081 
3082   SourceLocation Loc = NameInfo.getLoc();
3083   if (CheckDeclInExpr(*this, Loc, D))
3084     return ExprError();
3085 
3086   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3087     // Specifically diagnose references to class templates that are missing
3088     // a template argument list.
3089     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3090     return ExprError();
3091   }
3092 
3093   // Make sure that we're referring to a value.
3094   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3095   if (!VD) {
3096     Diag(Loc, diag::err_ref_non_value)
3097       << D << SS.getRange();
3098     Diag(D->getLocation(), diag::note_declared_at);
3099     return ExprError();
3100   }
3101 
3102   // Check whether this declaration can be used. Note that we suppress
3103   // this check when we're going to perform argument-dependent lookup
3104   // on this function name, because this might not be the function
3105   // that overload resolution actually selects.
3106   if (DiagnoseUseOfDecl(VD, Loc))
3107     return ExprError();
3108 
3109   // Only create DeclRefExpr's for valid Decl's.
3110   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3111     return ExprError();
3112 
3113   // Handle members of anonymous structs and unions.  If we got here,
3114   // and the reference is to a class member indirect field, then this
3115   // must be the subject of a pointer-to-member expression.
3116   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3117     if (!indirectField->isCXXClassMember())
3118       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3119                                                       indirectField);
3120 
3121   {
3122     QualType type = VD->getType();
3123     if (type.isNull())
3124       return ExprError();
3125     ExprValueKind valueKind = VK_RValue;
3126 
3127     switch (D->getKind()) {
3128     // Ignore all the non-ValueDecl kinds.
3129 #define ABSTRACT_DECL(kind)
3130 #define VALUE(type, base)
3131 #define DECL(type, base) \
3132     case Decl::type:
3133 #include "clang/AST/DeclNodes.inc"
3134       llvm_unreachable("invalid value decl kind");
3135 
3136     // These shouldn't make it here.
3137     case Decl::ObjCAtDefsField:
3138       llvm_unreachable("forming non-member reference to ivar?");
3139 
3140     // Enum constants are always r-values and never references.
3141     // Unresolved using declarations are dependent.
3142     case Decl::EnumConstant:
3143     case Decl::UnresolvedUsingValue:
3144     case Decl::OMPDeclareReduction:
3145     case Decl::OMPDeclareMapper:
3146       valueKind = VK_RValue;
3147       break;
3148 
3149     // Fields and indirect fields that got here must be for
3150     // pointer-to-member expressions; we just call them l-values for
3151     // internal consistency, because this subexpression doesn't really
3152     // exist in the high-level semantics.
3153     case Decl::Field:
3154     case Decl::IndirectField:
3155     case Decl::ObjCIvar:
3156       assert(getLangOpts().CPlusPlus &&
3157              "building reference to field in C?");
3158 
3159       // These can't have reference type in well-formed programs, but
3160       // for internal consistency we do this anyway.
3161       type = type.getNonReferenceType();
3162       valueKind = VK_LValue;
3163       break;
3164 
3165     // Non-type template parameters are either l-values or r-values
3166     // depending on the type.
3167     case Decl::NonTypeTemplateParm: {
3168       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3169         type = reftype->getPointeeType();
3170         valueKind = VK_LValue; // even if the parameter is an r-value reference
3171         break;
3172       }
3173 
3174       // For non-references, we need to strip qualifiers just in case
3175       // the template parameter was declared as 'const int' or whatever.
3176       valueKind = VK_RValue;
3177       type = type.getUnqualifiedType();
3178       break;
3179     }
3180 
3181     case Decl::Var:
3182     case Decl::VarTemplateSpecialization:
3183     case Decl::VarTemplatePartialSpecialization:
3184     case Decl::Decomposition:
3185     case Decl::OMPCapturedExpr:
3186       // In C, "extern void blah;" is valid and is an r-value.
3187       if (!getLangOpts().CPlusPlus &&
3188           !type.hasQualifiers() &&
3189           type->isVoidType()) {
3190         valueKind = VK_RValue;
3191         break;
3192       }
3193       LLVM_FALLTHROUGH;
3194 
3195     case Decl::ImplicitParam:
3196     case Decl::ParmVar: {
3197       // These are always l-values.
3198       valueKind = VK_LValue;
3199       type = type.getNonReferenceType();
3200 
3201       // FIXME: Does the addition of const really only apply in
3202       // potentially-evaluated contexts? Since the variable isn't actually
3203       // captured in an unevaluated context, it seems that the answer is no.
3204       if (!isUnevaluatedContext()) {
3205         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3206         if (!CapturedType.isNull())
3207           type = CapturedType;
3208       }
3209 
3210       break;
3211     }
3212 
3213     case Decl::Binding: {
3214       // These are always lvalues.
3215       valueKind = VK_LValue;
3216       type = type.getNonReferenceType();
3217       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3218       // decides how that's supposed to work.
3219       auto *BD = cast<BindingDecl>(VD);
3220       if (BD->getDeclContext() != CurContext) {
3221         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3222         if (DD && DD->hasLocalStorage())
3223           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3224       }
3225       break;
3226     }
3227 
3228     case Decl::Function: {
3229       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3230         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3231           type = Context.BuiltinFnTy;
3232           valueKind = VK_RValue;
3233           break;
3234         }
3235       }
3236 
3237       const FunctionType *fty = type->castAs<FunctionType>();
3238 
3239       // If we're referring to a function with an __unknown_anytype
3240       // result type, make the entire expression __unknown_anytype.
3241       if (fty->getReturnType() == Context.UnknownAnyTy) {
3242         type = Context.UnknownAnyTy;
3243         valueKind = VK_RValue;
3244         break;
3245       }
3246 
3247       // Functions are l-values in C++.
3248       if (getLangOpts().CPlusPlus) {
3249         valueKind = VK_LValue;
3250         break;
3251       }
3252 
3253       // C99 DR 316 says that, if a function type comes from a
3254       // function definition (without a prototype), that type is only
3255       // used for checking compatibility. Therefore, when referencing
3256       // the function, we pretend that we don't have the full function
3257       // type.
3258       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3259           isa<FunctionProtoType>(fty))
3260         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3261                                               fty->getExtInfo());
3262 
3263       // Functions are r-values in C.
3264       valueKind = VK_RValue;
3265       break;
3266     }
3267 
3268     case Decl::CXXDeductionGuide:
3269       llvm_unreachable("building reference to deduction guide");
3270 
3271     case Decl::MSProperty:
3272       valueKind = VK_LValue;
3273       break;
3274 
3275     case Decl::CXXMethod:
3276       // If we're referring to a method with an __unknown_anytype
3277       // result type, make the entire expression __unknown_anytype.
3278       // This should only be possible with a type written directly.
3279       if (const FunctionProtoType *proto
3280             = dyn_cast<FunctionProtoType>(VD->getType()))
3281         if (proto->getReturnType() == Context.UnknownAnyTy) {
3282           type = Context.UnknownAnyTy;
3283           valueKind = VK_RValue;
3284           break;
3285         }
3286 
3287       // C++ methods are l-values if static, r-values if non-static.
3288       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3289         valueKind = VK_LValue;
3290         break;
3291       }
3292       LLVM_FALLTHROUGH;
3293 
3294     case Decl::CXXConversion:
3295     case Decl::CXXDestructor:
3296     case Decl::CXXConstructor:
3297       valueKind = VK_RValue;
3298       break;
3299     }
3300 
3301     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3302                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3303                             TemplateArgs);
3304   }
3305 }
3306 
3307 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3308                                     SmallString<32> &Target) {
3309   Target.resize(CharByteWidth * (Source.size() + 1));
3310   char *ResultPtr = &Target[0];
3311   const llvm::UTF8 *ErrorPtr;
3312   bool success =
3313       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3314   (void)success;
3315   assert(success);
3316   Target.resize(ResultPtr - &Target[0]);
3317 }
3318 
3319 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3320                                      PredefinedExpr::IdentKind IK) {
3321   // Pick the current block, lambda, captured statement or function.
3322   Decl *currentDecl = nullptr;
3323   if (const BlockScopeInfo *BSI = getCurBlock())
3324     currentDecl = BSI->TheDecl;
3325   else if (const LambdaScopeInfo *LSI = getCurLambda())
3326     currentDecl = LSI->CallOperator;
3327   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3328     currentDecl = CSI->TheCapturedDecl;
3329   else
3330     currentDecl = getCurFunctionOrMethodDecl();
3331 
3332   if (!currentDecl) {
3333     Diag(Loc, diag::ext_predef_outside_function);
3334     currentDecl = Context.getTranslationUnitDecl();
3335   }
3336 
3337   QualType ResTy;
3338   StringLiteral *SL = nullptr;
3339   if (cast<DeclContext>(currentDecl)->isDependentContext())
3340     ResTy = Context.DependentTy;
3341   else {
3342     // Pre-defined identifiers are of type char[x], where x is the length of
3343     // the string.
3344     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3345     unsigned Length = Str.length();
3346 
3347     llvm::APInt LengthI(32, Length + 1);
3348     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3349       ResTy =
3350           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3351       SmallString<32> RawChars;
3352       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3353                               Str, RawChars);
3354       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3355                                            ArrayType::Normal,
3356                                            /*IndexTypeQuals*/ 0);
3357       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3358                                  /*Pascal*/ false, ResTy, Loc);
3359     } else {
3360       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3361       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3362                                            ArrayType::Normal,
3363                                            /*IndexTypeQuals*/ 0);
3364       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3365                                  /*Pascal*/ false, ResTy, Loc);
3366     }
3367   }
3368 
3369   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3370 }
3371 
3372 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3373   PredefinedExpr::IdentKind IK;
3374 
3375   switch (Kind) {
3376   default: llvm_unreachable("Unknown simple primary expr!");
3377   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3378   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3379   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3380   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3381   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3382   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3383   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3384   }
3385 
3386   return BuildPredefinedExpr(Loc, IK);
3387 }
3388 
3389 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3390   SmallString<16> CharBuffer;
3391   bool Invalid = false;
3392   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3393   if (Invalid)
3394     return ExprError();
3395 
3396   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3397                             PP, Tok.getKind());
3398   if (Literal.hadError())
3399     return ExprError();
3400 
3401   QualType Ty;
3402   if (Literal.isWide())
3403     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3404   else if (Literal.isUTF8() && getLangOpts().Char8)
3405     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3406   else if (Literal.isUTF16())
3407     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3408   else if (Literal.isUTF32())
3409     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3410   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3411     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3412   else
3413     Ty = Context.CharTy;  // 'x' -> char in C++
3414 
3415   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3416   if (Literal.isWide())
3417     Kind = CharacterLiteral::Wide;
3418   else if (Literal.isUTF16())
3419     Kind = CharacterLiteral::UTF16;
3420   else if (Literal.isUTF32())
3421     Kind = CharacterLiteral::UTF32;
3422   else if (Literal.isUTF8())
3423     Kind = CharacterLiteral::UTF8;
3424 
3425   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3426                                              Tok.getLocation());
3427 
3428   if (Literal.getUDSuffix().empty())
3429     return Lit;
3430 
3431   // We're building a user-defined literal.
3432   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3433   SourceLocation UDSuffixLoc =
3434     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3435 
3436   // Make sure we're allowed user-defined literals here.
3437   if (!UDLScope)
3438     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3439 
3440   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3441   //   operator "" X (ch)
3442   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3443                                         Lit, Tok.getLocation());
3444 }
3445 
3446 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3447   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3448   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3449                                 Context.IntTy, Loc);
3450 }
3451 
3452 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3453                                   QualType Ty, SourceLocation Loc) {
3454   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3455 
3456   using llvm::APFloat;
3457   APFloat Val(Format);
3458 
3459   APFloat::opStatus result = Literal.GetFloatValue(Val);
3460 
3461   // Overflow is always an error, but underflow is only an error if
3462   // we underflowed to zero (APFloat reports denormals as underflow).
3463   if ((result & APFloat::opOverflow) ||
3464       ((result & APFloat::opUnderflow) && Val.isZero())) {
3465     unsigned diagnostic;
3466     SmallString<20> buffer;
3467     if (result & APFloat::opOverflow) {
3468       diagnostic = diag::warn_float_overflow;
3469       APFloat::getLargest(Format).toString(buffer);
3470     } else {
3471       diagnostic = diag::warn_float_underflow;
3472       APFloat::getSmallest(Format).toString(buffer);
3473     }
3474 
3475     S.Diag(Loc, diagnostic)
3476       << Ty
3477       << StringRef(buffer.data(), buffer.size());
3478   }
3479 
3480   bool isExact = (result == APFloat::opOK);
3481   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3482 }
3483 
3484 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3485   assert(E && "Invalid expression");
3486 
3487   if (E->isValueDependent())
3488     return false;
3489 
3490   QualType QT = E->getType();
3491   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3492     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3493     return true;
3494   }
3495 
3496   llvm::APSInt ValueAPS;
3497   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3498 
3499   if (R.isInvalid())
3500     return true;
3501 
3502   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3503   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3504     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3505         << ValueAPS.toString(10) << ValueIsPositive;
3506     return true;
3507   }
3508 
3509   return false;
3510 }
3511 
3512 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3513   // Fast path for a single digit (which is quite common).  A single digit
3514   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3515   if (Tok.getLength() == 1) {
3516     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3517     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3518   }
3519 
3520   SmallString<128> SpellingBuffer;
3521   // NumericLiteralParser wants to overread by one character.  Add padding to
3522   // the buffer in case the token is copied to the buffer.  If getSpelling()
3523   // returns a StringRef to the memory buffer, it should have a null char at
3524   // the EOF, so it is also safe.
3525   SpellingBuffer.resize(Tok.getLength() + 1);
3526 
3527   // Get the spelling of the token, which eliminates trigraphs, etc.
3528   bool Invalid = false;
3529   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3530   if (Invalid)
3531     return ExprError();
3532 
3533   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3534   if (Literal.hadError)
3535     return ExprError();
3536 
3537   if (Literal.hasUDSuffix()) {
3538     // We're building a user-defined literal.
3539     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3540     SourceLocation UDSuffixLoc =
3541       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3542 
3543     // Make sure we're allowed user-defined literals here.
3544     if (!UDLScope)
3545       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3546 
3547     QualType CookedTy;
3548     if (Literal.isFloatingLiteral()) {
3549       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3550       // long double, the literal is treated as a call of the form
3551       //   operator "" X (f L)
3552       CookedTy = Context.LongDoubleTy;
3553     } else {
3554       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3555       // unsigned long long, the literal is treated as a call of the form
3556       //   operator "" X (n ULL)
3557       CookedTy = Context.UnsignedLongLongTy;
3558     }
3559 
3560     DeclarationName OpName =
3561       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3562     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3563     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3564 
3565     SourceLocation TokLoc = Tok.getLocation();
3566 
3567     // Perform literal operator lookup to determine if we're building a raw
3568     // literal or a cooked one.
3569     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3570     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3571                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3572                                   /*AllowStringTemplate*/ false,
3573                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3574     case LOLR_ErrorNoDiagnostic:
3575       // Lookup failure for imaginary constants isn't fatal, there's still the
3576       // GNU extension producing _Complex types.
3577       break;
3578     case LOLR_Error:
3579       return ExprError();
3580     case LOLR_Cooked: {
3581       Expr *Lit;
3582       if (Literal.isFloatingLiteral()) {
3583         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3584       } else {
3585         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3586         if (Literal.GetIntegerValue(ResultVal))
3587           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3588               << /* Unsigned */ 1;
3589         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3590                                      Tok.getLocation());
3591       }
3592       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3593     }
3594 
3595     case LOLR_Raw: {
3596       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3597       // literal is treated as a call of the form
3598       //   operator "" X ("n")
3599       unsigned Length = Literal.getUDSuffixOffset();
3600       QualType StrTy = Context.getConstantArrayType(
3601           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3602           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3603       Expr *Lit = StringLiteral::Create(
3604           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3605           /*Pascal*/false, StrTy, &TokLoc, 1);
3606       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3607     }
3608 
3609     case LOLR_Template: {
3610       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3611       // template), L is treated as a call fo the form
3612       //   operator "" X <'c1', 'c2', ... 'ck'>()
3613       // where n is the source character sequence c1 c2 ... ck.
3614       TemplateArgumentListInfo ExplicitArgs;
3615       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3616       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3617       llvm::APSInt Value(CharBits, CharIsUnsigned);
3618       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3619         Value = TokSpelling[I];
3620         TemplateArgument Arg(Context, Value, Context.CharTy);
3621         TemplateArgumentLocInfo ArgInfo;
3622         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3623       }
3624       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3625                                       &ExplicitArgs);
3626     }
3627     case LOLR_StringTemplate:
3628       llvm_unreachable("unexpected literal operator lookup result");
3629     }
3630   }
3631 
3632   Expr *Res;
3633 
3634   if (Literal.isFixedPointLiteral()) {
3635     QualType Ty;
3636 
3637     if (Literal.isAccum) {
3638       if (Literal.isHalf) {
3639         Ty = Context.ShortAccumTy;
3640       } else if (Literal.isLong) {
3641         Ty = Context.LongAccumTy;
3642       } else {
3643         Ty = Context.AccumTy;
3644       }
3645     } else if (Literal.isFract) {
3646       if (Literal.isHalf) {
3647         Ty = Context.ShortFractTy;
3648       } else if (Literal.isLong) {
3649         Ty = Context.LongFractTy;
3650       } else {
3651         Ty = Context.FractTy;
3652       }
3653     }
3654 
3655     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3656 
3657     bool isSigned = !Literal.isUnsigned;
3658     unsigned scale = Context.getFixedPointScale(Ty);
3659     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3660 
3661     llvm::APInt Val(bit_width, 0, isSigned);
3662     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3663     bool ValIsZero = Val.isNullValue() && !Overflowed;
3664 
3665     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3666     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3667       // Clause 6.4.4 - The value of a constant shall be in the range of
3668       // representable values for its type, with exception for constants of a
3669       // fract type with a value of exactly 1; such a constant shall denote
3670       // the maximal value for the type.
3671       --Val;
3672     else if (Val.ugt(MaxVal) || Overflowed)
3673       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3674 
3675     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3676                                               Tok.getLocation(), scale);
3677   } else if (Literal.isFloatingLiteral()) {
3678     QualType Ty;
3679     if (Literal.isHalf){
3680       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3681         Ty = Context.HalfTy;
3682       else {
3683         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3684         return ExprError();
3685       }
3686     } else if (Literal.isFloat)
3687       Ty = Context.FloatTy;
3688     else if (Literal.isLong)
3689       Ty = Context.LongDoubleTy;
3690     else if (Literal.isFloat16)
3691       Ty = Context.Float16Ty;
3692     else if (Literal.isFloat128)
3693       Ty = Context.Float128Ty;
3694     else
3695       Ty = Context.DoubleTy;
3696 
3697     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3698 
3699     if (Ty == Context.DoubleTy) {
3700       if (getLangOpts().SinglePrecisionConstants) {
3701         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3702         if (BTy->getKind() != BuiltinType::Float) {
3703           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3704         }
3705       } else if (getLangOpts().OpenCL &&
3706                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3707         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3708         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3709         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3710       }
3711     }
3712   } else if (!Literal.isIntegerLiteral()) {
3713     return ExprError();
3714   } else {
3715     QualType Ty;
3716 
3717     // 'long long' is a C99 or C++11 feature.
3718     if (!getLangOpts().C99 && Literal.isLongLong) {
3719       if (getLangOpts().CPlusPlus)
3720         Diag(Tok.getLocation(),
3721              getLangOpts().CPlusPlus11 ?
3722              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3723       else
3724         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3725     }
3726 
3727     // Get the value in the widest-possible width.
3728     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3729     llvm::APInt ResultVal(MaxWidth, 0);
3730 
3731     if (Literal.GetIntegerValue(ResultVal)) {
3732       // If this value didn't fit into uintmax_t, error and force to ull.
3733       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3734           << /* Unsigned */ 1;
3735       Ty = Context.UnsignedLongLongTy;
3736       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3737              "long long is not intmax_t?");
3738     } else {
3739       // If this value fits into a ULL, try to figure out what else it fits into
3740       // according to the rules of C99 6.4.4.1p5.
3741 
3742       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3743       // be an unsigned int.
3744       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3745 
3746       // Check from smallest to largest, picking the smallest type we can.
3747       unsigned Width = 0;
3748 
3749       // Microsoft specific integer suffixes are explicitly sized.
3750       if (Literal.MicrosoftInteger) {
3751         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3752           Width = 8;
3753           Ty = Context.CharTy;
3754         } else {
3755           Width = Literal.MicrosoftInteger;
3756           Ty = Context.getIntTypeForBitwidth(Width,
3757                                              /*Signed=*/!Literal.isUnsigned);
3758         }
3759       }
3760 
3761       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3762         // Are int/unsigned possibilities?
3763         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3764 
3765         // Does it fit in a unsigned int?
3766         if (ResultVal.isIntN(IntSize)) {
3767           // Does it fit in a signed int?
3768           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3769             Ty = Context.IntTy;
3770           else if (AllowUnsigned)
3771             Ty = Context.UnsignedIntTy;
3772           Width = IntSize;
3773         }
3774       }
3775 
3776       // Are long/unsigned long possibilities?
3777       if (Ty.isNull() && !Literal.isLongLong) {
3778         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3779 
3780         // Does it fit in a unsigned long?
3781         if (ResultVal.isIntN(LongSize)) {
3782           // Does it fit in a signed long?
3783           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3784             Ty = Context.LongTy;
3785           else if (AllowUnsigned)
3786             Ty = Context.UnsignedLongTy;
3787           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3788           // is compatible.
3789           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3790             const unsigned LongLongSize =
3791                 Context.getTargetInfo().getLongLongWidth();
3792             Diag(Tok.getLocation(),
3793                  getLangOpts().CPlusPlus
3794                      ? Literal.isLong
3795                            ? diag::warn_old_implicitly_unsigned_long_cxx
3796                            : /*C++98 UB*/ diag::
3797                                  ext_old_implicitly_unsigned_long_cxx
3798                      : diag::warn_old_implicitly_unsigned_long)
3799                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3800                                             : /*will be ill-formed*/ 1);
3801             Ty = Context.UnsignedLongTy;
3802           }
3803           Width = LongSize;
3804         }
3805       }
3806 
3807       // Check long long if needed.
3808       if (Ty.isNull()) {
3809         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3810 
3811         // Does it fit in a unsigned long long?
3812         if (ResultVal.isIntN(LongLongSize)) {
3813           // Does it fit in a signed long long?
3814           // To be compatible with MSVC, hex integer literals ending with the
3815           // LL or i64 suffix are always signed in Microsoft mode.
3816           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3817               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3818             Ty = Context.LongLongTy;
3819           else if (AllowUnsigned)
3820             Ty = Context.UnsignedLongLongTy;
3821           Width = LongLongSize;
3822         }
3823       }
3824 
3825       // If we still couldn't decide a type, we probably have something that
3826       // does not fit in a signed long long, but has no U suffix.
3827       if (Ty.isNull()) {
3828         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3829         Ty = Context.UnsignedLongLongTy;
3830         Width = Context.getTargetInfo().getLongLongWidth();
3831       }
3832 
3833       if (ResultVal.getBitWidth() != Width)
3834         ResultVal = ResultVal.trunc(Width);
3835     }
3836     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3837   }
3838 
3839   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3840   if (Literal.isImaginary) {
3841     Res = new (Context) ImaginaryLiteral(Res,
3842                                         Context.getComplexType(Res->getType()));
3843 
3844     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3845   }
3846   return Res;
3847 }
3848 
3849 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3850   assert(E && "ActOnParenExpr() missing expr");
3851   return new (Context) ParenExpr(L, R, E);
3852 }
3853 
3854 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3855                                          SourceLocation Loc,
3856                                          SourceRange ArgRange) {
3857   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3858   // scalar or vector data type argument..."
3859   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3860   // type (C99 6.2.5p18) or void.
3861   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3862     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3863       << T << ArgRange;
3864     return true;
3865   }
3866 
3867   assert((T->isVoidType() || !T->isIncompleteType()) &&
3868          "Scalar types should always be complete");
3869   return false;
3870 }
3871 
3872 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3873                                            SourceLocation Loc,
3874                                            SourceRange ArgRange,
3875                                            UnaryExprOrTypeTrait TraitKind) {
3876   // Invalid types must be hard errors for SFINAE in C++.
3877   if (S.LangOpts.CPlusPlus)
3878     return true;
3879 
3880   // C99 6.5.3.4p1:
3881   if (T->isFunctionType() &&
3882       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3883        TraitKind == UETT_PreferredAlignOf)) {
3884     // sizeof(function)/alignof(function) is allowed as an extension.
3885     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3886       << TraitKind << ArgRange;
3887     return false;
3888   }
3889 
3890   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3891   // this is an error (OpenCL v1.1 s6.3.k)
3892   if (T->isVoidType()) {
3893     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3894                                         : diag::ext_sizeof_alignof_void_type;
3895     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3896     return false;
3897   }
3898 
3899   return true;
3900 }
3901 
3902 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3903                                              SourceLocation Loc,
3904                                              SourceRange ArgRange,
3905                                              UnaryExprOrTypeTrait TraitKind) {
3906   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3907   // runtime doesn't allow it.
3908   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3909     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3910       << T << (TraitKind == UETT_SizeOf)
3911       << ArgRange;
3912     return true;
3913   }
3914 
3915   return false;
3916 }
3917 
3918 /// Check whether E is a pointer from a decayed array type (the decayed
3919 /// pointer type is equal to T) and emit a warning if it is.
3920 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3921                                      Expr *E) {
3922   // Don't warn if the operation changed the type.
3923   if (T != E->getType())
3924     return;
3925 
3926   // Now look for array decays.
3927   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3928   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3929     return;
3930 
3931   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3932                                              << ICE->getType()
3933                                              << ICE->getSubExpr()->getType();
3934 }
3935 
3936 /// Check the constraints on expression operands to unary type expression
3937 /// and type traits.
3938 ///
3939 /// Completes any types necessary and validates the constraints on the operand
3940 /// expression. The logic mostly mirrors the type-based overload, but may modify
3941 /// the expression as it completes the type for that expression through template
3942 /// instantiation, etc.
3943 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3944                                             UnaryExprOrTypeTrait ExprKind) {
3945   QualType ExprTy = E->getType();
3946   assert(!ExprTy->isReferenceType());
3947 
3948   bool IsUnevaluatedOperand =
3949       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3950        ExprKind == UETT_PreferredAlignOf);
3951   if (IsUnevaluatedOperand) {
3952     ExprResult Result = CheckUnevaluatedOperand(E);
3953     if (Result.isInvalid())
3954       return true;
3955     E = Result.get();
3956   }
3957 
3958   if (ExprKind == UETT_VecStep)
3959     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3960                                         E->getSourceRange());
3961 
3962   // Whitelist some types as extensions
3963   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3964                                       E->getSourceRange(), ExprKind))
3965     return false;
3966 
3967   // 'alignof' applied to an expression only requires the base element type of
3968   // the expression to be complete. 'sizeof' requires the expression's type to
3969   // be complete (and will attempt to complete it if it's an array of unknown
3970   // bound).
3971   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3972     if (RequireCompleteType(E->getExprLoc(),
3973                             Context.getBaseElementType(E->getType()),
3974                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3975                             E->getSourceRange()))
3976       return true;
3977   } else {
3978     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3979                                 ExprKind, E->getSourceRange()))
3980       return true;
3981   }
3982 
3983   // Completing the expression's type may have changed it.
3984   ExprTy = E->getType();
3985   assert(!ExprTy->isReferenceType());
3986 
3987   if (ExprTy->isFunctionType()) {
3988     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3989       << ExprKind << E->getSourceRange();
3990     return true;
3991   }
3992 
3993   // The operand for sizeof and alignof is in an unevaluated expression context,
3994   // so side effects could result in unintended consequences.
3995   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3996       E->HasSideEffects(Context, false))
3997     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3998 
3999   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4000                                        E->getSourceRange(), ExprKind))
4001     return true;
4002 
4003   if (ExprKind == UETT_SizeOf) {
4004     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4005       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4006         QualType OType = PVD->getOriginalType();
4007         QualType Type = PVD->getType();
4008         if (Type->isPointerType() && OType->isArrayType()) {
4009           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4010             << Type << OType;
4011           Diag(PVD->getLocation(), diag::note_declared_at);
4012         }
4013       }
4014     }
4015 
4016     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4017     // decays into a pointer and returns an unintended result. This is most
4018     // likely a typo for "sizeof(array) op x".
4019     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4020       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4021                                BO->getLHS());
4022       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4023                                BO->getRHS());
4024     }
4025   }
4026 
4027   return false;
4028 }
4029 
4030 /// Check the constraints on operands to unary expression and type
4031 /// traits.
4032 ///
4033 /// This will complete any types necessary, and validate the various constraints
4034 /// on those operands.
4035 ///
4036 /// The UsualUnaryConversions() function is *not* called by this routine.
4037 /// C99 6.3.2.1p[2-4] all state:
4038 ///   Except when it is the operand of the sizeof operator ...
4039 ///
4040 /// C++ [expr.sizeof]p4
4041 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4042 ///   standard conversions are not applied to the operand of sizeof.
4043 ///
4044 /// This policy is followed for all of the unary trait expressions.
4045 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4046                                             SourceLocation OpLoc,
4047                                             SourceRange ExprRange,
4048                                             UnaryExprOrTypeTrait ExprKind) {
4049   if (ExprType->isDependentType())
4050     return false;
4051 
4052   // C++ [expr.sizeof]p2:
4053   //     When applied to a reference or a reference type, the result
4054   //     is the size of the referenced type.
4055   // C++11 [expr.alignof]p3:
4056   //     When alignof is applied to a reference type, the result
4057   //     shall be the alignment of the referenced type.
4058   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4059     ExprType = Ref->getPointeeType();
4060 
4061   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4062   //   When alignof or _Alignof is applied to an array type, the result
4063   //   is the alignment of the element type.
4064   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4065       ExprKind == UETT_OpenMPRequiredSimdAlign)
4066     ExprType = Context.getBaseElementType(ExprType);
4067 
4068   if (ExprKind == UETT_VecStep)
4069     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4070 
4071   // Whitelist some types as extensions
4072   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4073                                       ExprKind))
4074     return false;
4075 
4076   if (RequireCompleteType(OpLoc, ExprType,
4077                           diag::err_sizeof_alignof_incomplete_type,
4078                           ExprKind, ExprRange))
4079     return true;
4080 
4081   if (ExprType->isFunctionType()) {
4082     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4083       << ExprKind << ExprRange;
4084     return true;
4085   }
4086 
4087   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4088                                        ExprKind))
4089     return true;
4090 
4091   return false;
4092 }
4093 
4094 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4095   // Cannot know anything else if the expression is dependent.
4096   if (E->isTypeDependent())
4097     return false;
4098 
4099   if (E->getObjectKind() == OK_BitField) {
4100     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4101        << 1 << E->getSourceRange();
4102     return true;
4103   }
4104 
4105   ValueDecl *D = nullptr;
4106   Expr *Inner = E->IgnoreParens();
4107   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4108     D = DRE->getDecl();
4109   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4110     D = ME->getMemberDecl();
4111   }
4112 
4113   // If it's a field, require the containing struct to have a
4114   // complete definition so that we can compute the layout.
4115   //
4116   // This can happen in C++11 onwards, either by naming the member
4117   // in a way that is not transformed into a member access expression
4118   // (in an unevaluated operand, for instance), or by naming the member
4119   // in a trailing-return-type.
4120   //
4121   // For the record, since __alignof__ on expressions is a GCC
4122   // extension, GCC seems to permit this but always gives the
4123   // nonsensical answer 0.
4124   //
4125   // We don't really need the layout here --- we could instead just
4126   // directly check for all the appropriate alignment-lowing
4127   // attributes --- but that would require duplicating a lot of
4128   // logic that just isn't worth duplicating for such a marginal
4129   // use-case.
4130   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4131     // Fast path this check, since we at least know the record has a
4132     // definition if we can find a member of it.
4133     if (!FD->getParent()->isCompleteDefinition()) {
4134       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4135         << E->getSourceRange();
4136       return true;
4137     }
4138 
4139     // Otherwise, if it's a field, and the field doesn't have
4140     // reference type, then it must have a complete type (or be a
4141     // flexible array member, which we explicitly want to
4142     // white-list anyway), which makes the following checks trivial.
4143     if (!FD->getType()->isReferenceType())
4144       return false;
4145   }
4146 
4147   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4148 }
4149 
4150 bool Sema::CheckVecStepExpr(Expr *E) {
4151   E = E->IgnoreParens();
4152 
4153   // Cannot know anything else if the expression is dependent.
4154   if (E->isTypeDependent())
4155     return false;
4156 
4157   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4158 }
4159 
4160 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4161                                         CapturingScopeInfo *CSI) {
4162   assert(T->isVariablyModifiedType());
4163   assert(CSI != nullptr);
4164 
4165   // We're going to walk down into the type and look for VLA expressions.
4166   do {
4167     const Type *Ty = T.getTypePtr();
4168     switch (Ty->getTypeClass()) {
4169 #define TYPE(Class, Base)
4170 #define ABSTRACT_TYPE(Class, Base)
4171 #define NON_CANONICAL_TYPE(Class, Base)
4172 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4173 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4174 #include "clang/AST/TypeNodes.inc"
4175       T = QualType();
4176       break;
4177     // These types are never variably-modified.
4178     case Type::Builtin:
4179     case Type::Complex:
4180     case Type::Vector:
4181     case Type::ExtVector:
4182     case Type::Record:
4183     case Type::Enum:
4184     case Type::Elaborated:
4185     case Type::TemplateSpecialization:
4186     case Type::ObjCObject:
4187     case Type::ObjCInterface:
4188     case Type::ObjCObjectPointer:
4189     case Type::ObjCTypeParam:
4190     case Type::Pipe:
4191       llvm_unreachable("type class is never variably-modified!");
4192     case Type::Adjusted:
4193       T = cast<AdjustedType>(Ty)->getOriginalType();
4194       break;
4195     case Type::Decayed:
4196       T = cast<DecayedType>(Ty)->getPointeeType();
4197       break;
4198     case Type::Pointer:
4199       T = cast<PointerType>(Ty)->getPointeeType();
4200       break;
4201     case Type::BlockPointer:
4202       T = cast<BlockPointerType>(Ty)->getPointeeType();
4203       break;
4204     case Type::LValueReference:
4205     case Type::RValueReference:
4206       T = cast<ReferenceType>(Ty)->getPointeeType();
4207       break;
4208     case Type::MemberPointer:
4209       T = cast<MemberPointerType>(Ty)->getPointeeType();
4210       break;
4211     case Type::ConstantArray:
4212     case Type::IncompleteArray:
4213       // Losing element qualification here is fine.
4214       T = cast<ArrayType>(Ty)->getElementType();
4215       break;
4216     case Type::VariableArray: {
4217       // Losing element qualification here is fine.
4218       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4219 
4220       // Unknown size indication requires no size computation.
4221       // Otherwise, evaluate and record it.
4222       auto Size = VAT->getSizeExpr();
4223       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4224           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4225         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4226 
4227       T = VAT->getElementType();
4228       break;
4229     }
4230     case Type::FunctionProto:
4231     case Type::FunctionNoProto:
4232       T = cast<FunctionType>(Ty)->getReturnType();
4233       break;
4234     case Type::Paren:
4235     case Type::TypeOf:
4236     case Type::UnaryTransform:
4237     case Type::Attributed:
4238     case Type::SubstTemplateTypeParm:
4239     case Type::PackExpansion:
4240     case Type::MacroQualified:
4241       // Keep walking after single level desugaring.
4242       T = T.getSingleStepDesugaredType(Context);
4243       break;
4244     case Type::Typedef:
4245       T = cast<TypedefType>(Ty)->desugar();
4246       break;
4247     case Type::Decltype:
4248       T = cast<DecltypeType>(Ty)->desugar();
4249       break;
4250     case Type::Auto:
4251     case Type::DeducedTemplateSpecialization:
4252       T = cast<DeducedType>(Ty)->getDeducedType();
4253       break;
4254     case Type::TypeOfExpr:
4255       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4256       break;
4257     case Type::Atomic:
4258       T = cast<AtomicType>(Ty)->getValueType();
4259       break;
4260     }
4261   } while (!T.isNull() && T->isVariablyModifiedType());
4262 }
4263 
4264 /// Build a sizeof or alignof expression given a type operand.
4265 ExprResult
4266 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4267                                      SourceLocation OpLoc,
4268                                      UnaryExprOrTypeTrait ExprKind,
4269                                      SourceRange R) {
4270   if (!TInfo)
4271     return ExprError();
4272 
4273   QualType T = TInfo->getType();
4274 
4275   if (!T->isDependentType() &&
4276       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4277     return ExprError();
4278 
4279   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4280     if (auto *TT = T->getAs<TypedefType>()) {
4281       for (auto I = FunctionScopes.rbegin(),
4282                 E = std::prev(FunctionScopes.rend());
4283            I != E; ++I) {
4284         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4285         if (CSI == nullptr)
4286           break;
4287         DeclContext *DC = nullptr;
4288         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4289           DC = LSI->CallOperator;
4290         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4291           DC = CRSI->TheCapturedDecl;
4292         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4293           DC = BSI->TheDecl;
4294         if (DC) {
4295           if (DC->containsDecl(TT->getDecl()))
4296             break;
4297           captureVariablyModifiedType(Context, T, CSI);
4298         }
4299       }
4300     }
4301   }
4302 
4303   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4304   return new (Context) UnaryExprOrTypeTraitExpr(
4305       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4306 }
4307 
4308 /// Build a sizeof or alignof expression given an expression
4309 /// operand.
4310 ExprResult
4311 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4312                                      UnaryExprOrTypeTrait ExprKind) {
4313   ExprResult PE = CheckPlaceholderExpr(E);
4314   if (PE.isInvalid())
4315     return ExprError();
4316 
4317   E = PE.get();
4318 
4319   // Verify that the operand is valid.
4320   bool isInvalid = false;
4321   if (E->isTypeDependent()) {
4322     // Delay type-checking for type-dependent expressions.
4323   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4324     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4325   } else if (ExprKind == UETT_VecStep) {
4326     isInvalid = CheckVecStepExpr(E);
4327   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4328       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4329       isInvalid = true;
4330   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4331     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4332     isInvalid = true;
4333   } else {
4334     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4335   }
4336 
4337   if (isInvalid)
4338     return ExprError();
4339 
4340   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4341     PE = TransformToPotentiallyEvaluated(E);
4342     if (PE.isInvalid()) return ExprError();
4343     E = PE.get();
4344   }
4345 
4346   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4347   return new (Context) UnaryExprOrTypeTraitExpr(
4348       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4349 }
4350 
4351 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4352 /// expr and the same for @c alignof and @c __alignof
4353 /// Note that the ArgRange is invalid if isType is false.
4354 ExprResult
4355 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4356                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4357                                     void *TyOrEx, SourceRange ArgRange) {
4358   // If error parsing type, ignore.
4359   if (!TyOrEx) return ExprError();
4360 
4361   if (IsType) {
4362     TypeSourceInfo *TInfo;
4363     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4364     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4365   }
4366 
4367   Expr *ArgEx = (Expr *)TyOrEx;
4368   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4369   return Result;
4370 }
4371 
4372 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4373                                      bool IsReal) {
4374   if (V.get()->isTypeDependent())
4375     return S.Context.DependentTy;
4376 
4377   // _Real and _Imag are only l-values for normal l-values.
4378   if (V.get()->getObjectKind() != OK_Ordinary) {
4379     V = S.DefaultLvalueConversion(V.get());
4380     if (V.isInvalid())
4381       return QualType();
4382   }
4383 
4384   // These operators return the element type of a complex type.
4385   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4386     return CT->getElementType();
4387 
4388   // Otherwise they pass through real integer and floating point types here.
4389   if (V.get()->getType()->isArithmeticType())
4390     return V.get()->getType();
4391 
4392   // Test for placeholders.
4393   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4394   if (PR.isInvalid()) return QualType();
4395   if (PR.get() != V.get()) {
4396     V = PR;
4397     return CheckRealImagOperand(S, V, Loc, IsReal);
4398   }
4399 
4400   // Reject anything else.
4401   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4402     << (IsReal ? "__real" : "__imag");
4403   return QualType();
4404 }
4405 
4406 
4407 
4408 ExprResult
4409 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4410                           tok::TokenKind Kind, Expr *Input) {
4411   UnaryOperatorKind Opc;
4412   switch (Kind) {
4413   default: llvm_unreachable("Unknown unary op!");
4414   case tok::plusplus:   Opc = UO_PostInc; break;
4415   case tok::minusminus: Opc = UO_PostDec; break;
4416   }
4417 
4418   // Since this might is a postfix expression, get rid of ParenListExprs.
4419   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4420   if (Result.isInvalid()) return ExprError();
4421   Input = Result.get();
4422 
4423   return BuildUnaryOp(S, OpLoc, Opc, Input);
4424 }
4425 
4426 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4427 ///
4428 /// \return true on error
4429 static bool checkArithmeticOnObjCPointer(Sema &S,
4430                                          SourceLocation opLoc,
4431                                          Expr *op) {
4432   assert(op->getType()->isObjCObjectPointerType());
4433   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4434       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4435     return false;
4436 
4437   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4438     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4439     << op->getSourceRange();
4440   return true;
4441 }
4442 
4443 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4444   auto *BaseNoParens = Base->IgnoreParens();
4445   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4446     return MSProp->getPropertyDecl()->getType()->isArrayType();
4447   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4448 }
4449 
4450 ExprResult
4451 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4452                               Expr *idx, SourceLocation rbLoc) {
4453   if (base && !base->getType().isNull() &&
4454       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4455     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4456                                     /*Length=*/nullptr, rbLoc);
4457 
4458   // Since this might be a postfix expression, get rid of ParenListExprs.
4459   if (isa<ParenListExpr>(base)) {
4460     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4461     if (result.isInvalid()) return ExprError();
4462     base = result.get();
4463   }
4464 
4465   // A comma-expression as the index is deprecated in C++2a onwards.
4466   if (getLangOpts().CPlusPlus2a &&
4467       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4468        (isa<CXXOperatorCallExpr>(idx) &&
4469         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4470     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4471       << SourceRange(base->getBeginLoc(), rbLoc);
4472   }
4473 
4474   // Handle any non-overload placeholder types in the base and index
4475   // expressions.  We can't handle overloads here because the other
4476   // operand might be an overloadable type, in which case the overload
4477   // resolution for the operator overload should get the first crack
4478   // at the overload.
4479   bool IsMSPropertySubscript = false;
4480   if (base->getType()->isNonOverloadPlaceholderType()) {
4481     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4482     if (!IsMSPropertySubscript) {
4483       ExprResult result = CheckPlaceholderExpr(base);
4484       if (result.isInvalid())
4485         return ExprError();
4486       base = result.get();
4487     }
4488   }
4489   if (idx->getType()->isNonOverloadPlaceholderType()) {
4490     ExprResult result = CheckPlaceholderExpr(idx);
4491     if (result.isInvalid()) return ExprError();
4492     idx = result.get();
4493   }
4494 
4495   // Build an unanalyzed expression if either operand is type-dependent.
4496   if (getLangOpts().CPlusPlus &&
4497       (base->isTypeDependent() || idx->isTypeDependent())) {
4498     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4499                                             VK_LValue, OK_Ordinary, rbLoc);
4500   }
4501 
4502   // MSDN, property (C++)
4503   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4504   // This attribute can also be used in the declaration of an empty array in a
4505   // class or structure definition. For example:
4506   // __declspec(property(get=GetX, put=PutX)) int x[];
4507   // The above statement indicates that x[] can be used with one or more array
4508   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4509   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4510   if (IsMSPropertySubscript) {
4511     // Build MS property subscript expression if base is MS property reference
4512     // or MS property subscript.
4513     return new (Context) MSPropertySubscriptExpr(
4514         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4515   }
4516 
4517   // Use C++ overloaded-operator rules if either operand has record
4518   // type.  The spec says to do this if either type is *overloadable*,
4519   // but enum types can't declare subscript operators or conversion
4520   // operators, so there's nothing interesting for overload resolution
4521   // to do if there aren't any record types involved.
4522   //
4523   // ObjC pointers have their own subscripting logic that is not tied
4524   // to overload resolution and so should not take this path.
4525   if (getLangOpts().CPlusPlus &&
4526       (base->getType()->isRecordType() ||
4527        (!base->getType()->isObjCObjectPointerType() &&
4528         idx->getType()->isRecordType()))) {
4529     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4530   }
4531 
4532   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4533 
4534   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4535     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4536 
4537   return Res;
4538 }
4539 
4540 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4541   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4542   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4543 
4544   // For expressions like `&(*s).b`, the base is recorded and what should be
4545   // checked.
4546   const MemberExpr *Member = nullptr;
4547   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4548     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4549 
4550   LastRecord.PossibleDerefs.erase(StrippedExpr);
4551 }
4552 
4553 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4554   QualType ResultTy = E->getType();
4555   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4556 
4557   // Bail if the element is an array since it is not memory access.
4558   if (isa<ArrayType>(ResultTy))
4559     return;
4560 
4561   if (ResultTy->hasAttr(attr::NoDeref)) {
4562     LastRecord.PossibleDerefs.insert(E);
4563     return;
4564   }
4565 
4566   // Check if the base type is a pointer to a member access of a struct
4567   // marked with noderef.
4568   const Expr *Base = E->getBase();
4569   QualType BaseTy = Base->getType();
4570   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4571     // Not a pointer access
4572     return;
4573 
4574   const MemberExpr *Member = nullptr;
4575   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4576          Member->isArrow())
4577     Base = Member->getBase();
4578 
4579   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4580     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4581       LastRecord.PossibleDerefs.insert(E);
4582   }
4583 }
4584 
4585 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4586                                           Expr *LowerBound,
4587                                           SourceLocation ColonLoc, Expr *Length,
4588                                           SourceLocation RBLoc) {
4589   if (Base->getType()->isPlaceholderType() &&
4590       !Base->getType()->isSpecificPlaceholderType(
4591           BuiltinType::OMPArraySection)) {
4592     ExprResult Result = CheckPlaceholderExpr(Base);
4593     if (Result.isInvalid())
4594       return ExprError();
4595     Base = Result.get();
4596   }
4597   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4598     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4599     if (Result.isInvalid())
4600       return ExprError();
4601     Result = DefaultLvalueConversion(Result.get());
4602     if (Result.isInvalid())
4603       return ExprError();
4604     LowerBound = Result.get();
4605   }
4606   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4607     ExprResult Result = CheckPlaceholderExpr(Length);
4608     if (Result.isInvalid())
4609       return ExprError();
4610     Result = DefaultLvalueConversion(Result.get());
4611     if (Result.isInvalid())
4612       return ExprError();
4613     Length = Result.get();
4614   }
4615 
4616   // Build an unanalyzed expression if either operand is type-dependent.
4617   if (Base->isTypeDependent() ||
4618       (LowerBound &&
4619        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4620       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4621     return new (Context)
4622         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4623                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4624   }
4625 
4626   // Perform default conversions.
4627   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4628   QualType ResultTy;
4629   if (OriginalTy->isAnyPointerType()) {
4630     ResultTy = OriginalTy->getPointeeType();
4631   } else if (OriginalTy->isArrayType()) {
4632     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4633   } else {
4634     return ExprError(
4635         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4636         << Base->getSourceRange());
4637   }
4638   // C99 6.5.2.1p1
4639   if (LowerBound) {
4640     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4641                                                       LowerBound);
4642     if (Res.isInvalid())
4643       return ExprError(Diag(LowerBound->getExprLoc(),
4644                             diag::err_omp_typecheck_section_not_integer)
4645                        << 0 << LowerBound->getSourceRange());
4646     LowerBound = Res.get();
4647 
4648     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4649         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4650       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4651           << 0 << LowerBound->getSourceRange();
4652   }
4653   if (Length) {
4654     auto Res =
4655         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4656     if (Res.isInvalid())
4657       return ExprError(Diag(Length->getExprLoc(),
4658                             diag::err_omp_typecheck_section_not_integer)
4659                        << 1 << Length->getSourceRange());
4660     Length = Res.get();
4661 
4662     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4663         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4664       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4665           << 1 << Length->getSourceRange();
4666   }
4667 
4668   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4669   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4670   // type. Note that functions are not objects, and that (in C99 parlance)
4671   // incomplete types are not object types.
4672   if (ResultTy->isFunctionType()) {
4673     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4674         << ResultTy << Base->getSourceRange();
4675     return ExprError();
4676   }
4677 
4678   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4679                           diag::err_omp_section_incomplete_type, Base))
4680     return ExprError();
4681 
4682   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4683     Expr::EvalResult Result;
4684     if (LowerBound->EvaluateAsInt(Result, Context)) {
4685       // OpenMP 4.5, [2.4 Array Sections]
4686       // The array section must be a subset of the original array.
4687       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4688       if (LowerBoundValue.isNegative()) {
4689         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4690             << LowerBound->getSourceRange();
4691         return ExprError();
4692       }
4693     }
4694   }
4695 
4696   if (Length) {
4697     Expr::EvalResult Result;
4698     if (Length->EvaluateAsInt(Result, Context)) {
4699       // OpenMP 4.5, [2.4 Array Sections]
4700       // The length must evaluate to non-negative integers.
4701       llvm::APSInt LengthValue = Result.Val.getInt();
4702       if (LengthValue.isNegative()) {
4703         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4704             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4705             << Length->getSourceRange();
4706         return ExprError();
4707       }
4708     }
4709   } else if (ColonLoc.isValid() &&
4710              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4711                                       !OriginalTy->isVariableArrayType()))) {
4712     // OpenMP 4.5, [2.4 Array Sections]
4713     // When the size of the array dimension is not known, the length must be
4714     // specified explicitly.
4715     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4716         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4717     return ExprError();
4718   }
4719 
4720   if (!Base->getType()->isSpecificPlaceholderType(
4721           BuiltinType::OMPArraySection)) {
4722     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4723     if (Result.isInvalid())
4724       return ExprError();
4725     Base = Result.get();
4726   }
4727   return new (Context)
4728       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4729                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4730 }
4731 
4732 ExprResult
4733 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4734                                       Expr *Idx, SourceLocation RLoc) {
4735   Expr *LHSExp = Base;
4736   Expr *RHSExp = Idx;
4737 
4738   ExprValueKind VK = VK_LValue;
4739   ExprObjectKind OK = OK_Ordinary;
4740 
4741   // Per C++ core issue 1213, the result is an xvalue if either operand is
4742   // a non-lvalue array, and an lvalue otherwise.
4743   if (getLangOpts().CPlusPlus11) {
4744     for (auto *Op : {LHSExp, RHSExp}) {
4745       Op = Op->IgnoreImplicit();
4746       if (Op->getType()->isArrayType() && !Op->isLValue())
4747         VK = VK_XValue;
4748     }
4749   }
4750 
4751   // Perform default conversions.
4752   if (!LHSExp->getType()->getAs<VectorType>()) {
4753     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4754     if (Result.isInvalid())
4755       return ExprError();
4756     LHSExp = Result.get();
4757   }
4758   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4759   if (Result.isInvalid())
4760     return ExprError();
4761   RHSExp = Result.get();
4762 
4763   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4764 
4765   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4766   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4767   // in the subscript position. As a result, we need to derive the array base
4768   // and index from the expression types.
4769   Expr *BaseExpr, *IndexExpr;
4770   QualType ResultType;
4771   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4772     BaseExpr = LHSExp;
4773     IndexExpr = RHSExp;
4774     ResultType = Context.DependentTy;
4775   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4776     BaseExpr = LHSExp;
4777     IndexExpr = RHSExp;
4778     ResultType = PTy->getPointeeType();
4779   } else if (const ObjCObjectPointerType *PTy =
4780                LHSTy->getAs<ObjCObjectPointerType>()) {
4781     BaseExpr = LHSExp;
4782     IndexExpr = RHSExp;
4783 
4784     // Use custom logic if this should be the pseudo-object subscript
4785     // expression.
4786     if (!LangOpts.isSubscriptPointerArithmetic())
4787       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4788                                           nullptr);
4789 
4790     ResultType = PTy->getPointeeType();
4791   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4792      // Handle the uncommon case of "123[Ptr]".
4793     BaseExpr = RHSExp;
4794     IndexExpr = LHSExp;
4795     ResultType = PTy->getPointeeType();
4796   } else if (const ObjCObjectPointerType *PTy =
4797                RHSTy->getAs<ObjCObjectPointerType>()) {
4798      // Handle the uncommon case of "123[Ptr]".
4799     BaseExpr = RHSExp;
4800     IndexExpr = LHSExp;
4801     ResultType = PTy->getPointeeType();
4802     if (!LangOpts.isSubscriptPointerArithmetic()) {
4803       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4804         << ResultType << BaseExpr->getSourceRange();
4805       return ExprError();
4806     }
4807   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4808     BaseExpr = LHSExp;    // vectors: V[123]
4809     IndexExpr = RHSExp;
4810     // We apply C++ DR1213 to vector subscripting too.
4811     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4812       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4813       if (Materialized.isInvalid())
4814         return ExprError();
4815       LHSExp = Materialized.get();
4816     }
4817     VK = LHSExp->getValueKind();
4818     if (VK != VK_RValue)
4819       OK = OK_VectorComponent;
4820 
4821     ResultType = VTy->getElementType();
4822     QualType BaseType = BaseExpr->getType();
4823     Qualifiers BaseQuals = BaseType.getQualifiers();
4824     Qualifiers MemberQuals = ResultType.getQualifiers();
4825     Qualifiers Combined = BaseQuals + MemberQuals;
4826     if (Combined != MemberQuals)
4827       ResultType = Context.getQualifiedType(ResultType, Combined);
4828   } else if (LHSTy->isArrayType()) {
4829     // If we see an array that wasn't promoted by
4830     // DefaultFunctionArrayLvalueConversion, it must be an array that
4831     // wasn't promoted because of the C90 rule that doesn't
4832     // allow promoting non-lvalue arrays.  Warn, then
4833     // force the promotion here.
4834     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4835         << LHSExp->getSourceRange();
4836     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4837                                CK_ArrayToPointerDecay).get();
4838     LHSTy = LHSExp->getType();
4839 
4840     BaseExpr = LHSExp;
4841     IndexExpr = RHSExp;
4842     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4843   } else if (RHSTy->isArrayType()) {
4844     // Same as previous, except for 123[f().a] case
4845     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4846         << RHSExp->getSourceRange();
4847     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4848                                CK_ArrayToPointerDecay).get();
4849     RHSTy = RHSExp->getType();
4850 
4851     BaseExpr = RHSExp;
4852     IndexExpr = LHSExp;
4853     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4854   } else {
4855     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4856        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4857   }
4858   // C99 6.5.2.1p1
4859   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4860     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4861                      << IndexExpr->getSourceRange());
4862 
4863   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4864        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4865          && !IndexExpr->isTypeDependent())
4866     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4867 
4868   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4869   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4870   // type. Note that Functions are not objects, and that (in C99 parlance)
4871   // incomplete types are not object types.
4872   if (ResultType->isFunctionType()) {
4873     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4874         << ResultType << BaseExpr->getSourceRange();
4875     return ExprError();
4876   }
4877 
4878   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4879     // GNU extension: subscripting on pointer to void
4880     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4881       << BaseExpr->getSourceRange();
4882 
4883     // C forbids expressions of unqualified void type from being l-values.
4884     // See IsCForbiddenLValueType.
4885     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4886   } else if (!ResultType->isDependentType() &&
4887       RequireCompleteType(LLoc, ResultType,
4888                           diag::err_subscript_incomplete_type, BaseExpr))
4889     return ExprError();
4890 
4891   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4892          !ResultType.isCForbiddenLValueType());
4893 
4894   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4895       FunctionScopes.size() > 1) {
4896     if (auto *TT =
4897             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4898       for (auto I = FunctionScopes.rbegin(),
4899                 E = std::prev(FunctionScopes.rend());
4900            I != E; ++I) {
4901         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4902         if (CSI == nullptr)
4903           break;
4904         DeclContext *DC = nullptr;
4905         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4906           DC = LSI->CallOperator;
4907         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4908           DC = CRSI->TheCapturedDecl;
4909         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4910           DC = BSI->TheDecl;
4911         if (DC) {
4912           if (DC->containsDecl(TT->getDecl()))
4913             break;
4914           captureVariablyModifiedType(
4915               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4916         }
4917       }
4918     }
4919   }
4920 
4921   return new (Context)
4922       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4923 }
4924 
4925 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4926                                   ParmVarDecl *Param) {
4927   if (Param->hasUnparsedDefaultArg()) {
4928     Diag(CallLoc,
4929          diag::err_use_of_default_argument_to_function_declared_later) <<
4930       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4931     Diag(UnparsedDefaultArgLocs[Param],
4932          diag::note_default_argument_declared_here);
4933     return true;
4934   }
4935 
4936   if (Param->hasUninstantiatedDefaultArg()) {
4937     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4938 
4939     EnterExpressionEvaluationContext EvalContext(
4940         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4941 
4942     // Instantiate the expression.
4943     //
4944     // FIXME: Pass in a correct Pattern argument, otherwise
4945     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4946     //
4947     // template<typename T>
4948     // struct A {
4949     //   static int FooImpl();
4950     //
4951     //   template<typename Tp>
4952     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4953     //   // template argument list [[T], [Tp]], should be [[Tp]].
4954     //   friend A<Tp> Foo(int a);
4955     // };
4956     //
4957     // template<typename T>
4958     // A<T> Foo(int a = A<T>::FooImpl());
4959     MultiLevelTemplateArgumentList MutiLevelArgList
4960       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4961 
4962     InstantiatingTemplate Inst(*this, CallLoc, Param,
4963                                MutiLevelArgList.getInnermost());
4964     if (Inst.isInvalid())
4965       return true;
4966     if (Inst.isAlreadyInstantiating()) {
4967       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4968       Param->setInvalidDecl();
4969       return true;
4970     }
4971 
4972     ExprResult Result;
4973     {
4974       // C++ [dcl.fct.default]p5:
4975       //   The names in the [default argument] expression are bound, and
4976       //   the semantic constraints are checked, at the point where the
4977       //   default argument expression appears.
4978       ContextRAII SavedContext(*this, FD);
4979       LocalInstantiationScope Local(*this);
4980       runWithSufficientStackSpace(CallLoc, [&] {
4981         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4982                                   /*DirectInit*/false);
4983       });
4984     }
4985     if (Result.isInvalid())
4986       return true;
4987 
4988     // Check the expression as an initializer for the parameter.
4989     InitializedEntity Entity
4990       = InitializedEntity::InitializeParameter(Context, Param);
4991     InitializationKind Kind = InitializationKind::CreateCopy(
4992         Param->getLocation(),
4993         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4994     Expr *ResultE = Result.getAs<Expr>();
4995 
4996     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4997     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4998     if (Result.isInvalid())
4999       return true;
5000 
5001     Result =
5002         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5003                             /*DiscardedValue*/ false);
5004     if (Result.isInvalid())
5005       return true;
5006 
5007     // Remember the instantiated default argument.
5008     Param->setDefaultArg(Result.getAs<Expr>());
5009     if (ASTMutationListener *L = getASTMutationListener()) {
5010       L->DefaultArgumentInstantiated(Param);
5011     }
5012   }
5013 
5014   // If the default argument expression is not set yet, we are building it now.
5015   if (!Param->hasInit()) {
5016     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5017     Param->setInvalidDecl();
5018     return true;
5019   }
5020 
5021   // If the default expression creates temporaries, we need to
5022   // push them to the current stack of expression temporaries so they'll
5023   // be properly destroyed.
5024   // FIXME: We should really be rebuilding the default argument with new
5025   // bound temporaries; see the comment in PR5810.
5026   // We don't need to do that with block decls, though, because
5027   // blocks in default argument expression can never capture anything.
5028   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5029     // Set the "needs cleanups" bit regardless of whether there are
5030     // any explicit objects.
5031     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5032 
5033     // Append all the objects to the cleanup list.  Right now, this
5034     // should always be a no-op, because blocks in default argument
5035     // expressions should never be able to capture anything.
5036     assert(!Init->getNumObjects() &&
5037            "default argument expression has capturing blocks?");
5038   }
5039 
5040   // We already type-checked the argument, so we know it works.
5041   // Just mark all of the declarations in this potentially-evaluated expression
5042   // as being "referenced".
5043   EnterExpressionEvaluationContext EvalContext(
5044       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5045   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5046                                    /*SkipLocalVariables=*/true);
5047   return false;
5048 }
5049 
5050 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5051                                         FunctionDecl *FD, ParmVarDecl *Param) {
5052   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5053     return ExprError();
5054   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5055 }
5056 
5057 Sema::VariadicCallType
5058 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5059                           Expr *Fn) {
5060   if (Proto && Proto->isVariadic()) {
5061     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5062       return VariadicConstructor;
5063     else if (Fn && Fn->getType()->isBlockPointerType())
5064       return VariadicBlock;
5065     else if (FDecl) {
5066       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5067         if (Method->isInstance())
5068           return VariadicMethod;
5069     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5070       return VariadicMethod;
5071     return VariadicFunction;
5072   }
5073   return VariadicDoesNotApply;
5074 }
5075 
5076 namespace {
5077 class FunctionCallCCC final : public FunctionCallFilterCCC {
5078 public:
5079   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5080                   unsigned NumArgs, MemberExpr *ME)
5081       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5082         FunctionName(FuncName) {}
5083 
5084   bool ValidateCandidate(const TypoCorrection &candidate) override {
5085     if (!candidate.getCorrectionSpecifier() ||
5086         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5087       return false;
5088     }
5089 
5090     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5091   }
5092 
5093   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5094     return std::make_unique<FunctionCallCCC>(*this);
5095   }
5096 
5097 private:
5098   const IdentifierInfo *const FunctionName;
5099 };
5100 }
5101 
5102 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5103                                                FunctionDecl *FDecl,
5104                                                ArrayRef<Expr *> Args) {
5105   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5106   DeclarationName FuncName = FDecl->getDeclName();
5107   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5108 
5109   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5110   if (TypoCorrection Corrected = S.CorrectTypo(
5111           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5112           S.getScopeForContext(S.CurContext), nullptr, CCC,
5113           Sema::CTK_ErrorRecovery)) {
5114     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5115       if (Corrected.isOverloaded()) {
5116         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5117         OverloadCandidateSet::iterator Best;
5118         for (NamedDecl *CD : Corrected) {
5119           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5120             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5121                                    OCS);
5122         }
5123         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5124         case OR_Success:
5125           ND = Best->FoundDecl;
5126           Corrected.setCorrectionDecl(ND);
5127           break;
5128         default:
5129           break;
5130         }
5131       }
5132       ND = ND->getUnderlyingDecl();
5133       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5134         return Corrected;
5135     }
5136   }
5137   return TypoCorrection();
5138 }
5139 
5140 /// ConvertArgumentsForCall - Converts the arguments specified in
5141 /// Args/NumArgs to the parameter types of the function FDecl with
5142 /// function prototype Proto. Call is the call expression itself, and
5143 /// Fn is the function expression. For a C++ member function, this
5144 /// routine does not attempt to convert the object argument. Returns
5145 /// true if the call is ill-formed.
5146 bool
5147 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5148                               FunctionDecl *FDecl,
5149                               const FunctionProtoType *Proto,
5150                               ArrayRef<Expr *> Args,
5151                               SourceLocation RParenLoc,
5152                               bool IsExecConfig) {
5153   // Bail out early if calling a builtin with custom typechecking.
5154   if (FDecl)
5155     if (unsigned ID = FDecl->getBuiltinID())
5156       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5157         return false;
5158 
5159   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5160   // assignment, to the types of the corresponding parameter, ...
5161   unsigned NumParams = Proto->getNumParams();
5162   bool Invalid = false;
5163   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5164   unsigned FnKind = Fn->getType()->isBlockPointerType()
5165                        ? 1 /* block */
5166                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5167                                        : 0 /* function */);
5168 
5169   // If too few arguments are available (and we don't have default
5170   // arguments for the remaining parameters), don't make the call.
5171   if (Args.size() < NumParams) {
5172     if (Args.size() < MinArgs) {
5173       TypoCorrection TC;
5174       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5175         unsigned diag_id =
5176             MinArgs == NumParams && !Proto->isVariadic()
5177                 ? diag::err_typecheck_call_too_few_args_suggest
5178                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5179         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5180                                         << static_cast<unsigned>(Args.size())
5181                                         << TC.getCorrectionRange());
5182       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5183         Diag(RParenLoc,
5184              MinArgs == NumParams && !Proto->isVariadic()
5185                  ? diag::err_typecheck_call_too_few_args_one
5186                  : diag::err_typecheck_call_too_few_args_at_least_one)
5187             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5188       else
5189         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5190                             ? diag::err_typecheck_call_too_few_args
5191                             : diag::err_typecheck_call_too_few_args_at_least)
5192             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5193             << Fn->getSourceRange();
5194 
5195       // Emit the location of the prototype.
5196       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5197         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5198 
5199       return true;
5200     }
5201     // We reserve space for the default arguments when we create
5202     // the call expression, before calling ConvertArgumentsForCall.
5203     assert((Call->getNumArgs() == NumParams) &&
5204            "We should have reserved space for the default arguments before!");
5205   }
5206 
5207   // If too many are passed and not variadic, error on the extras and drop
5208   // them.
5209   if (Args.size() > NumParams) {
5210     if (!Proto->isVariadic()) {
5211       TypoCorrection TC;
5212       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5213         unsigned diag_id =
5214             MinArgs == NumParams && !Proto->isVariadic()
5215                 ? diag::err_typecheck_call_too_many_args_suggest
5216                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5217         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5218                                         << static_cast<unsigned>(Args.size())
5219                                         << TC.getCorrectionRange());
5220       } else if (NumParams == 1 && FDecl &&
5221                  FDecl->getParamDecl(0)->getDeclName())
5222         Diag(Args[NumParams]->getBeginLoc(),
5223              MinArgs == NumParams
5224                  ? diag::err_typecheck_call_too_many_args_one
5225                  : diag::err_typecheck_call_too_many_args_at_most_one)
5226             << FnKind << FDecl->getParamDecl(0)
5227             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5228             << SourceRange(Args[NumParams]->getBeginLoc(),
5229                            Args.back()->getEndLoc());
5230       else
5231         Diag(Args[NumParams]->getBeginLoc(),
5232              MinArgs == NumParams
5233                  ? diag::err_typecheck_call_too_many_args
5234                  : diag::err_typecheck_call_too_many_args_at_most)
5235             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5236             << Fn->getSourceRange()
5237             << SourceRange(Args[NumParams]->getBeginLoc(),
5238                            Args.back()->getEndLoc());
5239 
5240       // Emit the location of the prototype.
5241       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5242         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5243 
5244       // This deletes the extra arguments.
5245       Call->shrinkNumArgs(NumParams);
5246       return true;
5247     }
5248   }
5249   SmallVector<Expr *, 8> AllArgs;
5250   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5251 
5252   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5253                                    AllArgs, CallType);
5254   if (Invalid)
5255     return true;
5256   unsigned TotalNumArgs = AllArgs.size();
5257   for (unsigned i = 0; i < TotalNumArgs; ++i)
5258     Call->setArg(i, AllArgs[i]);
5259 
5260   return false;
5261 }
5262 
5263 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5264                                   const FunctionProtoType *Proto,
5265                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5266                                   SmallVectorImpl<Expr *> &AllArgs,
5267                                   VariadicCallType CallType, bool AllowExplicit,
5268                                   bool IsListInitialization) {
5269   unsigned NumParams = Proto->getNumParams();
5270   bool Invalid = false;
5271   size_t ArgIx = 0;
5272   // Continue to check argument types (even if we have too few/many args).
5273   for (unsigned i = FirstParam; i < NumParams; i++) {
5274     QualType ProtoArgType = Proto->getParamType(i);
5275 
5276     Expr *Arg;
5277     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5278     if (ArgIx < Args.size()) {
5279       Arg = Args[ArgIx++];
5280 
5281       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5282                               diag::err_call_incomplete_argument, Arg))
5283         return true;
5284 
5285       // Strip the unbridged-cast placeholder expression off, if applicable.
5286       bool CFAudited = false;
5287       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5288           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5289           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5290         Arg = stripARCUnbridgedCast(Arg);
5291       else if (getLangOpts().ObjCAutoRefCount &&
5292                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5293                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5294         CFAudited = true;
5295 
5296       if (Proto->getExtParameterInfo(i).isNoEscape())
5297         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5298           BE->getBlockDecl()->setDoesNotEscape();
5299 
5300       InitializedEntity Entity =
5301           Param ? InitializedEntity::InitializeParameter(Context, Param,
5302                                                          ProtoArgType)
5303                 : InitializedEntity::InitializeParameter(
5304                       Context, ProtoArgType, Proto->isParamConsumed(i));
5305 
5306       // Remember that parameter belongs to a CF audited API.
5307       if (CFAudited)
5308         Entity.setParameterCFAudited();
5309 
5310       ExprResult ArgE = PerformCopyInitialization(
5311           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5312       if (ArgE.isInvalid())
5313         return true;
5314 
5315       Arg = ArgE.getAs<Expr>();
5316     } else {
5317       assert(Param && "can't use default arguments without a known callee");
5318 
5319       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5320       if (ArgExpr.isInvalid())
5321         return true;
5322 
5323       Arg = ArgExpr.getAs<Expr>();
5324     }
5325 
5326     // Check for array bounds violations for each argument to the call. This
5327     // check only triggers warnings when the argument isn't a more complex Expr
5328     // with its own checking, such as a BinaryOperator.
5329     CheckArrayAccess(Arg);
5330 
5331     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5332     CheckStaticArrayArgument(CallLoc, Param, Arg);
5333 
5334     AllArgs.push_back(Arg);
5335   }
5336 
5337   // If this is a variadic call, handle args passed through "...".
5338   if (CallType != VariadicDoesNotApply) {
5339     // Assume that extern "C" functions with variadic arguments that
5340     // return __unknown_anytype aren't *really* variadic.
5341     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5342         FDecl->isExternC()) {
5343       for (Expr *A : Args.slice(ArgIx)) {
5344         QualType paramType; // ignored
5345         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5346         Invalid |= arg.isInvalid();
5347         AllArgs.push_back(arg.get());
5348       }
5349 
5350     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5351     } else {
5352       for (Expr *A : Args.slice(ArgIx)) {
5353         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5354         Invalid |= Arg.isInvalid();
5355         // Copy blocks to the heap.
5356         if (A->getType()->isBlockPointerType())
5357           maybeExtendBlockObject(Arg);
5358         AllArgs.push_back(Arg.get());
5359       }
5360     }
5361 
5362     // Check for array bounds violations.
5363     for (Expr *A : Args.slice(ArgIx))
5364       CheckArrayAccess(A);
5365   }
5366   return Invalid;
5367 }
5368 
5369 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5370   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5371   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5372     TL = DTL.getOriginalLoc();
5373   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5374     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5375       << ATL.getLocalSourceRange();
5376 }
5377 
5378 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5379 /// array parameter, check that it is non-null, and that if it is formed by
5380 /// array-to-pointer decay, the underlying array is sufficiently large.
5381 ///
5382 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5383 /// array type derivation, then for each call to the function, the value of the
5384 /// corresponding actual argument shall provide access to the first element of
5385 /// an array with at least as many elements as specified by the size expression.
5386 void
5387 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5388                                ParmVarDecl *Param,
5389                                const Expr *ArgExpr) {
5390   // Static array parameters are not supported in C++.
5391   if (!Param || getLangOpts().CPlusPlus)
5392     return;
5393 
5394   QualType OrigTy = Param->getOriginalType();
5395 
5396   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5397   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5398     return;
5399 
5400   if (ArgExpr->isNullPointerConstant(Context,
5401                                      Expr::NPC_NeverValueDependent)) {
5402     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5403     DiagnoseCalleeStaticArrayParam(*this, Param);
5404     return;
5405   }
5406 
5407   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5408   if (!CAT)
5409     return;
5410 
5411   const ConstantArrayType *ArgCAT =
5412     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5413   if (!ArgCAT)
5414     return;
5415 
5416   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5417                                              ArgCAT->getElementType())) {
5418     if (ArgCAT->getSize().ult(CAT->getSize())) {
5419       Diag(CallLoc, diag::warn_static_array_too_small)
5420           << ArgExpr->getSourceRange()
5421           << (unsigned)ArgCAT->getSize().getZExtValue()
5422           << (unsigned)CAT->getSize().getZExtValue() << 0;
5423       DiagnoseCalleeStaticArrayParam(*this, Param);
5424     }
5425     return;
5426   }
5427 
5428   Optional<CharUnits> ArgSize =
5429       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5430   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5431   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5432     Diag(CallLoc, diag::warn_static_array_too_small)
5433         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5434         << (unsigned)ParmSize->getQuantity() << 1;
5435     DiagnoseCalleeStaticArrayParam(*this, Param);
5436   }
5437 }
5438 
5439 /// Given a function expression of unknown-any type, try to rebuild it
5440 /// to have a function type.
5441 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5442 
5443 /// Is the given type a placeholder that we need to lower out
5444 /// immediately during argument processing?
5445 static bool isPlaceholderToRemoveAsArg(QualType type) {
5446   // Placeholders are never sugared.
5447   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5448   if (!placeholder) return false;
5449 
5450   switch (placeholder->getKind()) {
5451   // Ignore all the non-placeholder types.
5452 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5453   case BuiltinType::Id:
5454 #include "clang/Basic/OpenCLImageTypes.def"
5455 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5456   case BuiltinType::Id:
5457 #include "clang/Basic/OpenCLExtensionTypes.def"
5458   // In practice we'll never use this, since all SVE types are sugared
5459   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5460 #define SVE_TYPE(Name, Id, SingletonId) \
5461   case BuiltinType::Id:
5462 #include "clang/Basic/AArch64SVEACLETypes.def"
5463 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5464 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5465 #include "clang/AST/BuiltinTypes.def"
5466     return false;
5467 
5468   // We cannot lower out overload sets; they might validly be resolved
5469   // by the call machinery.
5470   case BuiltinType::Overload:
5471     return false;
5472 
5473   // Unbridged casts in ARC can be handled in some call positions and
5474   // should be left in place.
5475   case BuiltinType::ARCUnbridgedCast:
5476     return false;
5477 
5478   // Pseudo-objects should be converted as soon as possible.
5479   case BuiltinType::PseudoObject:
5480     return true;
5481 
5482   // The debugger mode could theoretically but currently does not try
5483   // to resolve unknown-typed arguments based on known parameter types.
5484   case BuiltinType::UnknownAny:
5485     return true;
5486 
5487   // These are always invalid as call arguments and should be reported.
5488   case BuiltinType::BoundMember:
5489   case BuiltinType::BuiltinFn:
5490   case BuiltinType::OMPArraySection:
5491     return true;
5492 
5493   }
5494   llvm_unreachable("bad builtin type kind");
5495 }
5496 
5497 /// Check an argument list for placeholders that we won't try to
5498 /// handle later.
5499 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5500   // Apply this processing to all the arguments at once instead of
5501   // dying at the first failure.
5502   bool hasInvalid = false;
5503   for (size_t i = 0, e = args.size(); i != e; i++) {
5504     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5505       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5506       if (result.isInvalid()) hasInvalid = true;
5507       else args[i] = result.get();
5508     } else if (hasInvalid) {
5509       (void)S.CorrectDelayedTyposInExpr(args[i]);
5510     }
5511   }
5512   return hasInvalid;
5513 }
5514 
5515 /// If a builtin function has a pointer argument with no explicit address
5516 /// space, then it should be able to accept a pointer to any address
5517 /// space as input.  In order to do this, we need to replace the
5518 /// standard builtin declaration with one that uses the same address space
5519 /// as the call.
5520 ///
5521 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5522 ///                  it does not contain any pointer arguments without
5523 ///                  an address space qualifer.  Otherwise the rewritten
5524 ///                  FunctionDecl is returned.
5525 /// TODO: Handle pointer return types.
5526 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5527                                                 FunctionDecl *FDecl,
5528                                                 MultiExprArg ArgExprs) {
5529 
5530   QualType DeclType = FDecl->getType();
5531   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5532 
5533   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5534       ArgExprs.size() < FT->getNumParams())
5535     return nullptr;
5536 
5537   bool NeedsNewDecl = false;
5538   unsigned i = 0;
5539   SmallVector<QualType, 8> OverloadParams;
5540 
5541   for (QualType ParamType : FT->param_types()) {
5542 
5543     // Convert array arguments to pointer to simplify type lookup.
5544     ExprResult ArgRes =
5545         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5546     if (ArgRes.isInvalid())
5547       return nullptr;
5548     Expr *Arg = ArgRes.get();
5549     QualType ArgType = Arg->getType();
5550     if (!ParamType->isPointerType() ||
5551         ParamType.hasAddressSpace() ||
5552         !ArgType->isPointerType() ||
5553         !ArgType->getPointeeType().hasAddressSpace()) {
5554       OverloadParams.push_back(ParamType);
5555       continue;
5556     }
5557 
5558     QualType PointeeType = ParamType->getPointeeType();
5559     if (PointeeType.hasAddressSpace())
5560       continue;
5561 
5562     NeedsNewDecl = true;
5563     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5564 
5565     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5566     OverloadParams.push_back(Context.getPointerType(PointeeType));
5567   }
5568 
5569   if (!NeedsNewDecl)
5570     return nullptr;
5571 
5572   FunctionProtoType::ExtProtoInfo EPI;
5573   EPI.Variadic = FT->isVariadic();
5574   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5575                                                 OverloadParams, EPI);
5576   DeclContext *Parent = FDecl->getParent();
5577   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5578                                                     FDecl->getLocation(),
5579                                                     FDecl->getLocation(),
5580                                                     FDecl->getIdentifier(),
5581                                                     OverloadTy,
5582                                                     /*TInfo=*/nullptr,
5583                                                     SC_Extern, false,
5584                                                     /*hasPrototype=*/true);
5585   SmallVector<ParmVarDecl*, 16> Params;
5586   FT = cast<FunctionProtoType>(OverloadTy);
5587   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5588     QualType ParamType = FT->getParamType(i);
5589     ParmVarDecl *Parm =
5590         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5591                                 SourceLocation(), nullptr, ParamType,
5592                                 /*TInfo=*/nullptr, SC_None, nullptr);
5593     Parm->setScopeInfo(0, i);
5594     Params.push_back(Parm);
5595   }
5596   OverloadDecl->setParams(Params);
5597   return OverloadDecl;
5598 }
5599 
5600 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5601                                     FunctionDecl *Callee,
5602                                     MultiExprArg ArgExprs) {
5603   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5604   // similar attributes) really don't like it when functions are called with an
5605   // invalid number of args.
5606   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5607                          /*PartialOverloading=*/false) &&
5608       !Callee->isVariadic())
5609     return;
5610   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5611     return;
5612 
5613   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5614     S.Diag(Fn->getBeginLoc(),
5615            isa<CXXMethodDecl>(Callee)
5616                ? diag::err_ovl_no_viable_member_function_in_call
5617                : diag::err_ovl_no_viable_function_in_call)
5618         << Callee << Callee->getSourceRange();
5619     S.Diag(Callee->getLocation(),
5620            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5621         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5622     return;
5623   }
5624 }
5625 
5626 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5627     const UnresolvedMemberExpr *const UME, Sema &S) {
5628 
5629   const auto GetFunctionLevelDCIfCXXClass =
5630       [](Sema &S) -> const CXXRecordDecl * {
5631     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5632     if (!DC || !DC->getParent())
5633       return nullptr;
5634 
5635     // If the call to some member function was made from within a member
5636     // function body 'M' return return 'M's parent.
5637     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5638       return MD->getParent()->getCanonicalDecl();
5639     // else the call was made from within a default member initializer of a
5640     // class, so return the class.
5641     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5642       return RD->getCanonicalDecl();
5643     return nullptr;
5644   };
5645   // If our DeclContext is neither a member function nor a class (in the
5646   // case of a lambda in a default member initializer), we can't have an
5647   // enclosing 'this'.
5648 
5649   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5650   if (!CurParentClass)
5651     return false;
5652 
5653   // The naming class for implicit member functions call is the class in which
5654   // name lookup starts.
5655   const CXXRecordDecl *const NamingClass =
5656       UME->getNamingClass()->getCanonicalDecl();
5657   assert(NamingClass && "Must have naming class even for implicit access");
5658 
5659   // If the unresolved member functions were found in a 'naming class' that is
5660   // related (either the same or derived from) to the class that contains the
5661   // member function that itself contained the implicit member access.
5662 
5663   return CurParentClass == NamingClass ||
5664          CurParentClass->isDerivedFrom(NamingClass);
5665 }
5666 
5667 static void
5668 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5669     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5670 
5671   if (!UME)
5672     return;
5673 
5674   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5675   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5676   // already been captured, or if this is an implicit member function call (if
5677   // it isn't, an attempt to capture 'this' should already have been made).
5678   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5679       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5680     return;
5681 
5682   // Check if the naming class in which the unresolved members were found is
5683   // related (same as or is a base of) to the enclosing class.
5684 
5685   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5686     return;
5687 
5688 
5689   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5690   // If the enclosing function is not dependent, then this lambda is
5691   // capture ready, so if we can capture this, do so.
5692   if (!EnclosingFunctionCtx->isDependentContext()) {
5693     // If the current lambda and all enclosing lambdas can capture 'this' -
5694     // then go ahead and capture 'this' (since our unresolved overload set
5695     // contains at least one non-static member function).
5696     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5697       S.CheckCXXThisCapture(CallLoc);
5698   } else if (S.CurContext->isDependentContext()) {
5699     // ... since this is an implicit member reference, that might potentially
5700     // involve a 'this' capture, mark 'this' for potential capture in
5701     // enclosing lambdas.
5702     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5703       CurLSI->addPotentialThisCapture(CallLoc);
5704   }
5705 }
5706 
5707 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5708                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5709                                Expr *ExecConfig) {
5710   ExprResult Call =
5711       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5712   if (Call.isInvalid())
5713     return Call;
5714 
5715   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5716   // language modes.
5717   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5718     if (ULE->hasExplicitTemplateArgs() &&
5719         ULE->decls_begin() == ULE->decls_end()) {
5720       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5721                                  ? diag::warn_cxx17_compat_adl_only_template_id
5722                                  : diag::ext_adl_only_template_id)
5723           << ULE->getName();
5724     }
5725   }
5726 
5727   return Call;
5728 }
5729 
5730 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5731 /// This provides the location of the left/right parens and a list of comma
5732 /// locations.
5733 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5734                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5735                                Expr *ExecConfig, bool IsExecConfig) {
5736   // Since this might be a postfix expression, get rid of ParenListExprs.
5737   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5738   if (Result.isInvalid()) return ExprError();
5739   Fn = Result.get();
5740 
5741   if (checkArgsForPlaceholders(*this, ArgExprs))
5742     return ExprError();
5743 
5744   if (getLangOpts().CPlusPlus) {
5745     // If this is a pseudo-destructor expression, build the call immediately.
5746     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5747       if (!ArgExprs.empty()) {
5748         // Pseudo-destructor calls should not have any arguments.
5749         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5750             << FixItHint::CreateRemoval(
5751                    SourceRange(ArgExprs.front()->getBeginLoc(),
5752                                ArgExprs.back()->getEndLoc()));
5753       }
5754 
5755       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5756                               VK_RValue, RParenLoc);
5757     }
5758     if (Fn->getType() == Context.PseudoObjectTy) {
5759       ExprResult result = CheckPlaceholderExpr(Fn);
5760       if (result.isInvalid()) return ExprError();
5761       Fn = result.get();
5762     }
5763 
5764     // Determine whether this is a dependent call inside a C++ template,
5765     // in which case we won't do any semantic analysis now.
5766     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5767       if (ExecConfig) {
5768         return CUDAKernelCallExpr::Create(
5769             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5770             Context.DependentTy, VK_RValue, RParenLoc);
5771       } else {
5772 
5773         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5774             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5775             Fn->getBeginLoc());
5776 
5777         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5778                                 VK_RValue, RParenLoc);
5779       }
5780     }
5781 
5782     // Determine whether this is a call to an object (C++ [over.call.object]).
5783     if (Fn->getType()->isRecordType())
5784       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5785                                           RParenLoc);
5786 
5787     if (Fn->getType() == Context.UnknownAnyTy) {
5788       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5789       if (result.isInvalid()) return ExprError();
5790       Fn = result.get();
5791     }
5792 
5793     if (Fn->getType() == Context.BoundMemberTy) {
5794       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5795                                        RParenLoc);
5796     }
5797   }
5798 
5799   // Check for overloaded calls.  This can happen even in C due to extensions.
5800   if (Fn->getType() == Context.OverloadTy) {
5801     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5802 
5803     // We aren't supposed to apply this logic if there's an '&' involved.
5804     if (!find.HasFormOfMemberPointer) {
5805       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5806         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5807                                 VK_RValue, RParenLoc);
5808       OverloadExpr *ovl = find.Expression;
5809       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5810         return BuildOverloadedCallExpr(
5811             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5812             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5813       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5814                                        RParenLoc);
5815     }
5816   }
5817 
5818   // If we're directly calling a function, get the appropriate declaration.
5819   if (Fn->getType() == Context.UnknownAnyTy) {
5820     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5821     if (result.isInvalid()) return ExprError();
5822     Fn = result.get();
5823   }
5824 
5825   Expr *NakedFn = Fn->IgnoreParens();
5826 
5827   bool CallingNDeclIndirectly = false;
5828   NamedDecl *NDecl = nullptr;
5829   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5830     if (UnOp->getOpcode() == UO_AddrOf) {
5831       CallingNDeclIndirectly = true;
5832       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5833     }
5834   }
5835 
5836   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5837     NDecl = DRE->getDecl();
5838 
5839     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5840     if (FDecl && FDecl->getBuiltinID()) {
5841       // Rewrite the function decl for this builtin by replacing parameters
5842       // with no explicit address space with the address space of the arguments
5843       // in ArgExprs.
5844       if ((FDecl =
5845                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5846         NDecl = FDecl;
5847         Fn = DeclRefExpr::Create(
5848             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5849             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5850             nullptr, DRE->isNonOdrUse());
5851       }
5852     }
5853   } else if (isa<MemberExpr>(NakedFn))
5854     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5855 
5856   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5857     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5858                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5859       return ExprError();
5860 
5861     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5862       return ExprError();
5863 
5864     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5865   }
5866 
5867   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5868                                ExecConfig, IsExecConfig);
5869 }
5870 
5871 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5872 ///
5873 /// __builtin_astype( value, dst type )
5874 ///
5875 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5876                                  SourceLocation BuiltinLoc,
5877                                  SourceLocation RParenLoc) {
5878   ExprValueKind VK = VK_RValue;
5879   ExprObjectKind OK = OK_Ordinary;
5880   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5881   QualType SrcTy = E->getType();
5882   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5883     return ExprError(Diag(BuiltinLoc,
5884                           diag::err_invalid_astype_of_different_size)
5885                      << DstTy
5886                      << SrcTy
5887                      << E->getSourceRange());
5888   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5889 }
5890 
5891 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5892 /// provided arguments.
5893 ///
5894 /// __builtin_convertvector( value, dst type )
5895 ///
5896 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5897                                         SourceLocation BuiltinLoc,
5898                                         SourceLocation RParenLoc) {
5899   TypeSourceInfo *TInfo;
5900   GetTypeFromParser(ParsedDestTy, &TInfo);
5901   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5902 }
5903 
5904 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5905 /// i.e. an expression not of \p OverloadTy.  The expression should
5906 /// unary-convert to an expression of function-pointer or
5907 /// block-pointer type.
5908 ///
5909 /// \param NDecl the declaration being called, if available
5910 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5911                                        SourceLocation LParenLoc,
5912                                        ArrayRef<Expr *> Args,
5913                                        SourceLocation RParenLoc, Expr *Config,
5914                                        bool IsExecConfig, ADLCallKind UsesADL) {
5915   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5916   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5917 
5918   // Functions with 'interrupt' attribute cannot be called directly.
5919   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5920     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5921     return ExprError();
5922   }
5923 
5924   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5925   // so there's some risk when calling out to non-interrupt handler functions
5926   // that the callee might not preserve them. This is easy to diagnose here,
5927   // but can be very challenging to debug.
5928   if (auto *Caller = getCurFunctionDecl())
5929     if (Caller->hasAttr<ARMInterruptAttr>()) {
5930       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5931       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5932         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5933     }
5934 
5935   // Promote the function operand.
5936   // We special-case function promotion here because we only allow promoting
5937   // builtin functions to function pointers in the callee of a call.
5938   ExprResult Result;
5939   QualType ResultTy;
5940   if (BuiltinID &&
5941       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5942     // Extract the return type from the (builtin) function pointer type.
5943     // FIXME Several builtins still have setType in
5944     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5945     // Builtins.def to ensure they are correct before removing setType calls.
5946     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5947     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5948     ResultTy = FDecl->getCallResultType();
5949   } else {
5950     Result = CallExprUnaryConversions(Fn);
5951     ResultTy = Context.BoolTy;
5952   }
5953   if (Result.isInvalid())
5954     return ExprError();
5955   Fn = Result.get();
5956 
5957   // Check for a valid function type, but only if it is not a builtin which
5958   // requires custom type checking. These will be handled by
5959   // CheckBuiltinFunctionCall below just after creation of the call expression.
5960   const FunctionType *FuncT = nullptr;
5961   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5962   retry:
5963     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5964       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5965       // have type pointer to function".
5966       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5967       if (!FuncT)
5968         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5969                          << Fn->getType() << Fn->getSourceRange());
5970     } else if (const BlockPointerType *BPT =
5971                    Fn->getType()->getAs<BlockPointerType>()) {
5972       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5973     } else {
5974       // Handle calls to expressions of unknown-any type.
5975       if (Fn->getType() == Context.UnknownAnyTy) {
5976         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5977         if (rewrite.isInvalid())
5978           return ExprError();
5979         Fn = rewrite.get();
5980         goto retry;
5981       }
5982 
5983       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5984                        << Fn->getType() << Fn->getSourceRange());
5985     }
5986   }
5987 
5988   // Get the number of parameters in the function prototype, if any.
5989   // We will allocate space for max(Args.size(), NumParams) arguments
5990   // in the call expression.
5991   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5992   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5993 
5994   CallExpr *TheCall;
5995   if (Config) {
5996     assert(UsesADL == ADLCallKind::NotADL &&
5997            "CUDAKernelCallExpr should not use ADL");
5998     TheCall =
5999         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6000                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6001   } else {
6002     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6003                                RParenLoc, NumParams, UsesADL);
6004   }
6005 
6006   if (!getLangOpts().CPlusPlus) {
6007     // Forget about the nulled arguments since typo correction
6008     // do not handle them well.
6009     TheCall->shrinkNumArgs(Args.size());
6010     // C cannot always handle TypoExpr nodes in builtin calls and direct
6011     // function calls as their argument checking don't necessarily handle
6012     // dependent types properly, so make sure any TypoExprs have been
6013     // dealt with.
6014     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6015     if (!Result.isUsable()) return ExprError();
6016     CallExpr *TheOldCall = TheCall;
6017     TheCall = dyn_cast<CallExpr>(Result.get());
6018     bool CorrectedTypos = TheCall != TheOldCall;
6019     if (!TheCall) return Result;
6020     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6021 
6022     // A new call expression node was created if some typos were corrected.
6023     // However it may not have been constructed with enough storage. In this
6024     // case, rebuild the node with enough storage. The waste of space is
6025     // immaterial since this only happens when some typos were corrected.
6026     if (CorrectedTypos && Args.size() < NumParams) {
6027       if (Config)
6028         TheCall = CUDAKernelCallExpr::Create(
6029             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6030             RParenLoc, NumParams);
6031       else
6032         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6033                                    RParenLoc, NumParams, UsesADL);
6034     }
6035     // We can now handle the nulled arguments for the default arguments.
6036     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6037   }
6038 
6039   // Bail out early if calling a builtin with custom type checking.
6040   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6041     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6042 
6043   if (getLangOpts().CUDA) {
6044     if (Config) {
6045       // CUDA: Kernel calls must be to global functions
6046       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6047         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6048             << FDecl << Fn->getSourceRange());
6049 
6050       // CUDA: Kernel function must have 'void' return type
6051       if (!FuncT->getReturnType()->isVoidType() &&
6052           !FuncT->getReturnType()->getAs<AutoType>() &&
6053           !FuncT->getReturnType()->isInstantiationDependentType())
6054         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6055             << Fn->getType() << Fn->getSourceRange());
6056     } else {
6057       // CUDA: Calls to global functions must be configured
6058       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6059         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6060             << FDecl << Fn->getSourceRange());
6061     }
6062   }
6063 
6064   // Check for a valid return type
6065   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6066                           FDecl))
6067     return ExprError();
6068 
6069   // We know the result type of the call, set it.
6070   TheCall->setType(FuncT->getCallResultType(Context));
6071   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6072 
6073   if (Proto) {
6074     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6075                                 IsExecConfig))
6076       return ExprError();
6077   } else {
6078     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6079 
6080     if (FDecl) {
6081       // Check if we have too few/too many template arguments, based
6082       // on our knowledge of the function definition.
6083       const FunctionDecl *Def = nullptr;
6084       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6085         Proto = Def->getType()->getAs<FunctionProtoType>();
6086        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6087           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6088           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6089       }
6090 
6091       // If the function we're calling isn't a function prototype, but we have
6092       // a function prototype from a prior declaratiom, use that prototype.
6093       if (!FDecl->hasPrototype())
6094         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6095     }
6096 
6097     // Promote the arguments (C99 6.5.2.2p6).
6098     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6099       Expr *Arg = Args[i];
6100 
6101       if (Proto && i < Proto->getNumParams()) {
6102         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6103             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6104         ExprResult ArgE =
6105             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6106         if (ArgE.isInvalid())
6107           return true;
6108 
6109         Arg = ArgE.getAs<Expr>();
6110 
6111       } else {
6112         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6113 
6114         if (ArgE.isInvalid())
6115           return true;
6116 
6117         Arg = ArgE.getAs<Expr>();
6118       }
6119 
6120       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6121                               diag::err_call_incomplete_argument, Arg))
6122         return ExprError();
6123 
6124       TheCall->setArg(i, Arg);
6125     }
6126   }
6127 
6128   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6129     if (!Method->isStatic())
6130       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6131         << Fn->getSourceRange());
6132 
6133   // Check for sentinels
6134   if (NDecl)
6135     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6136 
6137   // Do special checking on direct calls to functions.
6138   if (FDecl) {
6139     if (CheckFunctionCall(FDecl, TheCall, Proto))
6140       return ExprError();
6141 
6142     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6143 
6144     if (BuiltinID)
6145       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6146   } else if (NDecl) {
6147     if (CheckPointerCall(NDecl, TheCall, Proto))
6148       return ExprError();
6149   } else {
6150     if (CheckOtherCall(TheCall, Proto))
6151       return ExprError();
6152   }
6153 
6154   return MaybeBindToTemporary(TheCall);
6155 }
6156 
6157 ExprResult
6158 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6159                            SourceLocation RParenLoc, Expr *InitExpr) {
6160   assert(Ty && "ActOnCompoundLiteral(): missing type");
6161   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6162 
6163   TypeSourceInfo *TInfo;
6164   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6165   if (!TInfo)
6166     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6167 
6168   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6169 }
6170 
6171 ExprResult
6172 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6173                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6174   QualType literalType = TInfo->getType();
6175 
6176   if (literalType->isArrayType()) {
6177     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6178           diag::err_illegal_decl_array_incomplete_type,
6179           SourceRange(LParenLoc,
6180                       LiteralExpr->getSourceRange().getEnd())))
6181       return ExprError();
6182     if (literalType->isVariableArrayType())
6183       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6184         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6185   } else if (!literalType->isDependentType() &&
6186              RequireCompleteType(LParenLoc, literalType,
6187                diag::err_typecheck_decl_incomplete_type,
6188                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6189     return ExprError();
6190 
6191   InitializedEntity Entity
6192     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6193   InitializationKind Kind
6194     = InitializationKind::CreateCStyleCast(LParenLoc,
6195                                            SourceRange(LParenLoc, RParenLoc),
6196                                            /*InitList=*/true);
6197   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6198   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6199                                       &literalType);
6200   if (Result.isInvalid())
6201     return ExprError();
6202   LiteralExpr = Result.get();
6203 
6204   bool isFileScope = !CurContext->isFunctionOrMethod();
6205 
6206   // In C, compound literals are l-values for some reason.
6207   // For GCC compatibility, in C++, file-scope array compound literals with
6208   // constant initializers are also l-values, and compound literals are
6209   // otherwise prvalues.
6210   //
6211   // (GCC also treats C++ list-initialized file-scope array prvalues with
6212   // constant initializers as l-values, but that's non-conforming, so we don't
6213   // follow it there.)
6214   //
6215   // FIXME: It would be better to handle the lvalue cases as materializing and
6216   // lifetime-extending a temporary object, but our materialized temporaries
6217   // representation only supports lifetime extension from a variable, not "out
6218   // of thin air".
6219   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6220   // is bound to the result of applying array-to-pointer decay to the compound
6221   // literal.
6222   // FIXME: GCC supports compound literals of reference type, which should
6223   // obviously have a value kind derived from the kind of reference involved.
6224   ExprValueKind VK =
6225       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6226           ? VK_RValue
6227           : VK_LValue;
6228 
6229   if (isFileScope)
6230     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6231       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6232         Expr *Init = ILE->getInit(i);
6233         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6234       }
6235 
6236   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6237                                               VK, LiteralExpr, isFileScope);
6238   if (isFileScope) {
6239     if (!LiteralExpr->isTypeDependent() &&
6240         !LiteralExpr->isValueDependent() &&
6241         !literalType->isDependentType()) // C99 6.5.2.5p3
6242       if (CheckForConstantInitializer(LiteralExpr, literalType))
6243         return ExprError();
6244   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6245              literalType.getAddressSpace() != LangAS::Default) {
6246     // Embedded-C extensions to C99 6.5.2.5:
6247     //   "If the compound literal occurs inside the body of a function, the
6248     //   type name shall not be qualified by an address-space qualifier."
6249     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6250       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6251     return ExprError();
6252   }
6253 
6254   // Compound literals that have automatic storage duration are destroyed at
6255   // the end of the scope. Emit diagnostics if it is or contains a C union type
6256   // that is non-trivial to destruct.
6257   if (!isFileScope)
6258     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6259       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6260                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6261 
6262   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6263       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6264     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6265                                        E->getInitializer()->getExprLoc());
6266 
6267   return MaybeBindToTemporary(E);
6268 }
6269 
6270 ExprResult
6271 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6272                     SourceLocation RBraceLoc) {
6273   // Only produce each kind of designated initialization diagnostic once.
6274   SourceLocation FirstDesignator;
6275   bool DiagnosedArrayDesignator = false;
6276   bool DiagnosedNestedDesignator = false;
6277   bool DiagnosedMixedDesignator = false;
6278 
6279   // Check that any designated initializers are syntactically valid in the
6280   // current language mode.
6281   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6282     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6283       if (FirstDesignator.isInvalid())
6284         FirstDesignator = DIE->getBeginLoc();
6285 
6286       if (!getLangOpts().CPlusPlus)
6287         break;
6288 
6289       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6290         DiagnosedNestedDesignator = true;
6291         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6292           << DIE->getDesignatorsSourceRange();
6293       }
6294 
6295       for (auto &Desig : DIE->designators()) {
6296         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6297           DiagnosedArrayDesignator = true;
6298           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6299             << Desig.getSourceRange();
6300         }
6301       }
6302 
6303       if (!DiagnosedMixedDesignator &&
6304           !isa<DesignatedInitExpr>(InitArgList[0])) {
6305         DiagnosedMixedDesignator = true;
6306         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6307           << DIE->getSourceRange();
6308         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6309           << InitArgList[0]->getSourceRange();
6310       }
6311     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6312                isa<DesignatedInitExpr>(InitArgList[0])) {
6313       DiagnosedMixedDesignator = true;
6314       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6315       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6316         << DIE->getSourceRange();
6317       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6318         << InitArgList[I]->getSourceRange();
6319     }
6320   }
6321 
6322   if (FirstDesignator.isValid()) {
6323     // Only diagnose designated initiaization as a C++20 extension if we didn't
6324     // already diagnose use of (non-C++20) C99 designator syntax.
6325     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6326         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6327       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6328                                 ? diag::warn_cxx17_compat_designated_init
6329                                 : diag::ext_cxx_designated_init);
6330     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6331       Diag(FirstDesignator, diag::ext_designated_init);
6332     }
6333   }
6334 
6335   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6336 }
6337 
6338 ExprResult
6339 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6340                     SourceLocation RBraceLoc) {
6341   // Semantic analysis for initializers is done by ActOnDeclarator() and
6342   // CheckInitializer() - it requires knowledge of the object being initialized.
6343 
6344   // Immediately handle non-overload placeholders.  Overloads can be
6345   // resolved contextually, but everything else here can't.
6346   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6347     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6348       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6349 
6350       // Ignore failures; dropping the entire initializer list because
6351       // of one failure would be terrible for indexing/etc.
6352       if (result.isInvalid()) continue;
6353 
6354       InitArgList[I] = result.get();
6355     }
6356   }
6357 
6358   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6359                                                RBraceLoc);
6360   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6361   return E;
6362 }
6363 
6364 /// Do an explicit extend of the given block pointer if we're in ARC.
6365 void Sema::maybeExtendBlockObject(ExprResult &E) {
6366   assert(E.get()->getType()->isBlockPointerType());
6367   assert(E.get()->isRValue());
6368 
6369   // Only do this in an r-value context.
6370   if (!getLangOpts().ObjCAutoRefCount) return;
6371 
6372   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6373                                CK_ARCExtendBlockObject, E.get(),
6374                                /*base path*/ nullptr, VK_RValue);
6375   Cleanup.setExprNeedsCleanups(true);
6376 }
6377 
6378 /// Prepare a conversion of the given expression to an ObjC object
6379 /// pointer type.
6380 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6381   QualType type = E.get()->getType();
6382   if (type->isObjCObjectPointerType()) {
6383     return CK_BitCast;
6384   } else if (type->isBlockPointerType()) {
6385     maybeExtendBlockObject(E);
6386     return CK_BlockPointerToObjCPointerCast;
6387   } else {
6388     assert(type->isPointerType());
6389     return CK_CPointerToObjCPointerCast;
6390   }
6391 }
6392 
6393 /// Prepares for a scalar cast, performing all the necessary stages
6394 /// except the final cast and returning the kind required.
6395 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6396   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6397   // Also, callers should have filtered out the invalid cases with
6398   // pointers.  Everything else should be possible.
6399 
6400   QualType SrcTy = Src.get()->getType();
6401   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6402     return CK_NoOp;
6403 
6404   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6405   case Type::STK_MemberPointer:
6406     llvm_unreachable("member pointer type in C");
6407 
6408   case Type::STK_CPointer:
6409   case Type::STK_BlockPointer:
6410   case Type::STK_ObjCObjectPointer:
6411     switch (DestTy->getScalarTypeKind()) {
6412     case Type::STK_CPointer: {
6413       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6414       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6415       if (SrcAS != DestAS)
6416         return CK_AddressSpaceConversion;
6417       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6418         return CK_NoOp;
6419       return CK_BitCast;
6420     }
6421     case Type::STK_BlockPointer:
6422       return (SrcKind == Type::STK_BlockPointer
6423                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6424     case Type::STK_ObjCObjectPointer:
6425       if (SrcKind == Type::STK_ObjCObjectPointer)
6426         return CK_BitCast;
6427       if (SrcKind == Type::STK_CPointer)
6428         return CK_CPointerToObjCPointerCast;
6429       maybeExtendBlockObject(Src);
6430       return CK_BlockPointerToObjCPointerCast;
6431     case Type::STK_Bool:
6432       return CK_PointerToBoolean;
6433     case Type::STK_Integral:
6434       return CK_PointerToIntegral;
6435     case Type::STK_Floating:
6436     case Type::STK_FloatingComplex:
6437     case Type::STK_IntegralComplex:
6438     case Type::STK_MemberPointer:
6439     case Type::STK_FixedPoint:
6440       llvm_unreachable("illegal cast from pointer");
6441     }
6442     llvm_unreachable("Should have returned before this");
6443 
6444   case Type::STK_FixedPoint:
6445     switch (DestTy->getScalarTypeKind()) {
6446     case Type::STK_FixedPoint:
6447       return CK_FixedPointCast;
6448     case Type::STK_Bool:
6449       return CK_FixedPointToBoolean;
6450     case Type::STK_Integral:
6451       return CK_FixedPointToIntegral;
6452     case Type::STK_Floating:
6453     case Type::STK_IntegralComplex:
6454     case Type::STK_FloatingComplex:
6455       Diag(Src.get()->getExprLoc(),
6456            diag::err_unimplemented_conversion_with_fixed_point_type)
6457           << DestTy;
6458       return CK_IntegralCast;
6459     case Type::STK_CPointer:
6460     case Type::STK_ObjCObjectPointer:
6461     case Type::STK_BlockPointer:
6462     case Type::STK_MemberPointer:
6463       llvm_unreachable("illegal cast to pointer type");
6464     }
6465     llvm_unreachable("Should have returned before this");
6466 
6467   case Type::STK_Bool: // casting from bool is like casting from an integer
6468   case Type::STK_Integral:
6469     switch (DestTy->getScalarTypeKind()) {
6470     case Type::STK_CPointer:
6471     case Type::STK_ObjCObjectPointer:
6472     case Type::STK_BlockPointer:
6473       if (Src.get()->isNullPointerConstant(Context,
6474                                            Expr::NPC_ValueDependentIsNull))
6475         return CK_NullToPointer;
6476       return CK_IntegralToPointer;
6477     case Type::STK_Bool:
6478       return CK_IntegralToBoolean;
6479     case Type::STK_Integral:
6480       return CK_IntegralCast;
6481     case Type::STK_Floating:
6482       return CK_IntegralToFloating;
6483     case Type::STK_IntegralComplex:
6484       Src = ImpCastExprToType(Src.get(),
6485                       DestTy->castAs<ComplexType>()->getElementType(),
6486                       CK_IntegralCast);
6487       return CK_IntegralRealToComplex;
6488     case Type::STK_FloatingComplex:
6489       Src = ImpCastExprToType(Src.get(),
6490                       DestTy->castAs<ComplexType>()->getElementType(),
6491                       CK_IntegralToFloating);
6492       return CK_FloatingRealToComplex;
6493     case Type::STK_MemberPointer:
6494       llvm_unreachable("member pointer type in C");
6495     case Type::STK_FixedPoint:
6496       return CK_IntegralToFixedPoint;
6497     }
6498     llvm_unreachable("Should have returned before this");
6499 
6500   case Type::STK_Floating:
6501     switch (DestTy->getScalarTypeKind()) {
6502     case Type::STK_Floating:
6503       return CK_FloatingCast;
6504     case Type::STK_Bool:
6505       return CK_FloatingToBoolean;
6506     case Type::STK_Integral:
6507       return CK_FloatingToIntegral;
6508     case Type::STK_FloatingComplex:
6509       Src = ImpCastExprToType(Src.get(),
6510                               DestTy->castAs<ComplexType>()->getElementType(),
6511                               CK_FloatingCast);
6512       return CK_FloatingRealToComplex;
6513     case Type::STK_IntegralComplex:
6514       Src = ImpCastExprToType(Src.get(),
6515                               DestTy->castAs<ComplexType>()->getElementType(),
6516                               CK_FloatingToIntegral);
6517       return CK_IntegralRealToComplex;
6518     case Type::STK_CPointer:
6519     case Type::STK_ObjCObjectPointer:
6520     case Type::STK_BlockPointer:
6521       llvm_unreachable("valid float->pointer cast?");
6522     case Type::STK_MemberPointer:
6523       llvm_unreachable("member pointer type in C");
6524     case Type::STK_FixedPoint:
6525       Diag(Src.get()->getExprLoc(),
6526            diag::err_unimplemented_conversion_with_fixed_point_type)
6527           << SrcTy;
6528       return CK_IntegralCast;
6529     }
6530     llvm_unreachable("Should have returned before this");
6531 
6532   case Type::STK_FloatingComplex:
6533     switch (DestTy->getScalarTypeKind()) {
6534     case Type::STK_FloatingComplex:
6535       return CK_FloatingComplexCast;
6536     case Type::STK_IntegralComplex:
6537       return CK_FloatingComplexToIntegralComplex;
6538     case Type::STK_Floating: {
6539       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6540       if (Context.hasSameType(ET, DestTy))
6541         return CK_FloatingComplexToReal;
6542       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6543       return CK_FloatingCast;
6544     }
6545     case Type::STK_Bool:
6546       return CK_FloatingComplexToBoolean;
6547     case Type::STK_Integral:
6548       Src = ImpCastExprToType(Src.get(),
6549                               SrcTy->castAs<ComplexType>()->getElementType(),
6550                               CK_FloatingComplexToReal);
6551       return CK_FloatingToIntegral;
6552     case Type::STK_CPointer:
6553     case Type::STK_ObjCObjectPointer:
6554     case Type::STK_BlockPointer:
6555       llvm_unreachable("valid complex float->pointer cast?");
6556     case Type::STK_MemberPointer:
6557       llvm_unreachable("member pointer type in C");
6558     case Type::STK_FixedPoint:
6559       Diag(Src.get()->getExprLoc(),
6560            diag::err_unimplemented_conversion_with_fixed_point_type)
6561           << SrcTy;
6562       return CK_IntegralCast;
6563     }
6564     llvm_unreachable("Should have returned before this");
6565 
6566   case Type::STK_IntegralComplex:
6567     switch (DestTy->getScalarTypeKind()) {
6568     case Type::STK_FloatingComplex:
6569       return CK_IntegralComplexToFloatingComplex;
6570     case Type::STK_IntegralComplex:
6571       return CK_IntegralComplexCast;
6572     case Type::STK_Integral: {
6573       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6574       if (Context.hasSameType(ET, DestTy))
6575         return CK_IntegralComplexToReal;
6576       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6577       return CK_IntegralCast;
6578     }
6579     case Type::STK_Bool:
6580       return CK_IntegralComplexToBoolean;
6581     case Type::STK_Floating:
6582       Src = ImpCastExprToType(Src.get(),
6583                               SrcTy->castAs<ComplexType>()->getElementType(),
6584                               CK_IntegralComplexToReal);
6585       return CK_IntegralToFloating;
6586     case Type::STK_CPointer:
6587     case Type::STK_ObjCObjectPointer:
6588     case Type::STK_BlockPointer:
6589       llvm_unreachable("valid complex int->pointer cast?");
6590     case Type::STK_MemberPointer:
6591       llvm_unreachable("member pointer type in C");
6592     case Type::STK_FixedPoint:
6593       Diag(Src.get()->getExprLoc(),
6594            diag::err_unimplemented_conversion_with_fixed_point_type)
6595           << SrcTy;
6596       return CK_IntegralCast;
6597     }
6598     llvm_unreachable("Should have returned before this");
6599   }
6600 
6601   llvm_unreachable("Unhandled scalar cast");
6602 }
6603 
6604 static bool breakDownVectorType(QualType type, uint64_t &len,
6605                                 QualType &eltType) {
6606   // Vectors are simple.
6607   if (const VectorType *vecType = type->getAs<VectorType>()) {
6608     len = vecType->getNumElements();
6609     eltType = vecType->getElementType();
6610     assert(eltType->isScalarType());
6611     return true;
6612   }
6613 
6614   // We allow lax conversion to and from non-vector types, but only if
6615   // they're real types (i.e. non-complex, non-pointer scalar types).
6616   if (!type->isRealType()) return false;
6617 
6618   len = 1;
6619   eltType = type;
6620   return true;
6621 }
6622 
6623 /// Are the two types lax-compatible vector types?  That is, given
6624 /// that one of them is a vector, do they have equal storage sizes,
6625 /// where the storage size is the number of elements times the element
6626 /// size?
6627 ///
6628 /// This will also return false if either of the types is neither a
6629 /// vector nor a real type.
6630 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6631   assert(destTy->isVectorType() || srcTy->isVectorType());
6632 
6633   // Disallow lax conversions between scalars and ExtVectors (these
6634   // conversions are allowed for other vector types because common headers
6635   // depend on them).  Most scalar OP ExtVector cases are handled by the
6636   // splat path anyway, which does what we want (convert, not bitcast).
6637   // What this rules out for ExtVectors is crazy things like char4*float.
6638   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6639   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6640 
6641   uint64_t srcLen, destLen;
6642   QualType srcEltTy, destEltTy;
6643   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6644   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6645 
6646   // ASTContext::getTypeSize will return the size rounded up to a
6647   // power of 2, so instead of using that, we need to use the raw
6648   // element size multiplied by the element count.
6649   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6650   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6651 
6652   return (srcLen * srcEltSize == destLen * destEltSize);
6653 }
6654 
6655 /// Is this a legal conversion between two types, one of which is
6656 /// known to be a vector type?
6657 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6658   assert(destTy->isVectorType() || srcTy->isVectorType());
6659 
6660   switch (Context.getLangOpts().getLaxVectorConversions()) {
6661   case LangOptions::LaxVectorConversionKind::None:
6662     return false;
6663 
6664   case LangOptions::LaxVectorConversionKind::Integer:
6665     if (!srcTy->isIntegralOrEnumerationType()) {
6666       auto *Vec = srcTy->getAs<VectorType>();
6667       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6668         return false;
6669     }
6670     if (!destTy->isIntegralOrEnumerationType()) {
6671       auto *Vec = destTy->getAs<VectorType>();
6672       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6673         return false;
6674     }
6675     // OK, integer (vector) -> integer (vector) bitcast.
6676     break;
6677 
6678     case LangOptions::LaxVectorConversionKind::All:
6679     break;
6680   }
6681 
6682   return areLaxCompatibleVectorTypes(srcTy, destTy);
6683 }
6684 
6685 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6686                            CastKind &Kind) {
6687   assert(VectorTy->isVectorType() && "Not a vector type!");
6688 
6689   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6690     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6691       return Diag(R.getBegin(),
6692                   Ty->isVectorType() ?
6693                   diag::err_invalid_conversion_between_vectors :
6694                   diag::err_invalid_conversion_between_vector_and_integer)
6695         << VectorTy << Ty << R;
6696   } else
6697     return Diag(R.getBegin(),
6698                 diag::err_invalid_conversion_between_vector_and_scalar)
6699       << VectorTy << Ty << R;
6700 
6701   Kind = CK_BitCast;
6702   return false;
6703 }
6704 
6705 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6706   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6707 
6708   if (DestElemTy == SplattedExpr->getType())
6709     return SplattedExpr;
6710 
6711   assert(DestElemTy->isFloatingType() ||
6712          DestElemTy->isIntegralOrEnumerationType());
6713 
6714   CastKind CK;
6715   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6716     // OpenCL requires that we convert `true` boolean expressions to -1, but
6717     // only when splatting vectors.
6718     if (DestElemTy->isFloatingType()) {
6719       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6720       // in two steps: boolean to signed integral, then to floating.
6721       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6722                                                  CK_BooleanToSignedIntegral);
6723       SplattedExpr = CastExprRes.get();
6724       CK = CK_IntegralToFloating;
6725     } else {
6726       CK = CK_BooleanToSignedIntegral;
6727     }
6728   } else {
6729     ExprResult CastExprRes = SplattedExpr;
6730     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6731     if (CastExprRes.isInvalid())
6732       return ExprError();
6733     SplattedExpr = CastExprRes.get();
6734   }
6735   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6736 }
6737 
6738 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6739                                     Expr *CastExpr, CastKind &Kind) {
6740   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6741 
6742   QualType SrcTy = CastExpr->getType();
6743 
6744   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6745   // an ExtVectorType.
6746   // In OpenCL, casts between vectors of different types are not allowed.
6747   // (See OpenCL 6.2).
6748   if (SrcTy->isVectorType()) {
6749     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6750         (getLangOpts().OpenCL &&
6751          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6752       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6753         << DestTy << SrcTy << R;
6754       return ExprError();
6755     }
6756     Kind = CK_BitCast;
6757     return CastExpr;
6758   }
6759 
6760   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6761   // conversion will take place first from scalar to elt type, and then
6762   // splat from elt type to vector.
6763   if (SrcTy->isPointerType())
6764     return Diag(R.getBegin(),
6765                 diag::err_invalid_conversion_between_vector_and_scalar)
6766       << DestTy << SrcTy << R;
6767 
6768   Kind = CK_VectorSplat;
6769   return prepareVectorSplat(DestTy, CastExpr);
6770 }
6771 
6772 ExprResult
6773 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6774                     Declarator &D, ParsedType &Ty,
6775                     SourceLocation RParenLoc, Expr *CastExpr) {
6776   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6777          "ActOnCastExpr(): missing type or expr");
6778 
6779   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6780   if (D.isInvalidType())
6781     return ExprError();
6782 
6783   if (getLangOpts().CPlusPlus) {
6784     // Check that there are no default arguments (C++ only).
6785     CheckExtraCXXDefaultArguments(D);
6786   } else {
6787     // Make sure any TypoExprs have been dealt with.
6788     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6789     if (!Res.isUsable())
6790       return ExprError();
6791     CastExpr = Res.get();
6792   }
6793 
6794   checkUnusedDeclAttributes(D);
6795 
6796   QualType castType = castTInfo->getType();
6797   Ty = CreateParsedType(castType, castTInfo);
6798 
6799   bool isVectorLiteral = false;
6800 
6801   // Check for an altivec or OpenCL literal,
6802   // i.e. all the elements are integer constants.
6803   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6804   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6805   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6806        && castType->isVectorType() && (PE || PLE)) {
6807     if (PLE && PLE->getNumExprs() == 0) {
6808       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6809       return ExprError();
6810     }
6811     if (PE || PLE->getNumExprs() == 1) {
6812       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6813       if (!E->getType()->isVectorType())
6814         isVectorLiteral = true;
6815     }
6816     else
6817       isVectorLiteral = true;
6818   }
6819 
6820   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6821   // then handle it as such.
6822   if (isVectorLiteral)
6823     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6824 
6825   // If the Expr being casted is a ParenListExpr, handle it specially.
6826   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6827   // sequence of BinOp comma operators.
6828   if (isa<ParenListExpr>(CastExpr)) {
6829     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6830     if (Result.isInvalid()) return ExprError();
6831     CastExpr = Result.get();
6832   }
6833 
6834   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6835       !getSourceManager().isInSystemMacro(LParenLoc))
6836     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6837 
6838   CheckTollFreeBridgeCast(castType, CastExpr);
6839 
6840   CheckObjCBridgeRelatedCast(castType, CastExpr);
6841 
6842   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6843 
6844   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6845 }
6846 
6847 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6848                                     SourceLocation RParenLoc, Expr *E,
6849                                     TypeSourceInfo *TInfo) {
6850   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6851          "Expected paren or paren list expression");
6852 
6853   Expr **exprs;
6854   unsigned numExprs;
6855   Expr *subExpr;
6856   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6857   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6858     LiteralLParenLoc = PE->getLParenLoc();
6859     LiteralRParenLoc = PE->getRParenLoc();
6860     exprs = PE->getExprs();
6861     numExprs = PE->getNumExprs();
6862   } else { // isa<ParenExpr> by assertion at function entrance
6863     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6864     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6865     subExpr = cast<ParenExpr>(E)->getSubExpr();
6866     exprs = &subExpr;
6867     numExprs = 1;
6868   }
6869 
6870   QualType Ty = TInfo->getType();
6871   assert(Ty->isVectorType() && "Expected vector type");
6872 
6873   SmallVector<Expr *, 8> initExprs;
6874   const VectorType *VTy = Ty->castAs<VectorType>();
6875   unsigned numElems = VTy->getNumElements();
6876 
6877   // '(...)' form of vector initialization in AltiVec: the number of
6878   // initializers must be one or must match the size of the vector.
6879   // If a single value is specified in the initializer then it will be
6880   // replicated to all the components of the vector
6881   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6882     // The number of initializers must be one or must match the size of the
6883     // vector. If a single value is specified in the initializer then it will
6884     // be replicated to all the components of the vector
6885     if (numExprs == 1) {
6886       QualType ElemTy = VTy->getElementType();
6887       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6888       if (Literal.isInvalid())
6889         return ExprError();
6890       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6891                                   PrepareScalarCast(Literal, ElemTy));
6892       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6893     }
6894     else if (numExprs < numElems) {
6895       Diag(E->getExprLoc(),
6896            diag::err_incorrect_number_of_vector_initializers);
6897       return ExprError();
6898     }
6899     else
6900       initExprs.append(exprs, exprs + numExprs);
6901   }
6902   else {
6903     // For OpenCL, when the number of initializers is a single value,
6904     // it will be replicated to all components of the vector.
6905     if (getLangOpts().OpenCL &&
6906         VTy->getVectorKind() == VectorType::GenericVector &&
6907         numExprs == 1) {
6908         QualType ElemTy = VTy->getElementType();
6909         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6910         if (Literal.isInvalid())
6911           return ExprError();
6912         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6913                                     PrepareScalarCast(Literal, ElemTy));
6914         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6915     }
6916 
6917     initExprs.append(exprs, exprs + numExprs);
6918   }
6919   // FIXME: This means that pretty-printing the final AST will produce curly
6920   // braces instead of the original commas.
6921   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6922                                                    initExprs, LiteralRParenLoc);
6923   initE->setType(Ty);
6924   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6925 }
6926 
6927 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6928 /// the ParenListExpr into a sequence of comma binary operators.
6929 ExprResult
6930 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6931   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6932   if (!E)
6933     return OrigExpr;
6934 
6935   ExprResult Result(E->getExpr(0));
6936 
6937   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6938     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6939                         E->getExpr(i));
6940 
6941   if (Result.isInvalid()) return ExprError();
6942 
6943   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6944 }
6945 
6946 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6947                                     SourceLocation R,
6948                                     MultiExprArg Val) {
6949   return ParenListExpr::Create(Context, L, Val, R);
6950 }
6951 
6952 /// Emit a specialized diagnostic when one expression is a null pointer
6953 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6954 /// emitted.
6955 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6956                                       SourceLocation QuestionLoc) {
6957   Expr *NullExpr = LHSExpr;
6958   Expr *NonPointerExpr = RHSExpr;
6959   Expr::NullPointerConstantKind NullKind =
6960       NullExpr->isNullPointerConstant(Context,
6961                                       Expr::NPC_ValueDependentIsNotNull);
6962 
6963   if (NullKind == Expr::NPCK_NotNull) {
6964     NullExpr = RHSExpr;
6965     NonPointerExpr = LHSExpr;
6966     NullKind =
6967         NullExpr->isNullPointerConstant(Context,
6968                                         Expr::NPC_ValueDependentIsNotNull);
6969   }
6970 
6971   if (NullKind == Expr::NPCK_NotNull)
6972     return false;
6973 
6974   if (NullKind == Expr::NPCK_ZeroExpression)
6975     return false;
6976 
6977   if (NullKind == Expr::NPCK_ZeroLiteral) {
6978     // In this case, check to make sure that we got here from a "NULL"
6979     // string in the source code.
6980     NullExpr = NullExpr->IgnoreParenImpCasts();
6981     SourceLocation loc = NullExpr->getExprLoc();
6982     if (!findMacroSpelling(loc, "NULL"))
6983       return false;
6984   }
6985 
6986   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6987   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6988       << NonPointerExpr->getType() << DiagType
6989       << NonPointerExpr->getSourceRange();
6990   return true;
6991 }
6992 
6993 /// Return false if the condition expression is valid, true otherwise.
6994 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6995   QualType CondTy = Cond->getType();
6996 
6997   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6998   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6999     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7000       << CondTy << Cond->getSourceRange();
7001     return true;
7002   }
7003 
7004   // C99 6.5.15p2
7005   if (CondTy->isScalarType()) return false;
7006 
7007   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7008     << CondTy << Cond->getSourceRange();
7009   return true;
7010 }
7011 
7012 /// Handle when one or both operands are void type.
7013 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7014                                          ExprResult &RHS) {
7015     Expr *LHSExpr = LHS.get();
7016     Expr *RHSExpr = RHS.get();
7017 
7018     if (!LHSExpr->getType()->isVoidType())
7019       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7020           << RHSExpr->getSourceRange();
7021     if (!RHSExpr->getType()->isVoidType())
7022       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7023           << LHSExpr->getSourceRange();
7024     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7025     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7026     return S.Context.VoidTy;
7027 }
7028 
7029 /// Return false if the NullExpr can be promoted to PointerTy,
7030 /// true otherwise.
7031 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7032                                         QualType PointerTy) {
7033   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7034       !NullExpr.get()->isNullPointerConstant(S.Context,
7035                                             Expr::NPC_ValueDependentIsNull))
7036     return true;
7037 
7038   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7039   return false;
7040 }
7041 
7042 /// Checks compatibility between two pointers and return the resulting
7043 /// type.
7044 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7045                                                      ExprResult &RHS,
7046                                                      SourceLocation Loc) {
7047   QualType LHSTy = LHS.get()->getType();
7048   QualType RHSTy = RHS.get()->getType();
7049 
7050   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7051     // Two identical pointers types are always compatible.
7052     return LHSTy;
7053   }
7054 
7055   QualType lhptee, rhptee;
7056 
7057   // Get the pointee types.
7058   bool IsBlockPointer = false;
7059   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7060     lhptee = LHSBTy->getPointeeType();
7061     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7062     IsBlockPointer = true;
7063   } else {
7064     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7065     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7066   }
7067 
7068   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7069   // differently qualified versions of compatible types, the result type is
7070   // a pointer to an appropriately qualified version of the composite
7071   // type.
7072 
7073   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7074   // clause doesn't make sense for our extensions. E.g. address space 2 should
7075   // be incompatible with address space 3: they may live on different devices or
7076   // anything.
7077   Qualifiers lhQual = lhptee.getQualifiers();
7078   Qualifiers rhQual = rhptee.getQualifiers();
7079 
7080   LangAS ResultAddrSpace = LangAS::Default;
7081   LangAS LAddrSpace = lhQual.getAddressSpace();
7082   LangAS RAddrSpace = rhQual.getAddressSpace();
7083 
7084   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7085   // spaces is disallowed.
7086   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7087     ResultAddrSpace = LAddrSpace;
7088   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7089     ResultAddrSpace = RAddrSpace;
7090   else {
7091     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7092         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7093         << RHS.get()->getSourceRange();
7094     return QualType();
7095   }
7096 
7097   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7098   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7099   lhQual.removeCVRQualifiers();
7100   rhQual.removeCVRQualifiers();
7101 
7102   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7103   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7104   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7105   // qual types are compatible iff
7106   //  * corresponded types are compatible
7107   //  * CVR qualifiers are equal
7108   //  * address spaces are equal
7109   // Thus for conditional operator we merge CVR and address space unqualified
7110   // pointees and if there is a composite type we return a pointer to it with
7111   // merged qualifiers.
7112   LHSCastKind =
7113       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7114   RHSCastKind =
7115       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7116   lhQual.removeAddressSpace();
7117   rhQual.removeAddressSpace();
7118 
7119   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7120   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7121 
7122   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7123 
7124   if (CompositeTy.isNull()) {
7125     // In this situation, we assume void* type. No especially good
7126     // reason, but this is what gcc does, and we do have to pick
7127     // to get a consistent AST.
7128     QualType incompatTy;
7129     incompatTy = S.Context.getPointerType(
7130         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7131     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7132     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7133 
7134     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7135     // for casts between types with incompatible address space qualifiers.
7136     // For the following code the compiler produces casts between global and
7137     // local address spaces of the corresponded innermost pointees:
7138     // local int *global *a;
7139     // global int *global *b;
7140     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7141     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7142         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7143         << RHS.get()->getSourceRange();
7144 
7145     return incompatTy;
7146   }
7147 
7148   // The pointer types are compatible.
7149   // In case of OpenCL ResultTy should have the address space qualifier
7150   // which is a superset of address spaces of both the 2nd and the 3rd
7151   // operands of the conditional operator.
7152   QualType ResultTy = [&, ResultAddrSpace]() {
7153     if (S.getLangOpts().OpenCL) {
7154       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7155       CompositeQuals.setAddressSpace(ResultAddrSpace);
7156       return S.Context
7157           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7158           .withCVRQualifiers(MergedCVRQual);
7159     }
7160     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7161   }();
7162   if (IsBlockPointer)
7163     ResultTy = S.Context.getBlockPointerType(ResultTy);
7164   else
7165     ResultTy = S.Context.getPointerType(ResultTy);
7166 
7167   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7168   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7169   return ResultTy;
7170 }
7171 
7172 /// Return the resulting type when the operands are both block pointers.
7173 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7174                                                           ExprResult &LHS,
7175                                                           ExprResult &RHS,
7176                                                           SourceLocation Loc) {
7177   QualType LHSTy = LHS.get()->getType();
7178   QualType RHSTy = RHS.get()->getType();
7179 
7180   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7181     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7182       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7183       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7184       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7185       return destType;
7186     }
7187     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7188       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7189       << RHS.get()->getSourceRange();
7190     return QualType();
7191   }
7192 
7193   // We have 2 block pointer types.
7194   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7195 }
7196 
7197 /// Return the resulting type when the operands are both pointers.
7198 static QualType
7199 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7200                                             ExprResult &RHS,
7201                                             SourceLocation Loc) {
7202   // get the pointer types
7203   QualType LHSTy = LHS.get()->getType();
7204   QualType RHSTy = RHS.get()->getType();
7205 
7206   // get the "pointed to" types
7207   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7208   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7209 
7210   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7211   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7212     // Figure out necessary qualifiers (C99 6.5.15p6)
7213     QualType destPointee
7214       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7215     QualType destType = S.Context.getPointerType(destPointee);
7216     // Add qualifiers if necessary.
7217     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7218     // Promote to void*.
7219     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7220     return destType;
7221   }
7222   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7223     QualType destPointee
7224       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7225     QualType destType = S.Context.getPointerType(destPointee);
7226     // Add qualifiers if necessary.
7227     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7228     // Promote to void*.
7229     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7230     return destType;
7231   }
7232 
7233   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7234 }
7235 
7236 /// Return false if the first expression is not an integer and the second
7237 /// expression is not a pointer, true otherwise.
7238 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7239                                         Expr* PointerExpr, SourceLocation Loc,
7240                                         bool IsIntFirstExpr) {
7241   if (!PointerExpr->getType()->isPointerType() ||
7242       !Int.get()->getType()->isIntegerType())
7243     return false;
7244 
7245   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7246   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7247 
7248   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7249     << Expr1->getType() << Expr2->getType()
7250     << Expr1->getSourceRange() << Expr2->getSourceRange();
7251   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7252                             CK_IntegralToPointer);
7253   return true;
7254 }
7255 
7256 /// Simple conversion between integer and floating point types.
7257 ///
7258 /// Used when handling the OpenCL conditional operator where the
7259 /// condition is a vector while the other operands are scalar.
7260 ///
7261 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7262 /// types are either integer or floating type. Between the two
7263 /// operands, the type with the higher rank is defined as the "result
7264 /// type". The other operand needs to be promoted to the same type. No
7265 /// other type promotion is allowed. We cannot use
7266 /// UsualArithmeticConversions() for this purpose, since it always
7267 /// promotes promotable types.
7268 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7269                                             ExprResult &RHS,
7270                                             SourceLocation QuestionLoc) {
7271   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7272   if (LHS.isInvalid())
7273     return QualType();
7274   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7275   if (RHS.isInvalid())
7276     return QualType();
7277 
7278   // For conversion purposes, we ignore any qualifiers.
7279   // For example, "const float" and "float" are equivalent.
7280   QualType LHSType =
7281     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7282   QualType RHSType =
7283     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7284 
7285   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7286     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7287       << LHSType << LHS.get()->getSourceRange();
7288     return QualType();
7289   }
7290 
7291   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7292     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7293       << RHSType << RHS.get()->getSourceRange();
7294     return QualType();
7295   }
7296 
7297   // If both types are identical, no conversion is needed.
7298   if (LHSType == RHSType)
7299     return LHSType;
7300 
7301   // Now handle "real" floating types (i.e. float, double, long double).
7302   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7303     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7304                                  /*IsCompAssign = */ false);
7305 
7306   // Finally, we have two differing integer types.
7307   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7308   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7309 }
7310 
7311 /// Convert scalar operands to a vector that matches the
7312 ///        condition in length.
7313 ///
7314 /// Used when handling the OpenCL conditional operator where the
7315 /// condition is a vector while the other operands are scalar.
7316 ///
7317 /// We first compute the "result type" for the scalar operands
7318 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7319 /// into a vector of that type where the length matches the condition
7320 /// vector type. s6.11.6 requires that the element types of the result
7321 /// and the condition must have the same number of bits.
7322 static QualType
7323 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7324                               QualType CondTy, SourceLocation QuestionLoc) {
7325   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7326   if (ResTy.isNull()) return QualType();
7327 
7328   const VectorType *CV = CondTy->getAs<VectorType>();
7329   assert(CV);
7330 
7331   // Determine the vector result type
7332   unsigned NumElements = CV->getNumElements();
7333   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7334 
7335   // Ensure that all types have the same number of bits
7336   if (S.Context.getTypeSize(CV->getElementType())
7337       != S.Context.getTypeSize(ResTy)) {
7338     // Since VectorTy is created internally, it does not pretty print
7339     // with an OpenCL name. Instead, we just print a description.
7340     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7341     SmallString<64> Str;
7342     llvm::raw_svector_ostream OS(Str);
7343     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7344     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7345       << CondTy << OS.str();
7346     return QualType();
7347   }
7348 
7349   // Convert operands to the vector result type
7350   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7351   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7352 
7353   return VectorTy;
7354 }
7355 
7356 /// Return false if this is a valid OpenCL condition vector
7357 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7358                                        SourceLocation QuestionLoc) {
7359   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7360   // integral type.
7361   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7362   assert(CondTy);
7363   QualType EleTy = CondTy->getElementType();
7364   if (EleTy->isIntegerType()) return false;
7365 
7366   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7367     << Cond->getType() << Cond->getSourceRange();
7368   return true;
7369 }
7370 
7371 /// Return false if the vector condition type and the vector
7372 ///        result type are compatible.
7373 ///
7374 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7375 /// number of elements, and their element types have the same number
7376 /// of bits.
7377 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7378                               SourceLocation QuestionLoc) {
7379   const VectorType *CV = CondTy->getAs<VectorType>();
7380   const VectorType *RV = VecResTy->getAs<VectorType>();
7381   assert(CV && RV);
7382 
7383   if (CV->getNumElements() != RV->getNumElements()) {
7384     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7385       << CondTy << VecResTy;
7386     return true;
7387   }
7388 
7389   QualType CVE = CV->getElementType();
7390   QualType RVE = RV->getElementType();
7391 
7392   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7393     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7394       << CondTy << VecResTy;
7395     return true;
7396   }
7397 
7398   return false;
7399 }
7400 
7401 /// Return the resulting type for the conditional operator in
7402 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7403 ///        s6.3.i) when the condition is a vector type.
7404 static QualType
7405 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7406                              ExprResult &LHS, ExprResult &RHS,
7407                              SourceLocation QuestionLoc) {
7408   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7409   if (Cond.isInvalid())
7410     return QualType();
7411   QualType CondTy = Cond.get()->getType();
7412 
7413   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7414     return QualType();
7415 
7416   // If either operand is a vector then find the vector type of the
7417   // result as specified in OpenCL v1.1 s6.3.i.
7418   if (LHS.get()->getType()->isVectorType() ||
7419       RHS.get()->getType()->isVectorType()) {
7420     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7421                                               /*isCompAssign*/false,
7422                                               /*AllowBothBool*/true,
7423                                               /*AllowBoolConversions*/false);
7424     if (VecResTy.isNull()) return QualType();
7425     // The result type must match the condition type as specified in
7426     // OpenCL v1.1 s6.11.6.
7427     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7428       return QualType();
7429     return VecResTy;
7430   }
7431 
7432   // Both operands are scalar.
7433   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7434 }
7435 
7436 /// Return true if the Expr is block type
7437 static bool checkBlockType(Sema &S, const Expr *E) {
7438   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7439     QualType Ty = CE->getCallee()->getType();
7440     if (Ty->isBlockPointerType()) {
7441       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7442       return true;
7443     }
7444   }
7445   return false;
7446 }
7447 
7448 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7449 /// In that case, LHS = cond.
7450 /// C99 6.5.15
7451 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7452                                         ExprResult &RHS, ExprValueKind &VK,
7453                                         ExprObjectKind &OK,
7454                                         SourceLocation QuestionLoc) {
7455 
7456   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7457   if (!LHSResult.isUsable()) return QualType();
7458   LHS = LHSResult;
7459 
7460   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7461   if (!RHSResult.isUsable()) return QualType();
7462   RHS = RHSResult;
7463 
7464   // C++ is sufficiently different to merit its own checker.
7465   if (getLangOpts().CPlusPlus)
7466     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7467 
7468   VK = VK_RValue;
7469   OK = OK_Ordinary;
7470 
7471   // The OpenCL operator with a vector condition is sufficiently
7472   // different to merit its own checker.
7473   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7474     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7475 
7476   // First, check the condition.
7477   Cond = UsualUnaryConversions(Cond.get());
7478   if (Cond.isInvalid())
7479     return QualType();
7480   if (checkCondition(*this, Cond.get(), QuestionLoc))
7481     return QualType();
7482 
7483   // Now check the two expressions.
7484   if (LHS.get()->getType()->isVectorType() ||
7485       RHS.get()->getType()->isVectorType())
7486     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7487                                /*AllowBothBool*/true,
7488                                /*AllowBoolConversions*/false);
7489 
7490   QualType ResTy =
7491       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7492   if (LHS.isInvalid() || RHS.isInvalid())
7493     return QualType();
7494 
7495   QualType LHSTy = LHS.get()->getType();
7496   QualType RHSTy = RHS.get()->getType();
7497 
7498   // Diagnose attempts to convert between __float128 and long double where
7499   // such conversions currently can't be handled.
7500   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7501     Diag(QuestionLoc,
7502          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7503       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7504     return QualType();
7505   }
7506 
7507   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7508   // selection operator (?:).
7509   if (getLangOpts().OpenCL &&
7510       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7511     return QualType();
7512   }
7513 
7514   // If both operands have arithmetic type, do the usual arithmetic conversions
7515   // to find a common type: C99 6.5.15p3,5.
7516   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7517     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7518     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7519 
7520     return ResTy;
7521   }
7522 
7523   // If both operands are the same structure or union type, the result is that
7524   // type.
7525   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7526     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7527       if (LHSRT->getDecl() == RHSRT->getDecl())
7528         // "If both the operands have structure or union type, the result has
7529         // that type."  This implies that CV qualifiers are dropped.
7530         return LHSTy.getUnqualifiedType();
7531     // FIXME: Type of conditional expression must be complete in C mode.
7532   }
7533 
7534   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7535   // The following || allows only one side to be void (a GCC-ism).
7536   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7537     return checkConditionalVoidType(*this, LHS, RHS);
7538   }
7539 
7540   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7541   // the type of the other operand."
7542   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7543   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7544 
7545   // All objective-c pointer type analysis is done here.
7546   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7547                                                         QuestionLoc);
7548   if (LHS.isInvalid() || RHS.isInvalid())
7549     return QualType();
7550   if (!compositeType.isNull())
7551     return compositeType;
7552 
7553 
7554   // Handle block pointer types.
7555   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7556     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7557                                                      QuestionLoc);
7558 
7559   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7560   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7561     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7562                                                        QuestionLoc);
7563 
7564   // GCC compatibility: soften pointer/integer mismatch.  Note that
7565   // null pointers have been filtered out by this point.
7566   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7567       /*IsIntFirstExpr=*/true))
7568     return RHSTy;
7569   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7570       /*IsIntFirstExpr=*/false))
7571     return LHSTy;
7572 
7573   // Emit a better diagnostic if one of the expressions is a null pointer
7574   // constant and the other is not a pointer type. In this case, the user most
7575   // likely forgot to take the address of the other expression.
7576   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7577     return QualType();
7578 
7579   // Otherwise, the operands are not compatible.
7580   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7581     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7582     << RHS.get()->getSourceRange();
7583   return QualType();
7584 }
7585 
7586 /// FindCompositeObjCPointerType - Helper method to find composite type of
7587 /// two objective-c pointer types of the two input expressions.
7588 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7589                                             SourceLocation QuestionLoc) {
7590   QualType LHSTy = LHS.get()->getType();
7591   QualType RHSTy = RHS.get()->getType();
7592 
7593   // Handle things like Class and struct objc_class*.  Here we case the result
7594   // to the pseudo-builtin, because that will be implicitly cast back to the
7595   // redefinition type if an attempt is made to access its fields.
7596   if (LHSTy->isObjCClassType() &&
7597       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7598     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7599     return LHSTy;
7600   }
7601   if (RHSTy->isObjCClassType() &&
7602       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7603     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7604     return RHSTy;
7605   }
7606   // And the same for struct objc_object* / id
7607   if (LHSTy->isObjCIdType() &&
7608       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7609     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7610     return LHSTy;
7611   }
7612   if (RHSTy->isObjCIdType() &&
7613       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7614     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7615     return RHSTy;
7616   }
7617   // And the same for struct objc_selector* / SEL
7618   if (Context.isObjCSelType(LHSTy) &&
7619       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7620     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7621     return LHSTy;
7622   }
7623   if (Context.isObjCSelType(RHSTy) &&
7624       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7625     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7626     return RHSTy;
7627   }
7628   // Check constraints for Objective-C object pointers types.
7629   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7630 
7631     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7632       // Two identical object pointer types are always compatible.
7633       return LHSTy;
7634     }
7635     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7636     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7637     QualType compositeType = LHSTy;
7638 
7639     // If both operands are interfaces and either operand can be
7640     // assigned to the other, use that type as the composite
7641     // type. This allows
7642     //   xxx ? (A*) a : (B*) b
7643     // where B is a subclass of A.
7644     //
7645     // Additionally, as for assignment, if either type is 'id'
7646     // allow silent coercion. Finally, if the types are
7647     // incompatible then make sure to use 'id' as the composite
7648     // type so the result is acceptable for sending messages to.
7649 
7650     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7651     // It could return the composite type.
7652     if (!(compositeType =
7653           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7654       // Nothing more to do.
7655     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7656       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7657     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7658       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7659     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7660                 RHSOPT->isObjCQualifiedIdType()) &&
7661                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7662                                                          true)) {
7663       // Need to handle "id<xx>" explicitly.
7664       // GCC allows qualified id and any Objective-C type to devolve to
7665       // id. Currently localizing to here until clear this should be
7666       // part of ObjCQualifiedIdTypesAreCompatible.
7667       compositeType = Context.getObjCIdType();
7668     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7669       compositeType = Context.getObjCIdType();
7670     } else {
7671       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7672       << LHSTy << RHSTy
7673       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7674       QualType incompatTy = Context.getObjCIdType();
7675       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7676       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7677       return incompatTy;
7678     }
7679     // The object pointer types are compatible.
7680     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7681     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7682     return compositeType;
7683   }
7684   // Check Objective-C object pointer types and 'void *'
7685   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7686     if (getLangOpts().ObjCAutoRefCount) {
7687       // ARC forbids the implicit conversion of object pointers to 'void *',
7688       // so these types are not compatible.
7689       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7690           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7691       LHS = RHS = true;
7692       return QualType();
7693     }
7694     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7695     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7696     QualType destPointee
7697     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7698     QualType destType = Context.getPointerType(destPointee);
7699     // Add qualifiers if necessary.
7700     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7701     // Promote to void*.
7702     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7703     return destType;
7704   }
7705   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7706     if (getLangOpts().ObjCAutoRefCount) {
7707       // ARC forbids the implicit conversion of object pointers to 'void *',
7708       // so these types are not compatible.
7709       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7710           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7711       LHS = RHS = true;
7712       return QualType();
7713     }
7714     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7715     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7716     QualType destPointee
7717     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7718     QualType destType = Context.getPointerType(destPointee);
7719     // Add qualifiers if necessary.
7720     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7721     // Promote to void*.
7722     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7723     return destType;
7724   }
7725   return QualType();
7726 }
7727 
7728 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7729 /// ParenRange in parentheses.
7730 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7731                                const PartialDiagnostic &Note,
7732                                SourceRange ParenRange) {
7733   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7734   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7735       EndLoc.isValid()) {
7736     Self.Diag(Loc, Note)
7737       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7738       << FixItHint::CreateInsertion(EndLoc, ")");
7739   } else {
7740     // We can't display the parentheses, so just show the bare note.
7741     Self.Diag(Loc, Note) << ParenRange;
7742   }
7743 }
7744 
7745 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7746   return BinaryOperator::isAdditiveOp(Opc) ||
7747          BinaryOperator::isMultiplicativeOp(Opc) ||
7748          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7749   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7750   // not any of the logical operators.  Bitwise-xor is commonly used as a
7751   // logical-xor because there is no logical-xor operator.  The logical
7752   // operators, including uses of xor, have a high false positive rate for
7753   // precedence warnings.
7754 }
7755 
7756 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7757 /// expression, either using a built-in or overloaded operator,
7758 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7759 /// expression.
7760 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7761                                    Expr **RHSExprs) {
7762   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7763   E = E->IgnoreImpCasts();
7764   E = E->IgnoreConversionOperator();
7765   E = E->IgnoreImpCasts();
7766   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7767     E = MTE->getSubExpr();
7768     E = E->IgnoreImpCasts();
7769   }
7770 
7771   // Built-in binary operator.
7772   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7773     if (IsArithmeticOp(OP->getOpcode())) {
7774       *Opcode = OP->getOpcode();
7775       *RHSExprs = OP->getRHS();
7776       return true;
7777     }
7778   }
7779 
7780   // Overloaded operator.
7781   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7782     if (Call->getNumArgs() != 2)
7783       return false;
7784 
7785     // Make sure this is really a binary operator that is safe to pass into
7786     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7787     OverloadedOperatorKind OO = Call->getOperator();
7788     if (OO < OO_Plus || OO > OO_Arrow ||
7789         OO == OO_PlusPlus || OO == OO_MinusMinus)
7790       return false;
7791 
7792     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7793     if (IsArithmeticOp(OpKind)) {
7794       *Opcode = OpKind;
7795       *RHSExprs = Call->getArg(1);
7796       return true;
7797     }
7798   }
7799 
7800   return false;
7801 }
7802 
7803 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7804 /// or is a logical expression such as (x==y) which has int type, but is
7805 /// commonly interpreted as boolean.
7806 static bool ExprLooksBoolean(Expr *E) {
7807   E = E->IgnoreParenImpCasts();
7808 
7809   if (E->getType()->isBooleanType())
7810     return true;
7811   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7812     return OP->isComparisonOp() || OP->isLogicalOp();
7813   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7814     return OP->getOpcode() == UO_LNot;
7815   if (E->getType()->isPointerType())
7816     return true;
7817   // FIXME: What about overloaded operator calls returning "unspecified boolean
7818   // type"s (commonly pointer-to-members)?
7819 
7820   return false;
7821 }
7822 
7823 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7824 /// and binary operator are mixed in a way that suggests the programmer assumed
7825 /// the conditional operator has higher precedence, for example:
7826 /// "int x = a + someBinaryCondition ? 1 : 2".
7827 static void DiagnoseConditionalPrecedence(Sema &Self,
7828                                           SourceLocation OpLoc,
7829                                           Expr *Condition,
7830                                           Expr *LHSExpr,
7831                                           Expr *RHSExpr) {
7832   BinaryOperatorKind CondOpcode;
7833   Expr *CondRHS;
7834 
7835   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7836     return;
7837   if (!ExprLooksBoolean(CondRHS))
7838     return;
7839 
7840   // The condition is an arithmetic binary expression, with a right-
7841   // hand side that looks boolean, so warn.
7842 
7843   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7844                         ? diag::warn_precedence_bitwise_conditional
7845                         : diag::warn_precedence_conditional;
7846 
7847   Self.Diag(OpLoc, DiagID)
7848       << Condition->getSourceRange()
7849       << BinaryOperator::getOpcodeStr(CondOpcode);
7850 
7851   SuggestParentheses(
7852       Self, OpLoc,
7853       Self.PDiag(diag::note_precedence_silence)
7854           << BinaryOperator::getOpcodeStr(CondOpcode),
7855       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7856 
7857   SuggestParentheses(Self, OpLoc,
7858                      Self.PDiag(diag::note_precedence_conditional_first),
7859                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7860 }
7861 
7862 /// Compute the nullability of a conditional expression.
7863 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7864                                               QualType LHSTy, QualType RHSTy,
7865                                               ASTContext &Ctx) {
7866   if (!ResTy->isAnyPointerType())
7867     return ResTy;
7868 
7869   auto GetNullability = [&Ctx](QualType Ty) {
7870     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7871     if (Kind)
7872       return *Kind;
7873     return NullabilityKind::Unspecified;
7874   };
7875 
7876   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7877   NullabilityKind MergedKind;
7878 
7879   // Compute nullability of a binary conditional expression.
7880   if (IsBin) {
7881     if (LHSKind == NullabilityKind::NonNull)
7882       MergedKind = NullabilityKind::NonNull;
7883     else
7884       MergedKind = RHSKind;
7885   // Compute nullability of a normal conditional expression.
7886   } else {
7887     if (LHSKind == NullabilityKind::Nullable ||
7888         RHSKind == NullabilityKind::Nullable)
7889       MergedKind = NullabilityKind::Nullable;
7890     else if (LHSKind == NullabilityKind::NonNull)
7891       MergedKind = RHSKind;
7892     else if (RHSKind == NullabilityKind::NonNull)
7893       MergedKind = LHSKind;
7894     else
7895       MergedKind = NullabilityKind::Unspecified;
7896   }
7897 
7898   // Return if ResTy already has the correct nullability.
7899   if (GetNullability(ResTy) == MergedKind)
7900     return ResTy;
7901 
7902   // Strip all nullability from ResTy.
7903   while (ResTy->getNullability(Ctx))
7904     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7905 
7906   // Create a new AttributedType with the new nullability kind.
7907   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7908   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7909 }
7910 
7911 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7912 /// in the case of a the GNU conditional expr extension.
7913 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7914                                     SourceLocation ColonLoc,
7915                                     Expr *CondExpr, Expr *LHSExpr,
7916                                     Expr *RHSExpr) {
7917   if (!getLangOpts().CPlusPlus) {
7918     // C cannot handle TypoExpr nodes in the condition because it
7919     // doesn't handle dependent types properly, so make sure any TypoExprs have
7920     // been dealt with before checking the operands.
7921     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7922     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7923     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7924 
7925     if (!CondResult.isUsable())
7926       return ExprError();
7927 
7928     if (LHSExpr) {
7929       if (!LHSResult.isUsable())
7930         return ExprError();
7931     }
7932 
7933     if (!RHSResult.isUsable())
7934       return ExprError();
7935 
7936     CondExpr = CondResult.get();
7937     LHSExpr = LHSResult.get();
7938     RHSExpr = RHSResult.get();
7939   }
7940 
7941   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7942   // was the condition.
7943   OpaqueValueExpr *opaqueValue = nullptr;
7944   Expr *commonExpr = nullptr;
7945   if (!LHSExpr) {
7946     commonExpr = CondExpr;
7947     // Lower out placeholder types first.  This is important so that we don't
7948     // try to capture a placeholder. This happens in few cases in C++; such
7949     // as Objective-C++'s dictionary subscripting syntax.
7950     if (commonExpr->hasPlaceholderType()) {
7951       ExprResult result = CheckPlaceholderExpr(commonExpr);
7952       if (!result.isUsable()) return ExprError();
7953       commonExpr = result.get();
7954     }
7955     // We usually want to apply unary conversions *before* saving, except
7956     // in the special case of a C++ l-value conditional.
7957     if (!(getLangOpts().CPlusPlus
7958           && !commonExpr->isTypeDependent()
7959           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7960           && commonExpr->isGLValue()
7961           && commonExpr->isOrdinaryOrBitFieldObject()
7962           && RHSExpr->isOrdinaryOrBitFieldObject()
7963           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7964       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7965       if (commonRes.isInvalid())
7966         return ExprError();
7967       commonExpr = commonRes.get();
7968     }
7969 
7970     // If the common expression is a class or array prvalue, materialize it
7971     // so that we can safely refer to it multiple times.
7972     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7973                                    commonExpr->getType()->isArrayType())) {
7974       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7975       if (MatExpr.isInvalid())
7976         return ExprError();
7977       commonExpr = MatExpr.get();
7978     }
7979 
7980     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7981                                                 commonExpr->getType(),
7982                                                 commonExpr->getValueKind(),
7983                                                 commonExpr->getObjectKind(),
7984                                                 commonExpr);
7985     LHSExpr = CondExpr = opaqueValue;
7986   }
7987 
7988   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7989   ExprValueKind VK = VK_RValue;
7990   ExprObjectKind OK = OK_Ordinary;
7991   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7992   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7993                                              VK, OK, QuestionLoc);
7994   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7995       RHS.isInvalid())
7996     return ExprError();
7997 
7998   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7999                                 RHS.get());
8000 
8001   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8002 
8003   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8004                                          Context);
8005 
8006   if (!commonExpr)
8007     return new (Context)
8008         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8009                             RHS.get(), result, VK, OK);
8010 
8011   return new (Context) BinaryConditionalOperator(
8012       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8013       ColonLoc, result, VK, OK);
8014 }
8015 
8016 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8017 // being closely modeled after the C99 spec:-). The odd characteristic of this
8018 // routine is it effectively iqnores the qualifiers on the top level pointee.
8019 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8020 // FIXME: add a couple examples in this comment.
8021 static Sema::AssignConvertType
8022 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8023   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8024   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8025 
8026   // get the "pointed to" type (ignoring qualifiers at the top level)
8027   const Type *lhptee, *rhptee;
8028   Qualifiers lhq, rhq;
8029   std::tie(lhptee, lhq) =
8030       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8031   std::tie(rhptee, rhq) =
8032       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8033 
8034   Sema::AssignConvertType ConvTy = Sema::Compatible;
8035 
8036   // C99 6.5.16.1p1: This following citation is common to constraints
8037   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8038   // qualifiers of the type *pointed to* by the right;
8039 
8040   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8041   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8042       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8043     // Ignore lifetime for further calculation.
8044     lhq.removeObjCLifetime();
8045     rhq.removeObjCLifetime();
8046   }
8047 
8048   if (!lhq.compatiblyIncludes(rhq)) {
8049     // Treat address-space mismatches as fatal.
8050     if (!lhq.isAddressSpaceSupersetOf(rhq))
8051       return Sema::IncompatiblePointerDiscardsQualifiers;
8052 
8053     // It's okay to add or remove GC or lifetime qualifiers when converting to
8054     // and from void*.
8055     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8056                         .compatiblyIncludes(
8057                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8058              && (lhptee->isVoidType() || rhptee->isVoidType()))
8059       ; // keep old
8060 
8061     // Treat lifetime mismatches as fatal.
8062     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8063       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8064 
8065     // For GCC/MS compatibility, other qualifier mismatches are treated
8066     // as still compatible in C.
8067     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8068   }
8069 
8070   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8071   // incomplete type and the other is a pointer to a qualified or unqualified
8072   // version of void...
8073   if (lhptee->isVoidType()) {
8074     if (rhptee->isIncompleteOrObjectType())
8075       return ConvTy;
8076 
8077     // As an extension, we allow cast to/from void* to function pointer.
8078     assert(rhptee->isFunctionType());
8079     return Sema::FunctionVoidPointer;
8080   }
8081 
8082   if (rhptee->isVoidType()) {
8083     if (lhptee->isIncompleteOrObjectType())
8084       return ConvTy;
8085 
8086     // As an extension, we allow cast to/from void* to function pointer.
8087     assert(lhptee->isFunctionType());
8088     return Sema::FunctionVoidPointer;
8089   }
8090 
8091   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8092   // unqualified versions of compatible types, ...
8093   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8094   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8095     // Check if the pointee types are compatible ignoring the sign.
8096     // We explicitly check for char so that we catch "char" vs
8097     // "unsigned char" on systems where "char" is unsigned.
8098     if (lhptee->isCharType())
8099       ltrans = S.Context.UnsignedCharTy;
8100     else if (lhptee->hasSignedIntegerRepresentation())
8101       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8102 
8103     if (rhptee->isCharType())
8104       rtrans = S.Context.UnsignedCharTy;
8105     else if (rhptee->hasSignedIntegerRepresentation())
8106       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8107 
8108     if (ltrans == rtrans) {
8109       // Types are compatible ignoring the sign. Qualifier incompatibility
8110       // takes priority over sign incompatibility because the sign
8111       // warning can be disabled.
8112       if (ConvTy != Sema::Compatible)
8113         return ConvTy;
8114 
8115       return Sema::IncompatiblePointerSign;
8116     }
8117 
8118     // If we are a multi-level pointer, it's possible that our issue is simply
8119     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8120     // the eventual target type is the same and the pointers have the same
8121     // level of indirection, this must be the issue.
8122     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8123       do {
8124         std::tie(lhptee, lhq) =
8125           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8126         std::tie(rhptee, rhq) =
8127           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8128 
8129         // Inconsistent address spaces at this point is invalid, even if the
8130         // address spaces would be compatible.
8131         // FIXME: This doesn't catch address space mismatches for pointers of
8132         // different nesting levels, like:
8133         //   __local int *** a;
8134         //   int ** b = a;
8135         // It's not clear how to actually determine when such pointers are
8136         // invalidly incompatible.
8137         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8138           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8139 
8140       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8141 
8142       if (lhptee == rhptee)
8143         return Sema::IncompatibleNestedPointerQualifiers;
8144     }
8145 
8146     // General pointer incompatibility takes priority over qualifiers.
8147     return Sema::IncompatiblePointer;
8148   }
8149   if (!S.getLangOpts().CPlusPlus &&
8150       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8151     return Sema::IncompatiblePointer;
8152   return ConvTy;
8153 }
8154 
8155 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8156 /// block pointer types are compatible or whether a block and normal pointer
8157 /// are compatible. It is more restrict than comparing two function pointer
8158 // types.
8159 static Sema::AssignConvertType
8160 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8161                                     QualType RHSType) {
8162   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8163   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8164 
8165   QualType lhptee, rhptee;
8166 
8167   // get the "pointed to" type (ignoring qualifiers at the top level)
8168   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8169   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8170 
8171   // In C++, the types have to match exactly.
8172   if (S.getLangOpts().CPlusPlus)
8173     return Sema::IncompatibleBlockPointer;
8174 
8175   Sema::AssignConvertType ConvTy = Sema::Compatible;
8176 
8177   // For blocks we enforce that qualifiers are identical.
8178   Qualifiers LQuals = lhptee.getLocalQualifiers();
8179   Qualifiers RQuals = rhptee.getLocalQualifiers();
8180   if (S.getLangOpts().OpenCL) {
8181     LQuals.removeAddressSpace();
8182     RQuals.removeAddressSpace();
8183   }
8184   if (LQuals != RQuals)
8185     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8186 
8187   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8188   // assignment.
8189   // The current behavior is similar to C++ lambdas. A block might be
8190   // assigned to a variable iff its return type and parameters are compatible
8191   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8192   // an assignment. Presumably it should behave in way that a function pointer
8193   // assignment does in C, so for each parameter and return type:
8194   //  * CVR and address space of LHS should be a superset of CVR and address
8195   //  space of RHS.
8196   //  * unqualified types should be compatible.
8197   if (S.getLangOpts().OpenCL) {
8198     if (!S.Context.typesAreBlockPointerCompatible(
8199             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8200             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8201       return Sema::IncompatibleBlockPointer;
8202   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8203     return Sema::IncompatibleBlockPointer;
8204 
8205   return ConvTy;
8206 }
8207 
8208 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8209 /// for assignment compatibility.
8210 static Sema::AssignConvertType
8211 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8212                                    QualType RHSType) {
8213   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8214   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8215 
8216   if (LHSType->isObjCBuiltinType()) {
8217     // Class is not compatible with ObjC object pointers.
8218     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8219         !RHSType->isObjCQualifiedClassType())
8220       return Sema::IncompatiblePointer;
8221     return Sema::Compatible;
8222   }
8223   if (RHSType->isObjCBuiltinType()) {
8224     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8225         !LHSType->isObjCQualifiedClassType())
8226       return Sema::IncompatiblePointer;
8227     return Sema::Compatible;
8228   }
8229   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8230   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8231 
8232   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8233       // make an exception for id<P>
8234       !LHSType->isObjCQualifiedIdType())
8235     return Sema::CompatiblePointerDiscardsQualifiers;
8236 
8237   if (S.Context.typesAreCompatible(LHSType, RHSType))
8238     return Sema::Compatible;
8239   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8240     return Sema::IncompatibleObjCQualifiedId;
8241   return Sema::IncompatiblePointer;
8242 }
8243 
8244 Sema::AssignConvertType
8245 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8246                                  QualType LHSType, QualType RHSType) {
8247   // Fake up an opaque expression.  We don't actually care about what
8248   // cast operations are required, so if CheckAssignmentConstraints
8249   // adds casts to this they'll be wasted, but fortunately that doesn't
8250   // usually happen on valid code.
8251   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8252   ExprResult RHSPtr = &RHSExpr;
8253   CastKind K;
8254 
8255   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8256 }
8257 
8258 /// This helper function returns true if QT is a vector type that has element
8259 /// type ElementType.
8260 static bool isVector(QualType QT, QualType ElementType) {
8261   if (const VectorType *VT = QT->getAs<VectorType>())
8262     return VT->getElementType() == ElementType;
8263   return false;
8264 }
8265 
8266 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8267 /// has code to accommodate several GCC extensions when type checking
8268 /// pointers. Here are some objectionable examples that GCC considers warnings:
8269 ///
8270 ///  int a, *pint;
8271 ///  short *pshort;
8272 ///  struct foo *pfoo;
8273 ///
8274 ///  pint = pshort; // warning: assignment from incompatible pointer type
8275 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8276 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8277 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8278 ///
8279 /// As a result, the code for dealing with pointers is more complex than the
8280 /// C99 spec dictates.
8281 ///
8282 /// Sets 'Kind' for any result kind except Incompatible.
8283 Sema::AssignConvertType
8284 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8285                                  CastKind &Kind, bool ConvertRHS) {
8286   QualType RHSType = RHS.get()->getType();
8287   QualType OrigLHSType = LHSType;
8288 
8289   // Get canonical types.  We're not formatting these types, just comparing
8290   // them.
8291   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8292   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8293 
8294   // Common case: no conversion required.
8295   if (LHSType == RHSType) {
8296     Kind = CK_NoOp;
8297     return Compatible;
8298   }
8299 
8300   // If we have an atomic type, try a non-atomic assignment, then just add an
8301   // atomic qualification step.
8302   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8303     Sema::AssignConvertType result =
8304       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8305     if (result != Compatible)
8306       return result;
8307     if (Kind != CK_NoOp && ConvertRHS)
8308       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8309     Kind = CK_NonAtomicToAtomic;
8310     return Compatible;
8311   }
8312 
8313   // If the left-hand side is a reference type, then we are in a
8314   // (rare!) case where we've allowed the use of references in C,
8315   // e.g., as a parameter type in a built-in function. In this case,
8316   // just make sure that the type referenced is compatible with the
8317   // right-hand side type. The caller is responsible for adjusting
8318   // LHSType so that the resulting expression does not have reference
8319   // type.
8320   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8321     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8322       Kind = CK_LValueBitCast;
8323       return Compatible;
8324     }
8325     return Incompatible;
8326   }
8327 
8328   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8329   // to the same ExtVector type.
8330   if (LHSType->isExtVectorType()) {
8331     if (RHSType->isExtVectorType())
8332       return Incompatible;
8333     if (RHSType->isArithmeticType()) {
8334       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8335       if (ConvertRHS)
8336         RHS = prepareVectorSplat(LHSType, RHS.get());
8337       Kind = CK_VectorSplat;
8338       return Compatible;
8339     }
8340   }
8341 
8342   // Conversions to or from vector type.
8343   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8344     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8345       // Allow assignments of an AltiVec vector type to an equivalent GCC
8346       // vector type and vice versa
8347       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8348         Kind = CK_BitCast;
8349         return Compatible;
8350       }
8351 
8352       // If we are allowing lax vector conversions, and LHS and RHS are both
8353       // vectors, the total size only needs to be the same. This is a bitcast;
8354       // no bits are changed but the result type is different.
8355       if (isLaxVectorConversion(RHSType, LHSType)) {
8356         Kind = CK_BitCast;
8357         return IncompatibleVectors;
8358       }
8359     }
8360 
8361     // When the RHS comes from another lax conversion (e.g. binops between
8362     // scalars and vectors) the result is canonicalized as a vector. When the
8363     // LHS is also a vector, the lax is allowed by the condition above. Handle
8364     // the case where LHS is a scalar.
8365     if (LHSType->isScalarType()) {
8366       const VectorType *VecType = RHSType->getAs<VectorType>();
8367       if (VecType && VecType->getNumElements() == 1 &&
8368           isLaxVectorConversion(RHSType, LHSType)) {
8369         ExprResult *VecExpr = &RHS;
8370         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8371         Kind = CK_BitCast;
8372         return Compatible;
8373       }
8374     }
8375 
8376     return Incompatible;
8377   }
8378 
8379   // Diagnose attempts to convert between __float128 and long double where
8380   // such conversions currently can't be handled.
8381   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8382     return Incompatible;
8383 
8384   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8385   // discards the imaginary part.
8386   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8387       !LHSType->getAs<ComplexType>())
8388     return Incompatible;
8389 
8390   // Arithmetic conversions.
8391   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8392       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8393     if (ConvertRHS)
8394       Kind = PrepareScalarCast(RHS, LHSType);
8395     return Compatible;
8396   }
8397 
8398   // Conversions to normal pointers.
8399   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8400     // U* -> T*
8401     if (isa<PointerType>(RHSType)) {
8402       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8403       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8404       if (AddrSpaceL != AddrSpaceR)
8405         Kind = CK_AddressSpaceConversion;
8406       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8407         Kind = CK_NoOp;
8408       else
8409         Kind = CK_BitCast;
8410       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8411     }
8412 
8413     // int -> T*
8414     if (RHSType->isIntegerType()) {
8415       Kind = CK_IntegralToPointer; // FIXME: null?
8416       return IntToPointer;
8417     }
8418 
8419     // C pointers are not compatible with ObjC object pointers,
8420     // with two exceptions:
8421     if (isa<ObjCObjectPointerType>(RHSType)) {
8422       //  - conversions to void*
8423       if (LHSPointer->getPointeeType()->isVoidType()) {
8424         Kind = CK_BitCast;
8425         return Compatible;
8426       }
8427 
8428       //  - conversions from 'Class' to the redefinition type
8429       if (RHSType->isObjCClassType() &&
8430           Context.hasSameType(LHSType,
8431                               Context.getObjCClassRedefinitionType())) {
8432         Kind = CK_BitCast;
8433         return Compatible;
8434       }
8435 
8436       Kind = CK_BitCast;
8437       return IncompatiblePointer;
8438     }
8439 
8440     // U^ -> void*
8441     if (RHSType->getAs<BlockPointerType>()) {
8442       if (LHSPointer->getPointeeType()->isVoidType()) {
8443         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8444         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8445                                 ->getPointeeType()
8446                                 .getAddressSpace();
8447         Kind =
8448             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8449         return Compatible;
8450       }
8451     }
8452 
8453     return Incompatible;
8454   }
8455 
8456   // Conversions to block pointers.
8457   if (isa<BlockPointerType>(LHSType)) {
8458     // U^ -> T^
8459     if (RHSType->isBlockPointerType()) {
8460       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8461                               ->getPointeeType()
8462                               .getAddressSpace();
8463       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8464                               ->getPointeeType()
8465                               .getAddressSpace();
8466       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8467       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8468     }
8469 
8470     // int or null -> T^
8471     if (RHSType->isIntegerType()) {
8472       Kind = CK_IntegralToPointer; // FIXME: null
8473       return IntToBlockPointer;
8474     }
8475 
8476     // id -> T^
8477     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8478       Kind = CK_AnyPointerToBlockPointerCast;
8479       return Compatible;
8480     }
8481 
8482     // void* -> T^
8483     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8484       if (RHSPT->getPointeeType()->isVoidType()) {
8485         Kind = CK_AnyPointerToBlockPointerCast;
8486         return Compatible;
8487       }
8488 
8489     return Incompatible;
8490   }
8491 
8492   // Conversions to Objective-C pointers.
8493   if (isa<ObjCObjectPointerType>(LHSType)) {
8494     // A* -> B*
8495     if (RHSType->isObjCObjectPointerType()) {
8496       Kind = CK_BitCast;
8497       Sema::AssignConvertType result =
8498         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8499       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8500           result == Compatible &&
8501           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8502         result = IncompatibleObjCWeakRef;
8503       return result;
8504     }
8505 
8506     // int or null -> A*
8507     if (RHSType->isIntegerType()) {
8508       Kind = CK_IntegralToPointer; // FIXME: null
8509       return IntToPointer;
8510     }
8511 
8512     // In general, C pointers are not compatible with ObjC object pointers,
8513     // with two exceptions:
8514     if (isa<PointerType>(RHSType)) {
8515       Kind = CK_CPointerToObjCPointerCast;
8516 
8517       //  - conversions from 'void*'
8518       if (RHSType->isVoidPointerType()) {
8519         return Compatible;
8520       }
8521 
8522       //  - conversions to 'Class' from its redefinition type
8523       if (LHSType->isObjCClassType() &&
8524           Context.hasSameType(RHSType,
8525                               Context.getObjCClassRedefinitionType())) {
8526         return Compatible;
8527       }
8528 
8529       return IncompatiblePointer;
8530     }
8531 
8532     // Only under strict condition T^ is compatible with an Objective-C pointer.
8533     if (RHSType->isBlockPointerType() &&
8534         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8535       if (ConvertRHS)
8536         maybeExtendBlockObject(RHS);
8537       Kind = CK_BlockPointerToObjCPointerCast;
8538       return Compatible;
8539     }
8540 
8541     return Incompatible;
8542   }
8543 
8544   // Conversions from pointers that are not covered by the above.
8545   if (isa<PointerType>(RHSType)) {
8546     // T* -> _Bool
8547     if (LHSType == Context.BoolTy) {
8548       Kind = CK_PointerToBoolean;
8549       return Compatible;
8550     }
8551 
8552     // T* -> int
8553     if (LHSType->isIntegerType()) {
8554       Kind = CK_PointerToIntegral;
8555       return PointerToInt;
8556     }
8557 
8558     return Incompatible;
8559   }
8560 
8561   // Conversions from Objective-C pointers that are not covered by the above.
8562   if (isa<ObjCObjectPointerType>(RHSType)) {
8563     // T* -> _Bool
8564     if (LHSType == Context.BoolTy) {
8565       Kind = CK_PointerToBoolean;
8566       return Compatible;
8567     }
8568 
8569     // T* -> int
8570     if (LHSType->isIntegerType()) {
8571       Kind = CK_PointerToIntegral;
8572       return PointerToInt;
8573     }
8574 
8575     return Incompatible;
8576   }
8577 
8578   // struct A -> struct B
8579   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8580     if (Context.typesAreCompatible(LHSType, RHSType)) {
8581       Kind = CK_NoOp;
8582       return Compatible;
8583     }
8584   }
8585 
8586   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8587     Kind = CK_IntToOCLSampler;
8588     return Compatible;
8589   }
8590 
8591   return Incompatible;
8592 }
8593 
8594 /// Constructs a transparent union from an expression that is
8595 /// used to initialize the transparent union.
8596 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8597                                       ExprResult &EResult, QualType UnionType,
8598                                       FieldDecl *Field) {
8599   // Build an initializer list that designates the appropriate member
8600   // of the transparent union.
8601   Expr *E = EResult.get();
8602   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8603                                                    E, SourceLocation());
8604   Initializer->setType(UnionType);
8605   Initializer->setInitializedFieldInUnion(Field);
8606 
8607   // Build a compound literal constructing a value of the transparent
8608   // union type from this initializer list.
8609   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8610   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8611                                         VK_RValue, Initializer, false);
8612 }
8613 
8614 Sema::AssignConvertType
8615 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8616                                                ExprResult &RHS) {
8617   QualType RHSType = RHS.get()->getType();
8618 
8619   // If the ArgType is a Union type, we want to handle a potential
8620   // transparent_union GCC extension.
8621   const RecordType *UT = ArgType->getAsUnionType();
8622   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8623     return Incompatible;
8624 
8625   // The field to initialize within the transparent union.
8626   RecordDecl *UD = UT->getDecl();
8627   FieldDecl *InitField = nullptr;
8628   // It's compatible if the expression matches any of the fields.
8629   for (auto *it : UD->fields()) {
8630     if (it->getType()->isPointerType()) {
8631       // If the transparent union contains a pointer type, we allow:
8632       // 1) void pointer
8633       // 2) null pointer constant
8634       if (RHSType->isPointerType())
8635         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8636           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8637           InitField = it;
8638           break;
8639         }
8640 
8641       if (RHS.get()->isNullPointerConstant(Context,
8642                                            Expr::NPC_ValueDependentIsNull)) {
8643         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8644                                 CK_NullToPointer);
8645         InitField = it;
8646         break;
8647       }
8648     }
8649 
8650     CastKind Kind;
8651     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8652           == Compatible) {
8653       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8654       InitField = it;
8655       break;
8656     }
8657   }
8658 
8659   if (!InitField)
8660     return Incompatible;
8661 
8662   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8663   return Compatible;
8664 }
8665 
8666 Sema::AssignConvertType
8667 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8668                                        bool Diagnose,
8669                                        bool DiagnoseCFAudited,
8670                                        bool ConvertRHS) {
8671   // We need to be able to tell the caller whether we diagnosed a problem, if
8672   // they ask us to issue diagnostics.
8673   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8674 
8675   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8676   // we can't avoid *all* modifications at the moment, so we need some somewhere
8677   // to put the updated value.
8678   ExprResult LocalRHS = CallerRHS;
8679   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8680 
8681   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8682     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8683       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8684           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8685         Diag(RHS.get()->getExprLoc(),
8686              diag::warn_noderef_to_dereferenceable_pointer)
8687             << RHS.get()->getSourceRange();
8688       }
8689     }
8690   }
8691 
8692   if (getLangOpts().CPlusPlus) {
8693     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8694       // C++ 5.17p3: If the left operand is not of class type, the
8695       // expression is implicitly converted (C++ 4) to the
8696       // cv-unqualified type of the left operand.
8697       QualType RHSType = RHS.get()->getType();
8698       if (Diagnose) {
8699         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8700                                         AA_Assigning);
8701       } else {
8702         ImplicitConversionSequence ICS =
8703             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8704                                   /*SuppressUserConversions=*/false,
8705                                   /*AllowExplicit=*/false,
8706                                   /*InOverloadResolution=*/false,
8707                                   /*CStyle=*/false,
8708                                   /*AllowObjCWritebackConversion=*/false);
8709         if (ICS.isFailure())
8710           return Incompatible;
8711         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8712                                         ICS, AA_Assigning);
8713       }
8714       if (RHS.isInvalid())
8715         return Incompatible;
8716       Sema::AssignConvertType result = Compatible;
8717       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8718           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8719         result = IncompatibleObjCWeakRef;
8720       return result;
8721     }
8722 
8723     // FIXME: Currently, we fall through and treat C++ classes like C
8724     // structures.
8725     // FIXME: We also fall through for atomics; not sure what should
8726     // happen there, though.
8727   } else if (RHS.get()->getType() == Context.OverloadTy) {
8728     // As a set of extensions to C, we support overloading on functions. These
8729     // functions need to be resolved here.
8730     DeclAccessPair DAP;
8731     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8732             RHS.get(), LHSType, /*Complain=*/false, DAP))
8733       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8734     else
8735       return Incompatible;
8736   }
8737 
8738   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8739   // a null pointer constant.
8740   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8741        LHSType->isBlockPointerType()) &&
8742       RHS.get()->isNullPointerConstant(Context,
8743                                        Expr::NPC_ValueDependentIsNull)) {
8744     if (Diagnose || ConvertRHS) {
8745       CastKind Kind;
8746       CXXCastPath Path;
8747       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8748                              /*IgnoreBaseAccess=*/false, Diagnose);
8749       if (ConvertRHS)
8750         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8751     }
8752     return Compatible;
8753   }
8754 
8755   // OpenCL queue_t type assignment.
8756   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8757                                  Context, Expr::NPC_ValueDependentIsNull)) {
8758     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8759     return Compatible;
8760   }
8761 
8762   // This check seems unnatural, however it is necessary to ensure the proper
8763   // conversion of functions/arrays. If the conversion were done for all
8764   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8765   // expressions that suppress this implicit conversion (&, sizeof).
8766   //
8767   // Suppress this for references: C++ 8.5.3p5.
8768   if (!LHSType->isReferenceType()) {
8769     // FIXME: We potentially allocate here even if ConvertRHS is false.
8770     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8771     if (RHS.isInvalid())
8772       return Incompatible;
8773   }
8774   CastKind Kind;
8775   Sema::AssignConvertType result =
8776     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8777 
8778   // C99 6.5.16.1p2: The value of the right operand is converted to the
8779   // type of the assignment expression.
8780   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8781   // so that we can use references in built-in functions even in C.
8782   // The getNonReferenceType() call makes sure that the resulting expression
8783   // does not have reference type.
8784   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8785     QualType Ty = LHSType.getNonLValueExprType(Context);
8786     Expr *E = RHS.get();
8787 
8788     // Check for various Objective-C errors. If we are not reporting
8789     // diagnostics and just checking for errors, e.g., during overload
8790     // resolution, return Incompatible to indicate the failure.
8791     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8792         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8793                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8794       if (!Diagnose)
8795         return Incompatible;
8796     }
8797     if (getLangOpts().ObjC &&
8798         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8799                                            E->getType(), E, Diagnose) ||
8800          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8801       if (!Diagnose)
8802         return Incompatible;
8803       // Replace the expression with a corrected version and continue so we
8804       // can find further errors.
8805       RHS = E;
8806       return Compatible;
8807     }
8808 
8809     if (ConvertRHS)
8810       RHS = ImpCastExprToType(E, Ty, Kind);
8811   }
8812 
8813   return result;
8814 }
8815 
8816 namespace {
8817 /// The original operand to an operator, prior to the application of the usual
8818 /// arithmetic conversions and converting the arguments of a builtin operator
8819 /// candidate.
8820 struct OriginalOperand {
8821   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8822     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8823       Op = MTE->getSubExpr();
8824     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8825       Op = BTE->getSubExpr();
8826     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8827       Orig = ICE->getSubExprAsWritten();
8828       Conversion = ICE->getConversionFunction();
8829     }
8830   }
8831 
8832   QualType getType() const { return Orig->getType(); }
8833 
8834   Expr *Orig;
8835   NamedDecl *Conversion;
8836 };
8837 }
8838 
8839 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8840                                ExprResult &RHS) {
8841   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8842 
8843   Diag(Loc, diag::err_typecheck_invalid_operands)
8844     << OrigLHS.getType() << OrigRHS.getType()
8845     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8846 
8847   // If a user-defined conversion was applied to either of the operands prior
8848   // to applying the built-in operator rules, tell the user about it.
8849   if (OrigLHS.Conversion) {
8850     Diag(OrigLHS.Conversion->getLocation(),
8851          diag::note_typecheck_invalid_operands_converted)
8852       << 0 << LHS.get()->getType();
8853   }
8854   if (OrigRHS.Conversion) {
8855     Diag(OrigRHS.Conversion->getLocation(),
8856          diag::note_typecheck_invalid_operands_converted)
8857       << 1 << RHS.get()->getType();
8858   }
8859 
8860   return QualType();
8861 }
8862 
8863 // Diagnose cases where a scalar was implicitly converted to a vector and
8864 // diagnose the underlying types. Otherwise, diagnose the error
8865 // as invalid vector logical operands for non-C++ cases.
8866 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8867                                             ExprResult &RHS) {
8868   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8869   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8870 
8871   bool LHSNatVec = LHSType->isVectorType();
8872   bool RHSNatVec = RHSType->isVectorType();
8873 
8874   if (!(LHSNatVec && RHSNatVec)) {
8875     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8876     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8877     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8878         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8879         << Vector->getSourceRange();
8880     return QualType();
8881   }
8882 
8883   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8884       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8885       << RHS.get()->getSourceRange();
8886 
8887   return QualType();
8888 }
8889 
8890 /// Try to convert a value of non-vector type to a vector type by converting
8891 /// the type to the element type of the vector and then performing a splat.
8892 /// If the language is OpenCL, we only use conversions that promote scalar
8893 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8894 /// for float->int.
8895 ///
8896 /// OpenCL V2.0 6.2.6.p2:
8897 /// An error shall occur if any scalar operand type has greater rank
8898 /// than the type of the vector element.
8899 ///
8900 /// \param scalar - if non-null, actually perform the conversions
8901 /// \return true if the operation fails (but without diagnosing the failure)
8902 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8903                                      QualType scalarTy,
8904                                      QualType vectorEltTy,
8905                                      QualType vectorTy,
8906                                      unsigned &DiagID) {
8907   // The conversion to apply to the scalar before splatting it,
8908   // if necessary.
8909   CastKind scalarCast = CK_NoOp;
8910 
8911   if (vectorEltTy->isIntegralType(S.Context)) {
8912     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8913         (scalarTy->isIntegerType() &&
8914          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8915       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8916       return true;
8917     }
8918     if (!scalarTy->isIntegralType(S.Context))
8919       return true;
8920     scalarCast = CK_IntegralCast;
8921   } else if (vectorEltTy->isRealFloatingType()) {
8922     if (scalarTy->isRealFloatingType()) {
8923       if (S.getLangOpts().OpenCL &&
8924           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8925         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8926         return true;
8927       }
8928       scalarCast = CK_FloatingCast;
8929     }
8930     else if (scalarTy->isIntegralType(S.Context))
8931       scalarCast = CK_IntegralToFloating;
8932     else
8933       return true;
8934   } else {
8935     return true;
8936   }
8937 
8938   // Adjust scalar if desired.
8939   if (scalar) {
8940     if (scalarCast != CK_NoOp)
8941       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8942     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8943   }
8944   return false;
8945 }
8946 
8947 /// Convert vector E to a vector with the same number of elements but different
8948 /// element type.
8949 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8950   const auto *VecTy = E->getType()->getAs<VectorType>();
8951   assert(VecTy && "Expression E must be a vector");
8952   QualType NewVecTy = S.Context.getVectorType(ElementType,
8953                                               VecTy->getNumElements(),
8954                                               VecTy->getVectorKind());
8955 
8956   // Look through the implicit cast. Return the subexpression if its type is
8957   // NewVecTy.
8958   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8959     if (ICE->getSubExpr()->getType() == NewVecTy)
8960       return ICE->getSubExpr();
8961 
8962   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8963   return S.ImpCastExprToType(E, NewVecTy, Cast);
8964 }
8965 
8966 /// Test if a (constant) integer Int can be casted to another integer type
8967 /// IntTy without losing precision.
8968 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8969                                       QualType OtherIntTy) {
8970   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8971 
8972   // Reject cases where the value of the Int is unknown as that would
8973   // possibly cause truncation, but accept cases where the scalar can be
8974   // demoted without loss of precision.
8975   Expr::EvalResult EVResult;
8976   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8977   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8978   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8979   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8980 
8981   if (CstInt) {
8982     // If the scalar is constant and is of a higher order and has more active
8983     // bits that the vector element type, reject it.
8984     llvm::APSInt Result = EVResult.Val.getInt();
8985     unsigned NumBits = IntSigned
8986                            ? (Result.isNegative() ? Result.getMinSignedBits()
8987                                                   : Result.getActiveBits())
8988                            : Result.getActiveBits();
8989     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8990       return true;
8991 
8992     // If the signedness of the scalar type and the vector element type
8993     // differs and the number of bits is greater than that of the vector
8994     // element reject it.
8995     return (IntSigned != OtherIntSigned &&
8996             NumBits > S.Context.getIntWidth(OtherIntTy));
8997   }
8998 
8999   // Reject cases where the value of the scalar is not constant and it's
9000   // order is greater than that of the vector element type.
9001   return (Order < 0);
9002 }
9003 
9004 /// Test if a (constant) integer Int can be casted to floating point type
9005 /// FloatTy without losing precision.
9006 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9007                                      QualType FloatTy) {
9008   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9009 
9010   // Determine if the integer constant can be expressed as a floating point
9011   // number of the appropriate type.
9012   Expr::EvalResult EVResult;
9013   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9014 
9015   uint64_t Bits = 0;
9016   if (CstInt) {
9017     // Reject constants that would be truncated if they were converted to
9018     // the floating point type. Test by simple to/from conversion.
9019     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9020     //        could be avoided if there was a convertFromAPInt method
9021     //        which could signal back if implicit truncation occurred.
9022     llvm::APSInt Result = EVResult.Val.getInt();
9023     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9024     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9025                            llvm::APFloat::rmTowardZero);
9026     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9027                              !IntTy->hasSignedIntegerRepresentation());
9028     bool Ignored = false;
9029     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9030                            &Ignored);
9031     if (Result != ConvertBack)
9032       return true;
9033   } else {
9034     // Reject types that cannot be fully encoded into the mantissa of
9035     // the float.
9036     Bits = S.Context.getTypeSize(IntTy);
9037     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9038         S.Context.getFloatTypeSemantics(FloatTy));
9039     if (Bits > FloatPrec)
9040       return true;
9041   }
9042 
9043   return false;
9044 }
9045 
9046 /// Attempt to convert and splat Scalar into a vector whose types matches
9047 /// Vector following GCC conversion rules. The rule is that implicit
9048 /// conversion can occur when Scalar can be casted to match Vector's element
9049 /// type without causing truncation of Scalar.
9050 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9051                                         ExprResult *Vector) {
9052   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9053   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9054   const VectorType *VT = VectorTy->getAs<VectorType>();
9055 
9056   assert(!isa<ExtVectorType>(VT) &&
9057          "ExtVectorTypes should not be handled here!");
9058 
9059   QualType VectorEltTy = VT->getElementType();
9060 
9061   // Reject cases where the vector element type or the scalar element type are
9062   // not integral or floating point types.
9063   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9064     return true;
9065 
9066   // The conversion to apply to the scalar before splatting it,
9067   // if necessary.
9068   CastKind ScalarCast = CK_NoOp;
9069 
9070   // Accept cases where the vector elements are integers and the scalar is
9071   // an integer.
9072   // FIXME: Notionally if the scalar was a floating point value with a precise
9073   //        integral representation, we could cast it to an appropriate integer
9074   //        type and then perform the rest of the checks here. GCC will perform
9075   //        this conversion in some cases as determined by the input language.
9076   //        We should accept it on a language independent basis.
9077   if (VectorEltTy->isIntegralType(S.Context) &&
9078       ScalarTy->isIntegralType(S.Context) &&
9079       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9080 
9081     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9082       return true;
9083 
9084     ScalarCast = CK_IntegralCast;
9085   } else if (VectorEltTy->isIntegralType(S.Context) &&
9086              ScalarTy->isRealFloatingType()) {
9087     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9088       ScalarCast = CK_FloatingToIntegral;
9089     else
9090       return true;
9091   } else if (VectorEltTy->isRealFloatingType()) {
9092     if (ScalarTy->isRealFloatingType()) {
9093 
9094       // Reject cases where the scalar type is not a constant and has a higher
9095       // Order than the vector element type.
9096       llvm::APFloat Result(0.0);
9097       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
9098       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9099       if (!CstScalar && Order < 0)
9100         return true;
9101 
9102       // If the scalar cannot be safely casted to the vector element type,
9103       // reject it.
9104       if (CstScalar) {
9105         bool Truncated = false;
9106         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9107                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9108         if (Truncated)
9109           return true;
9110       }
9111 
9112       ScalarCast = CK_FloatingCast;
9113     } else if (ScalarTy->isIntegralType(S.Context)) {
9114       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9115         return true;
9116 
9117       ScalarCast = CK_IntegralToFloating;
9118     } else
9119       return true;
9120   }
9121 
9122   // Adjust scalar if desired.
9123   if (Scalar) {
9124     if (ScalarCast != CK_NoOp)
9125       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9126     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9127   }
9128   return false;
9129 }
9130 
9131 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9132                                    SourceLocation Loc, bool IsCompAssign,
9133                                    bool AllowBothBool,
9134                                    bool AllowBoolConversions) {
9135   if (!IsCompAssign) {
9136     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9137     if (LHS.isInvalid())
9138       return QualType();
9139   }
9140   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9141   if (RHS.isInvalid())
9142     return QualType();
9143 
9144   // For conversion purposes, we ignore any qualifiers.
9145   // For example, "const float" and "float" are equivalent.
9146   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9147   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9148 
9149   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9150   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9151   assert(LHSVecType || RHSVecType);
9152 
9153   // AltiVec-style "vector bool op vector bool" combinations are allowed
9154   // for some operators but not others.
9155   if (!AllowBothBool &&
9156       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9157       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9158     return InvalidOperands(Loc, LHS, RHS);
9159 
9160   // If the vector types are identical, return.
9161   if (Context.hasSameType(LHSType, RHSType))
9162     return LHSType;
9163 
9164   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9165   if (LHSVecType && RHSVecType &&
9166       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9167     if (isa<ExtVectorType>(LHSVecType)) {
9168       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9169       return LHSType;
9170     }
9171 
9172     if (!IsCompAssign)
9173       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9174     return RHSType;
9175   }
9176 
9177   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9178   // can be mixed, with the result being the non-bool type.  The non-bool
9179   // operand must have integer element type.
9180   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9181       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9182       (Context.getTypeSize(LHSVecType->getElementType()) ==
9183        Context.getTypeSize(RHSVecType->getElementType()))) {
9184     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9185         LHSVecType->getElementType()->isIntegerType() &&
9186         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9187       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9188       return LHSType;
9189     }
9190     if (!IsCompAssign &&
9191         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9192         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9193         RHSVecType->getElementType()->isIntegerType()) {
9194       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9195       return RHSType;
9196     }
9197   }
9198 
9199   // If there's a vector type and a scalar, try to convert the scalar to
9200   // the vector element type and splat.
9201   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9202   if (!RHSVecType) {
9203     if (isa<ExtVectorType>(LHSVecType)) {
9204       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9205                                     LHSVecType->getElementType(), LHSType,
9206                                     DiagID))
9207         return LHSType;
9208     } else {
9209       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9210         return LHSType;
9211     }
9212   }
9213   if (!LHSVecType) {
9214     if (isa<ExtVectorType>(RHSVecType)) {
9215       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9216                                     LHSType, RHSVecType->getElementType(),
9217                                     RHSType, DiagID))
9218         return RHSType;
9219     } else {
9220       if (LHS.get()->getValueKind() == VK_LValue ||
9221           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9222         return RHSType;
9223     }
9224   }
9225 
9226   // FIXME: The code below also handles conversion between vectors and
9227   // non-scalars, we should break this down into fine grained specific checks
9228   // and emit proper diagnostics.
9229   QualType VecType = LHSVecType ? LHSType : RHSType;
9230   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9231   QualType OtherType = LHSVecType ? RHSType : LHSType;
9232   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9233   if (isLaxVectorConversion(OtherType, VecType)) {
9234     // If we're allowing lax vector conversions, only the total (data) size
9235     // needs to be the same. For non compound assignment, if one of the types is
9236     // scalar, the result is always the vector type.
9237     if (!IsCompAssign) {
9238       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9239       return VecType;
9240     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9241     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9242     // type. Note that this is already done by non-compound assignments in
9243     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9244     // <1 x T> -> T. The result is also a vector type.
9245     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9246                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9247       ExprResult *RHSExpr = &RHS;
9248       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9249       return VecType;
9250     }
9251   }
9252 
9253   // Okay, the expression is invalid.
9254 
9255   // If there's a non-vector, non-real operand, diagnose that.
9256   if ((!RHSVecType && !RHSType->isRealType()) ||
9257       (!LHSVecType && !LHSType->isRealType())) {
9258     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9259       << LHSType << RHSType
9260       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9261     return QualType();
9262   }
9263 
9264   // OpenCL V1.1 6.2.6.p1:
9265   // If the operands are of more than one vector type, then an error shall
9266   // occur. Implicit conversions between vector types are not permitted, per
9267   // section 6.2.1.
9268   if (getLangOpts().OpenCL &&
9269       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9270       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9271     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9272                                                            << RHSType;
9273     return QualType();
9274   }
9275 
9276 
9277   // If there is a vector type that is not a ExtVector and a scalar, we reach
9278   // this point if scalar could not be converted to the vector's element type
9279   // without truncation.
9280   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9281       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9282     QualType Scalar = LHSVecType ? RHSType : LHSType;
9283     QualType Vector = LHSVecType ? LHSType : RHSType;
9284     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9285     Diag(Loc,
9286          diag::err_typecheck_vector_not_convertable_implict_truncation)
9287         << ScalarOrVector << Scalar << Vector;
9288 
9289     return QualType();
9290   }
9291 
9292   // Otherwise, use the generic diagnostic.
9293   Diag(Loc, DiagID)
9294     << LHSType << RHSType
9295     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9296   return QualType();
9297 }
9298 
9299 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9300 // expression.  These are mainly cases where the null pointer is used as an
9301 // integer instead of a pointer.
9302 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9303                                 SourceLocation Loc, bool IsCompare) {
9304   // The canonical way to check for a GNU null is with isNullPointerConstant,
9305   // but we use a bit of a hack here for speed; this is a relatively
9306   // hot path, and isNullPointerConstant is slow.
9307   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9308   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9309 
9310   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9311 
9312   // Avoid analyzing cases where the result will either be invalid (and
9313   // diagnosed as such) or entirely valid and not something to warn about.
9314   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9315       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9316     return;
9317 
9318   // Comparison operations would not make sense with a null pointer no matter
9319   // what the other expression is.
9320   if (!IsCompare) {
9321     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9322         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9323         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9324     return;
9325   }
9326 
9327   // The rest of the operations only make sense with a null pointer
9328   // if the other expression is a pointer.
9329   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9330       NonNullType->canDecayToPointerType())
9331     return;
9332 
9333   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9334       << LHSNull /* LHS is NULL */ << NonNullType
9335       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9336 }
9337 
9338 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9339                                           SourceLocation Loc) {
9340   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9341   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9342   if (!LUE || !RUE)
9343     return;
9344   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9345       RUE->getKind() != UETT_SizeOf)
9346     return;
9347 
9348   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9349   QualType LHSTy = LHSArg->getType();
9350   QualType RHSTy;
9351 
9352   if (RUE->isArgumentType())
9353     RHSTy = RUE->getArgumentType();
9354   else
9355     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9356 
9357   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9358     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9359       return;
9360 
9361     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9362     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9363       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9364         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9365             << LHSArgDecl;
9366     }
9367   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9368     QualType ArrayElemTy = ArrayTy->getElementType();
9369     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9370         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9371         ArrayElemTy->isCharType() ||
9372         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9373       return;
9374     S.Diag(Loc, diag::warn_division_sizeof_array)
9375         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9376     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9377       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9378         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9379             << LHSArgDecl;
9380     }
9381 
9382     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9383   }
9384 }
9385 
9386 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9387                                                ExprResult &RHS,
9388                                                SourceLocation Loc, bool IsDiv) {
9389   // Check for division/remainder by zero.
9390   Expr::EvalResult RHSValue;
9391   if (!RHS.get()->isValueDependent() &&
9392       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9393       RHSValue.Val.getInt() == 0)
9394     S.DiagRuntimeBehavior(Loc, RHS.get(),
9395                           S.PDiag(diag::warn_remainder_division_by_zero)
9396                             << IsDiv << RHS.get()->getSourceRange());
9397 }
9398 
9399 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9400                                            SourceLocation Loc,
9401                                            bool IsCompAssign, bool IsDiv) {
9402   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9403 
9404   if (LHS.get()->getType()->isVectorType() ||
9405       RHS.get()->getType()->isVectorType())
9406     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9407                                /*AllowBothBool*/getLangOpts().AltiVec,
9408                                /*AllowBoolConversions*/false);
9409 
9410   QualType compType = UsualArithmeticConversions(
9411       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9412   if (LHS.isInvalid() || RHS.isInvalid())
9413     return QualType();
9414 
9415 
9416   if (compType.isNull() || !compType->isArithmeticType())
9417     return InvalidOperands(Loc, LHS, RHS);
9418   if (IsDiv) {
9419     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9420     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9421   }
9422   return compType;
9423 }
9424 
9425 QualType Sema::CheckRemainderOperands(
9426   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9427   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9428 
9429   if (LHS.get()->getType()->isVectorType() ||
9430       RHS.get()->getType()->isVectorType()) {
9431     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9432         RHS.get()->getType()->hasIntegerRepresentation())
9433       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9434                                  /*AllowBothBool*/getLangOpts().AltiVec,
9435                                  /*AllowBoolConversions*/false);
9436     return InvalidOperands(Loc, LHS, RHS);
9437   }
9438 
9439   QualType compType = UsualArithmeticConversions(
9440       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9441   if (LHS.isInvalid() || RHS.isInvalid())
9442     return QualType();
9443 
9444   if (compType.isNull() || !compType->isIntegerType())
9445     return InvalidOperands(Loc, LHS, RHS);
9446   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9447   return compType;
9448 }
9449 
9450 /// Diagnose invalid arithmetic on two void pointers.
9451 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9452                                                 Expr *LHSExpr, Expr *RHSExpr) {
9453   S.Diag(Loc, S.getLangOpts().CPlusPlus
9454                 ? diag::err_typecheck_pointer_arith_void_type
9455                 : diag::ext_gnu_void_ptr)
9456     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9457                             << RHSExpr->getSourceRange();
9458 }
9459 
9460 /// Diagnose invalid arithmetic on a void pointer.
9461 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9462                                             Expr *Pointer) {
9463   S.Diag(Loc, S.getLangOpts().CPlusPlus
9464                 ? diag::err_typecheck_pointer_arith_void_type
9465                 : diag::ext_gnu_void_ptr)
9466     << 0 /* one pointer */ << Pointer->getSourceRange();
9467 }
9468 
9469 /// Diagnose invalid arithmetic on a null pointer.
9470 ///
9471 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9472 /// idiom, which we recognize as a GNU extension.
9473 ///
9474 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9475                                             Expr *Pointer, bool IsGNUIdiom) {
9476   if (IsGNUIdiom)
9477     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9478       << Pointer->getSourceRange();
9479   else
9480     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9481       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9482 }
9483 
9484 /// Diagnose invalid arithmetic on two function pointers.
9485 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9486                                                     Expr *LHS, Expr *RHS) {
9487   assert(LHS->getType()->isAnyPointerType());
9488   assert(RHS->getType()->isAnyPointerType());
9489   S.Diag(Loc, S.getLangOpts().CPlusPlus
9490                 ? diag::err_typecheck_pointer_arith_function_type
9491                 : diag::ext_gnu_ptr_func_arith)
9492     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9493     // We only show the second type if it differs from the first.
9494     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9495                                                    RHS->getType())
9496     << RHS->getType()->getPointeeType()
9497     << LHS->getSourceRange() << RHS->getSourceRange();
9498 }
9499 
9500 /// Diagnose invalid arithmetic on a function pointer.
9501 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9502                                                 Expr *Pointer) {
9503   assert(Pointer->getType()->isAnyPointerType());
9504   S.Diag(Loc, S.getLangOpts().CPlusPlus
9505                 ? diag::err_typecheck_pointer_arith_function_type
9506                 : diag::ext_gnu_ptr_func_arith)
9507     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9508     << 0 /* one pointer, so only one type */
9509     << Pointer->getSourceRange();
9510 }
9511 
9512 /// Emit error if Operand is incomplete pointer type
9513 ///
9514 /// \returns True if pointer has incomplete type
9515 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9516                                                  Expr *Operand) {
9517   QualType ResType = Operand->getType();
9518   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9519     ResType = ResAtomicType->getValueType();
9520 
9521   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9522   QualType PointeeTy = ResType->getPointeeType();
9523   return S.RequireCompleteType(Loc, PointeeTy,
9524                                diag::err_typecheck_arithmetic_incomplete_type,
9525                                PointeeTy, Operand->getSourceRange());
9526 }
9527 
9528 /// Check the validity of an arithmetic pointer operand.
9529 ///
9530 /// If the operand has pointer type, this code will check for pointer types
9531 /// which are invalid in arithmetic operations. These will be diagnosed
9532 /// appropriately, including whether or not the use is supported as an
9533 /// extension.
9534 ///
9535 /// \returns True when the operand is valid to use (even if as an extension).
9536 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9537                                             Expr *Operand) {
9538   QualType ResType = Operand->getType();
9539   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9540     ResType = ResAtomicType->getValueType();
9541 
9542   if (!ResType->isAnyPointerType()) return true;
9543 
9544   QualType PointeeTy = ResType->getPointeeType();
9545   if (PointeeTy->isVoidType()) {
9546     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9547     return !S.getLangOpts().CPlusPlus;
9548   }
9549   if (PointeeTy->isFunctionType()) {
9550     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9551     return !S.getLangOpts().CPlusPlus;
9552   }
9553 
9554   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9555 
9556   return true;
9557 }
9558 
9559 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9560 /// operands.
9561 ///
9562 /// This routine will diagnose any invalid arithmetic on pointer operands much
9563 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9564 /// for emitting a single diagnostic even for operations where both LHS and RHS
9565 /// are (potentially problematic) pointers.
9566 ///
9567 /// \returns True when the operand is valid to use (even if as an extension).
9568 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9569                                                 Expr *LHSExpr, Expr *RHSExpr) {
9570   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9571   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9572   if (!isLHSPointer && !isRHSPointer) return true;
9573 
9574   QualType LHSPointeeTy, RHSPointeeTy;
9575   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9576   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9577 
9578   // if both are pointers check if operation is valid wrt address spaces
9579   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9580     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9581     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9582     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9583       S.Diag(Loc,
9584              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9585           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9586           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9587       return false;
9588     }
9589   }
9590 
9591   // Check for arithmetic on pointers to incomplete types.
9592   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9593   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9594   if (isLHSVoidPtr || isRHSVoidPtr) {
9595     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9596     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9597     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9598 
9599     return !S.getLangOpts().CPlusPlus;
9600   }
9601 
9602   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9603   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9604   if (isLHSFuncPtr || isRHSFuncPtr) {
9605     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9606     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9607                                                                 RHSExpr);
9608     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9609 
9610     return !S.getLangOpts().CPlusPlus;
9611   }
9612 
9613   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9614     return false;
9615   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9616     return false;
9617 
9618   return true;
9619 }
9620 
9621 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9622 /// literal.
9623 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9624                                   Expr *LHSExpr, Expr *RHSExpr) {
9625   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9626   Expr* IndexExpr = RHSExpr;
9627   if (!StrExpr) {
9628     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9629     IndexExpr = LHSExpr;
9630   }
9631 
9632   bool IsStringPlusInt = StrExpr &&
9633       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9634   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9635     return;
9636 
9637   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9638   Self.Diag(OpLoc, diag::warn_string_plus_int)
9639       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9640 
9641   // Only print a fixit for "str" + int, not for int + "str".
9642   if (IndexExpr == RHSExpr) {
9643     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9644     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9645         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9646         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9647         << FixItHint::CreateInsertion(EndLoc, "]");
9648   } else
9649     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9650 }
9651 
9652 /// Emit a warning when adding a char literal to a string.
9653 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9654                                    Expr *LHSExpr, Expr *RHSExpr) {
9655   const Expr *StringRefExpr = LHSExpr;
9656   const CharacterLiteral *CharExpr =
9657       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9658 
9659   if (!CharExpr) {
9660     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9661     StringRefExpr = RHSExpr;
9662   }
9663 
9664   if (!CharExpr || !StringRefExpr)
9665     return;
9666 
9667   const QualType StringType = StringRefExpr->getType();
9668 
9669   // Return if not a PointerType.
9670   if (!StringType->isAnyPointerType())
9671     return;
9672 
9673   // Return if not a CharacterType.
9674   if (!StringType->getPointeeType()->isAnyCharacterType())
9675     return;
9676 
9677   ASTContext &Ctx = Self.getASTContext();
9678   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9679 
9680   const QualType CharType = CharExpr->getType();
9681   if (!CharType->isAnyCharacterType() &&
9682       CharType->isIntegerType() &&
9683       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9684     Self.Diag(OpLoc, diag::warn_string_plus_char)
9685         << DiagRange << Ctx.CharTy;
9686   } else {
9687     Self.Diag(OpLoc, diag::warn_string_plus_char)
9688         << DiagRange << CharExpr->getType();
9689   }
9690 
9691   // Only print a fixit for str + char, not for char + str.
9692   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9693     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9694     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9695         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9696         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9697         << FixItHint::CreateInsertion(EndLoc, "]");
9698   } else {
9699     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9700   }
9701 }
9702 
9703 /// Emit error when two pointers are incompatible.
9704 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9705                                            Expr *LHSExpr, Expr *RHSExpr) {
9706   assert(LHSExpr->getType()->isAnyPointerType());
9707   assert(RHSExpr->getType()->isAnyPointerType());
9708   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9709     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9710     << RHSExpr->getSourceRange();
9711 }
9712 
9713 // C99 6.5.6
9714 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9715                                      SourceLocation Loc, BinaryOperatorKind Opc,
9716                                      QualType* CompLHSTy) {
9717   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9718 
9719   if (LHS.get()->getType()->isVectorType() ||
9720       RHS.get()->getType()->isVectorType()) {
9721     QualType compType = CheckVectorOperands(
9722         LHS, RHS, Loc, CompLHSTy,
9723         /*AllowBothBool*/getLangOpts().AltiVec,
9724         /*AllowBoolConversions*/getLangOpts().ZVector);
9725     if (CompLHSTy) *CompLHSTy = compType;
9726     return compType;
9727   }
9728 
9729   QualType compType = UsualArithmeticConversions(
9730       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9731   if (LHS.isInvalid() || RHS.isInvalid())
9732     return QualType();
9733 
9734   // Diagnose "string literal" '+' int and string '+' "char literal".
9735   if (Opc == BO_Add) {
9736     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9737     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9738   }
9739 
9740   // handle the common case first (both operands are arithmetic).
9741   if (!compType.isNull() && compType->isArithmeticType()) {
9742     if (CompLHSTy) *CompLHSTy = compType;
9743     return compType;
9744   }
9745 
9746   // Type-checking.  Ultimately the pointer's going to be in PExp;
9747   // note that we bias towards the LHS being the pointer.
9748   Expr *PExp = LHS.get(), *IExp = RHS.get();
9749 
9750   bool isObjCPointer;
9751   if (PExp->getType()->isPointerType()) {
9752     isObjCPointer = false;
9753   } else if (PExp->getType()->isObjCObjectPointerType()) {
9754     isObjCPointer = true;
9755   } else {
9756     std::swap(PExp, IExp);
9757     if (PExp->getType()->isPointerType()) {
9758       isObjCPointer = false;
9759     } else if (PExp->getType()->isObjCObjectPointerType()) {
9760       isObjCPointer = true;
9761     } else {
9762       return InvalidOperands(Loc, LHS, RHS);
9763     }
9764   }
9765   assert(PExp->getType()->isAnyPointerType());
9766 
9767   if (!IExp->getType()->isIntegerType())
9768     return InvalidOperands(Loc, LHS, RHS);
9769 
9770   // Adding to a null pointer results in undefined behavior.
9771   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9772           Context, Expr::NPC_ValueDependentIsNotNull)) {
9773     // In C++ adding zero to a null pointer is defined.
9774     Expr::EvalResult KnownVal;
9775     if (!getLangOpts().CPlusPlus ||
9776         (!IExp->isValueDependent() &&
9777          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9778           KnownVal.Val.getInt() != 0))) {
9779       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9780       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9781           Context, BO_Add, PExp, IExp);
9782       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9783     }
9784   }
9785 
9786   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9787     return QualType();
9788 
9789   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9790     return QualType();
9791 
9792   // Check array bounds for pointer arithemtic
9793   CheckArrayAccess(PExp, IExp);
9794 
9795   if (CompLHSTy) {
9796     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9797     if (LHSTy.isNull()) {
9798       LHSTy = LHS.get()->getType();
9799       if (LHSTy->isPromotableIntegerType())
9800         LHSTy = Context.getPromotedIntegerType(LHSTy);
9801     }
9802     *CompLHSTy = LHSTy;
9803   }
9804 
9805   return PExp->getType();
9806 }
9807 
9808 // C99 6.5.6
9809 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9810                                         SourceLocation Loc,
9811                                         QualType* CompLHSTy) {
9812   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9813 
9814   if (LHS.get()->getType()->isVectorType() ||
9815       RHS.get()->getType()->isVectorType()) {
9816     QualType compType = CheckVectorOperands(
9817         LHS, RHS, Loc, CompLHSTy,
9818         /*AllowBothBool*/getLangOpts().AltiVec,
9819         /*AllowBoolConversions*/getLangOpts().ZVector);
9820     if (CompLHSTy) *CompLHSTy = compType;
9821     return compType;
9822   }
9823 
9824   QualType compType = UsualArithmeticConversions(
9825       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9826   if (LHS.isInvalid() || RHS.isInvalid())
9827     return QualType();
9828 
9829   // Enforce type constraints: C99 6.5.6p3.
9830 
9831   // Handle the common case first (both operands are arithmetic).
9832   if (!compType.isNull() && compType->isArithmeticType()) {
9833     if (CompLHSTy) *CompLHSTy = compType;
9834     return compType;
9835   }
9836 
9837   // Either ptr - int   or   ptr - ptr.
9838   if (LHS.get()->getType()->isAnyPointerType()) {
9839     QualType lpointee = LHS.get()->getType()->getPointeeType();
9840 
9841     // Diagnose bad cases where we step over interface counts.
9842     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9843         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9844       return QualType();
9845 
9846     // The result type of a pointer-int computation is the pointer type.
9847     if (RHS.get()->getType()->isIntegerType()) {
9848       // Subtracting from a null pointer should produce a warning.
9849       // The last argument to the diagnose call says this doesn't match the
9850       // GNU int-to-pointer idiom.
9851       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9852                                            Expr::NPC_ValueDependentIsNotNull)) {
9853         // In C++ adding zero to a null pointer is defined.
9854         Expr::EvalResult KnownVal;
9855         if (!getLangOpts().CPlusPlus ||
9856             (!RHS.get()->isValueDependent() &&
9857              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9858               KnownVal.Val.getInt() != 0))) {
9859           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9860         }
9861       }
9862 
9863       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9864         return QualType();
9865 
9866       // Check array bounds for pointer arithemtic
9867       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9868                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9869 
9870       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9871       return LHS.get()->getType();
9872     }
9873 
9874     // Handle pointer-pointer subtractions.
9875     if (const PointerType *RHSPTy
9876           = RHS.get()->getType()->getAs<PointerType>()) {
9877       QualType rpointee = RHSPTy->getPointeeType();
9878 
9879       if (getLangOpts().CPlusPlus) {
9880         // Pointee types must be the same: C++ [expr.add]
9881         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9882           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9883         }
9884       } else {
9885         // Pointee types must be compatible C99 6.5.6p3
9886         if (!Context.typesAreCompatible(
9887                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9888                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9889           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9890           return QualType();
9891         }
9892       }
9893 
9894       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9895                                                LHS.get(), RHS.get()))
9896         return QualType();
9897 
9898       // FIXME: Add warnings for nullptr - ptr.
9899 
9900       // The pointee type may have zero size.  As an extension, a structure or
9901       // union may have zero size or an array may have zero length.  In this
9902       // case subtraction does not make sense.
9903       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9904         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9905         if (ElementSize.isZero()) {
9906           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9907             << rpointee.getUnqualifiedType()
9908             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9909         }
9910       }
9911 
9912       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9913       return Context.getPointerDiffType();
9914     }
9915   }
9916 
9917   return InvalidOperands(Loc, LHS, RHS);
9918 }
9919 
9920 static bool isScopedEnumerationType(QualType T) {
9921   if (const EnumType *ET = T->getAs<EnumType>())
9922     return ET->getDecl()->isScoped();
9923   return false;
9924 }
9925 
9926 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9927                                    SourceLocation Loc, BinaryOperatorKind Opc,
9928                                    QualType LHSType) {
9929   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9930   // so skip remaining warnings as we don't want to modify values within Sema.
9931   if (S.getLangOpts().OpenCL)
9932     return;
9933 
9934   // Check right/shifter operand
9935   Expr::EvalResult RHSResult;
9936   if (RHS.get()->isValueDependent() ||
9937       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9938     return;
9939   llvm::APSInt Right = RHSResult.Val.getInt();
9940 
9941   if (Right.isNegative()) {
9942     S.DiagRuntimeBehavior(Loc, RHS.get(),
9943                           S.PDiag(diag::warn_shift_negative)
9944                             << RHS.get()->getSourceRange());
9945     return;
9946   }
9947   llvm::APInt LeftBits(Right.getBitWidth(),
9948                        S.Context.getTypeSize(LHS.get()->getType()));
9949   if (Right.uge(LeftBits)) {
9950     S.DiagRuntimeBehavior(Loc, RHS.get(),
9951                           S.PDiag(diag::warn_shift_gt_typewidth)
9952                             << RHS.get()->getSourceRange());
9953     return;
9954   }
9955   if (Opc != BO_Shl)
9956     return;
9957 
9958   // When left shifting an ICE which is signed, we can check for overflow which
9959   // according to C++ standards prior to C++2a has undefined behavior
9960   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9961   // more than the maximum value representable in the result type, so never
9962   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9963   // expression is still probably a bug.)
9964   Expr::EvalResult LHSResult;
9965   if (LHS.get()->isValueDependent() ||
9966       LHSType->hasUnsignedIntegerRepresentation() ||
9967       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9968     return;
9969   llvm::APSInt Left = LHSResult.Val.getInt();
9970 
9971   // If LHS does not have a signed type and non-negative value
9972   // then, the behavior is undefined before C++2a. Warn about it.
9973   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9974       !S.getLangOpts().CPlusPlus2a) {
9975     S.DiagRuntimeBehavior(Loc, LHS.get(),
9976                           S.PDiag(diag::warn_shift_lhs_negative)
9977                             << LHS.get()->getSourceRange());
9978     return;
9979   }
9980 
9981   llvm::APInt ResultBits =
9982       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9983   if (LeftBits.uge(ResultBits))
9984     return;
9985   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9986   Result = Result.shl(Right);
9987 
9988   // Print the bit representation of the signed integer as an unsigned
9989   // hexadecimal number.
9990   SmallString<40> HexResult;
9991   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9992 
9993   // If we are only missing a sign bit, this is less likely to result in actual
9994   // bugs -- if the result is cast back to an unsigned type, it will have the
9995   // expected value. Thus we place this behind a different warning that can be
9996   // turned off separately if needed.
9997   if (LeftBits == ResultBits - 1) {
9998     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9999         << HexResult << LHSType
10000         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10001     return;
10002   }
10003 
10004   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10005     << HexResult.str() << Result.getMinSignedBits() << LHSType
10006     << Left.getBitWidth() << LHS.get()->getSourceRange()
10007     << RHS.get()->getSourceRange();
10008 }
10009 
10010 /// Return the resulting type when a vector is shifted
10011 ///        by a scalar or vector shift amount.
10012 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10013                                  SourceLocation Loc, bool IsCompAssign) {
10014   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10015   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10016       !LHS.get()->getType()->isVectorType()) {
10017     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10018       << RHS.get()->getType() << LHS.get()->getType()
10019       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10020     return QualType();
10021   }
10022 
10023   if (!IsCompAssign) {
10024     LHS = S.UsualUnaryConversions(LHS.get());
10025     if (LHS.isInvalid()) return QualType();
10026   }
10027 
10028   RHS = S.UsualUnaryConversions(RHS.get());
10029   if (RHS.isInvalid()) return QualType();
10030 
10031   QualType LHSType = LHS.get()->getType();
10032   // Note that LHS might be a scalar because the routine calls not only in
10033   // OpenCL case.
10034   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10035   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10036 
10037   // Note that RHS might not be a vector.
10038   QualType RHSType = RHS.get()->getType();
10039   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10040   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10041 
10042   // The operands need to be integers.
10043   if (!LHSEleType->isIntegerType()) {
10044     S.Diag(Loc, diag::err_typecheck_expect_int)
10045       << LHS.get()->getType() << LHS.get()->getSourceRange();
10046     return QualType();
10047   }
10048 
10049   if (!RHSEleType->isIntegerType()) {
10050     S.Diag(Loc, diag::err_typecheck_expect_int)
10051       << RHS.get()->getType() << RHS.get()->getSourceRange();
10052     return QualType();
10053   }
10054 
10055   if (!LHSVecTy) {
10056     assert(RHSVecTy);
10057     if (IsCompAssign)
10058       return RHSType;
10059     if (LHSEleType != RHSEleType) {
10060       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10061       LHSEleType = RHSEleType;
10062     }
10063     QualType VecTy =
10064         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10065     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10066     LHSType = VecTy;
10067   } else if (RHSVecTy) {
10068     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10069     // are applied component-wise. So if RHS is a vector, then ensure
10070     // that the number of elements is the same as LHS...
10071     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10072       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10073         << LHS.get()->getType() << RHS.get()->getType()
10074         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10075       return QualType();
10076     }
10077     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10078       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10079       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10080       if (LHSBT != RHSBT &&
10081           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10082         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10083             << LHS.get()->getType() << RHS.get()->getType()
10084             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10085       }
10086     }
10087   } else {
10088     // ...else expand RHS to match the number of elements in LHS.
10089     QualType VecTy =
10090       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10091     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10092   }
10093 
10094   return LHSType;
10095 }
10096 
10097 // C99 6.5.7
10098 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10099                                   SourceLocation Loc, BinaryOperatorKind Opc,
10100                                   bool IsCompAssign) {
10101   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10102 
10103   // Vector shifts promote their scalar inputs to vector type.
10104   if (LHS.get()->getType()->isVectorType() ||
10105       RHS.get()->getType()->isVectorType()) {
10106     if (LangOpts.ZVector) {
10107       // The shift operators for the z vector extensions work basically
10108       // like general shifts, except that neither the LHS nor the RHS is
10109       // allowed to be a "vector bool".
10110       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10111         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10112           return InvalidOperands(Loc, LHS, RHS);
10113       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10114         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10115           return InvalidOperands(Loc, LHS, RHS);
10116     }
10117     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10118   }
10119 
10120   // Shifts don't perform usual arithmetic conversions, they just do integer
10121   // promotions on each operand. C99 6.5.7p3
10122 
10123   // For the LHS, do usual unary conversions, but then reset them away
10124   // if this is a compound assignment.
10125   ExprResult OldLHS = LHS;
10126   LHS = UsualUnaryConversions(LHS.get());
10127   if (LHS.isInvalid())
10128     return QualType();
10129   QualType LHSType = LHS.get()->getType();
10130   if (IsCompAssign) LHS = OldLHS;
10131 
10132   // The RHS is simpler.
10133   RHS = UsualUnaryConversions(RHS.get());
10134   if (RHS.isInvalid())
10135     return QualType();
10136   QualType RHSType = RHS.get()->getType();
10137 
10138   // C99 6.5.7p2: Each of the operands shall have integer type.
10139   if (!LHSType->hasIntegerRepresentation() ||
10140       !RHSType->hasIntegerRepresentation())
10141     return InvalidOperands(Loc, LHS, RHS);
10142 
10143   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10144   // hasIntegerRepresentation() above instead of this.
10145   if (isScopedEnumerationType(LHSType) ||
10146       isScopedEnumerationType(RHSType)) {
10147     return InvalidOperands(Loc, LHS, RHS);
10148   }
10149   // Sanity-check shift operands
10150   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10151 
10152   // "The type of the result is that of the promoted left operand."
10153   return LHSType;
10154 }
10155 
10156 /// Diagnose bad pointer comparisons.
10157 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10158                                               ExprResult &LHS, ExprResult &RHS,
10159                                               bool IsError) {
10160   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10161                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10162     << LHS.get()->getType() << RHS.get()->getType()
10163     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10164 }
10165 
10166 /// Returns false if the pointers are converted to a composite type,
10167 /// true otherwise.
10168 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10169                                            ExprResult &LHS, ExprResult &RHS) {
10170   // C++ [expr.rel]p2:
10171   //   [...] Pointer conversions (4.10) and qualification
10172   //   conversions (4.4) are performed on pointer operands (or on
10173   //   a pointer operand and a null pointer constant) to bring
10174   //   them to their composite pointer type. [...]
10175   //
10176   // C++ [expr.eq]p1 uses the same notion for (in)equality
10177   // comparisons of pointers.
10178 
10179   QualType LHSType = LHS.get()->getType();
10180   QualType RHSType = RHS.get()->getType();
10181   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10182          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10183 
10184   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10185   if (T.isNull()) {
10186     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10187         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10188       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10189     else
10190       S.InvalidOperands(Loc, LHS, RHS);
10191     return true;
10192   }
10193 
10194   return false;
10195 }
10196 
10197 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10198                                                     ExprResult &LHS,
10199                                                     ExprResult &RHS,
10200                                                     bool IsError) {
10201   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10202                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10203     << LHS.get()->getType() << RHS.get()->getType()
10204     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10205 }
10206 
10207 static bool isObjCObjectLiteral(ExprResult &E) {
10208   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10209   case Stmt::ObjCArrayLiteralClass:
10210   case Stmt::ObjCDictionaryLiteralClass:
10211   case Stmt::ObjCStringLiteralClass:
10212   case Stmt::ObjCBoxedExprClass:
10213     return true;
10214   default:
10215     // Note that ObjCBoolLiteral is NOT an object literal!
10216     return false;
10217   }
10218 }
10219 
10220 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10221   const ObjCObjectPointerType *Type =
10222     LHS->getType()->getAs<ObjCObjectPointerType>();
10223 
10224   // If this is not actually an Objective-C object, bail out.
10225   if (!Type)
10226     return false;
10227 
10228   // Get the LHS object's interface type.
10229   QualType InterfaceType = Type->getPointeeType();
10230 
10231   // If the RHS isn't an Objective-C object, bail out.
10232   if (!RHS->getType()->isObjCObjectPointerType())
10233     return false;
10234 
10235   // Try to find the -isEqual: method.
10236   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10237   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10238                                                       InterfaceType,
10239                                                       /*IsInstance=*/true);
10240   if (!Method) {
10241     if (Type->isObjCIdType()) {
10242       // For 'id', just check the global pool.
10243       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10244                                                   /*receiverId=*/true);
10245     } else {
10246       // Check protocols.
10247       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10248                                              /*IsInstance=*/true);
10249     }
10250   }
10251 
10252   if (!Method)
10253     return false;
10254 
10255   QualType T = Method->parameters()[0]->getType();
10256   if (!T->isObjCObjectPointerType())
10257     return false;
10258 
10259   QualType R = Method->getReturnType();
10260   if (!R->isScalarType())
10261     return false;
10262 
10263   return true;
10264 }
10265 
10266 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10267   FromE = FromE->IgnoreParenImpCasts();
10268   switch (FromE->getStmtClass()) {
10269     default:
10270       break;
10271     case Stmt::ObjCStringLiteralClass:
10272       // "string literal"
10273       return LK_String;
10274     case Stmt::ObjCArrayLiteralClass:
10275       // "array literal"
10276       return LK_Array;
10277     case Stmt::ObjCDictionaryLiteralClass:
10278       // "dictionary literal"
10279       return LK_Dictionary;
10280     case Stmt::BlockExprClass:
10281       return LK_Block;
10282     case Stmt::ObjCBoxedExprClass: {
10283       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10284       switch (Inner->getStmtClass()) {
10285         case Stmt::IntegerLiteralClass:
10286         case Stmt::FloatingLiteralClass:
10287         case Stmt::CharacterLiteralClass:
10288         case Stmt::ObjCBoolLiteralExprClass:
10289         case Stmt::CXXBoolLiteralExprClass:
10290           // "numeric literal"
10291           return LK_Numeric;
10292         case Stmt::ImplicitCastExprClass: {
10293           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10294           // Boolean literals can be represented by implicit casts.
10295           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10296             return LK_Numeric;
10297           break;
10298         }
10299         default:
10300           break;
10301       }
10302       return LK_Boxed;
10303     }
10304   }
10305   return LK_None;
10306 }
10307 
10308 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10309                                           ExprResult &LHS, ExprResult &RHS,
10310                                           BinaryOperator::Opcode Opc){
10311   Expr *Literal;
10312   Expr *Other;
10313   if (isObjCObjectLiteral(LHS)) {
10314     Literal = LHS.get();
10315     Other = RHS.get();
10316   } else {
10317     Literal = RHS.get();
10318     Other = LHS.get();
10319   }
10320 
10321   // Don't warn on comparisons against nil.
10322   Other = Other->IgnoreParenCasts();
10323   if (Other->isNullPointerConstant(S.getASTContext(),
10324                                    Expr::NPC_ValueDependentIsNotNull))
10325     return;
10326 
10327   // This should be kept in sync with warn_objc_literal_comparison.
10328   // LK_String should always be after the other literals, since it has its own
10329   // warning flag.
10330   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10331   assert(LiteralKind != Sema::LK_Block);
10332   if (LiteralKind == Sema::LK_None) {
10333     llvm_unreachable("Unknown Objective-C object literal kind");
10334   }
10335 
10336   if (LiteralKind == Sema::LK_String)
10337     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10338       << Literal->getSourceRange();
10339   else
10340     S.Diag(Loc, diag::warn_objc_literal_comparison)
10341       << LiteralKind << Literal->getSourceRange();
10342 
10343   if (BinaryOperator::isEqualityOp(Opc) &&
10344       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10345     SourceLocation Start = LHS.get()->getBeginLoc();
10346     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10347     CharSourceRange OpRange =
10348       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10349 
10350     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10351       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10352       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10353       << FixItHint::CreateInsertion(End, "]");
10354   }
10355 }
10356 
10357 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10358 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10359                                            ExprResult &RHS, SourceLocation Loc,
10360                                            BinaryOperatorKind Opc) {
10361   // Check that left hand side is !something.
10362   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10363   if (!UO || UO->getOpcode() != UO_LNot) return;
10364 
10365   // Only check if the right hand side is non-bool arithmetic type.
10366   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10367 
10368   // Make sure that the something in !something is not bool.
10369   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10370   if (SubExpr->isKnownToHaveBooleanValue()) return;
10371 
10372   // Emit warning.
10373   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10374   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10375       << Loc << IsBitwiseOp;
10376 
10377   // First note suggest !(x < y)
10378   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10379   SourceLocation FirstClose = RHS.get()->getEndLoc();
10380   FirstClose = S.getLocForEndOfToken(FirstClose);
10381   if (FirstClose.isInvalid())
10382     FirstOpen = SourceLocation();
10383   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10384       << IsBitwiseOp
10385       << FixItHint::CreateInsertion(FirstOpen, "(")
10386       << FixItHint::CreateInsertion(FirstClose, ")");
10387 
10388   // Second note suggests (!x) < y
10389   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10390   SourceLocation SecondClose = LHS.get()->getEndLoc();
10391   SecondClose = S.getLocForEndOfToken(SecondClose);
10392   if (SecondClose.isInvalid())
10393     SecondOpen = SourceLocation();
10394   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10395       << FixItHint::CreateInsertion(SecondOpen, "(")
10396       << FixItHint::CreateInsertion(SecondClose, ")");
10397 }
10398 
10399 // Returns true if E refers to a non-weak array.
10400 static bool checkForArray(const Expr *E) {
10401   const ValueDecl *D = nullptr;
10402   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10403     D = DR->getDecl();
10404   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10405     if (Mem->isImplicitAccess())
10406       D = Mem->getMemberDecl();
10407   }
10408   if (!D)
10409     return false;
10410   return D->getType()->isArrayType() && !D->isWeak();
10411 }
10412 
10413 /// Diagnose some forms of syntactically-obvious tautological comparison.
10414 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10415                                            Expr *LHS, Expr *RHS,
10416                                            BinaryOperatorKind Opc) {
10417   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10418   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10419 
10420   QualType LHSType = LHS->getType();
10421   QualType RHSType = RHS->getType();
10422   if (LHSType->hasFloatingRepresentation() ||
10423       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10424       S.inTemplateInstantiation())
10425     return;
10426 
10427   // Comparisons between two array types are ill-formed for operator<=>, so
10428   // we shouldn't emit any additional warnings about it.
10429   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10430     return;
10431 
10432   // For non-floating point types, check for self-comparisons of the form
10433   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10434   // often indicate logic errors in the program.
10435   //
10436   // NOTE: Don't warn about comparison expressions resulting from macro
10437   // expansion. Also don't warn about comparisons which are only self
10438   // comparisons within a template instantiation. The warnings should catch
10439   // obvious cases in the definition of the template anyways. The idea is to
10440   // warn when the typed comparison operator will always evaluate to the same
10441   // result.
10442 
10443   // Used for indexing into %select in warn_comparison_always
10444   enum {
10445     AlwaysConstant,
10446     AlwaysTrue,
10447     AlwaysFalse,
10448     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10449   };
10450 
10451   // C++2a [depr.array.comp]:
10452   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10453   //   operands of array type are deprecated.
10454   if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10455       RHSStripped->getType()->isArrayType()) {
10456     S.Diag(Loc, diag::warn_depr_array_comparison)
10457         << LHS->getSourceRange() << RHS->getSourceRange()
10458         << LHSStripped->getType() << RHSStripped->getType();
10459     // Carry on to produce the tautological comparison warning, if this
10460     // expression is potentially-evaluated, we can resolve the array to a
10461     // non-weak declaration, and so on.
10462   }
10463 
10464   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10465     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10466       unsigned Result;
10467       switch (Opc) {
10468       case BO_EQ:
10469       case BO_LE:
10470       case BO_GE:
10471         Result = AlwaysTrue;
10472         break;
10473       case BO_NE:
10474       case BO_LT:
10475       case BO_GT:
10476         Result = AlwaysFalse;
10477         break;
10478       case BO_Cmp:
10479         Result = AlwaysEqual;
10480         break;
10481       default:
10482         Result = AlwaysConstant;
10483         break;
10484       }
10485       S.DiagRuntimeBehavior(Loc, nullptr,
10486                             S.PDiag(diag::warn_comparison_always)
10487                                 << 0 /*self-comparison*/
10488                                 << Result);
10489     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10490       // What is it always going to evaluate to?
10491       unsigned Result;
10492       switch (Opc) {
10493       case BO_EQ: // e.g. array1 == array2
10494         Result = AlwaysFalse;
10495         break;
10496       case BO_NE: // e.g. array1 != array2
10497         Result = AlwaysTrue;
10498         break;
10499       default: // e.g. array1 <= array2
10500         // The best we can say is 'a constant'
10501         Result = AlwaysConstant;
10502         break;
10503       }
10504       S.DiagRuntimeBehavior(Loc, nullptr,
10505                             S.PDiag(diag::warn_comparison_always)
10506                                 << 1 /*array comparison*/
10507                                 << Result);
10508     }
10509   }
10510 
10511   if (isa<CastExpr>(LHSStripped))
10512     LHSStripped = LHSStripped->IgnoreParenCasts();
10513   if (isa<CastExpr>(RHSStripped))
10514     RHSStripped = RHSStripped->IgnoreParenCasts();
10515 
10516   // Warn about comparisons against a string constant (unless the other
10517   // operand is null); the user probably wants string comparison function.
10518   Expr *LiteralString = nullptr;
10519   Expr *LiteralStringStripped = nullptr;
10520   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10521       !RHSStripped->isNullPointerConstant(S.Context,
10522                                           Expr::NPC_ValueDependentIsNull)) {
10523     LiteralString = LHS;
10524     LiteralStringStripped = LHSStripped;
10525   } else if ((isa<StringLiteral>(RHSStripped) ||
10526               isa<ObjCEncodeExpr>(RHSStripped)) &&
10527              !LHSStripped->isNullPointerConstant(S.Context,
10528                                           Expr::NPC_ValueDependentIsNull)) {
10529     LiteralString = RHS;
10530     LiteralStringStripped = RHSStripped;
10531   }
10532 
10533   if (LiteralString) {
10534     S.DiagRuntimeBehavior(Loc, nullptr,
10535                           S.PDiag(diag::warn_stringcompare)
10536                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10537                               << LiteralString->getSourceRange());
10538   }
10539 }
10540 
10541 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10542   switch (CK) {
10543   default: {
10544 #ifndef NDEBUG
10545     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10546                  << "\n";
10547 #endif
10548     llvm_unreachable("unhandled cast kind");
10549   }
10550   case CK_UserDefinedConversion:
10551     return ICK_Identity;
10552   case CK_LValueToRValue:
10553     return ICK_Lvalue_To_Rvalue;
10554   case CK_ArrayToPointerDecay:
10555     return ICK_Array_To_Pointer;
10556   case CK_FunctionToPointerDecay:
10557     return ICK_Function_To_Pointer;
10558   case CK_IntegralCast:
10559     return ICK_Integral_Conversion;
10560   case CK_FloatingCast:
10561     return ICK_Floating_Conversion;
10562   case CK_IntegralToFloating:
10563   case CK_FloatingToIntegral:
10564     return ICK_Floating_Integral;
10565   case CK_IntegralComplexCast:
10566   case CK_FloatingComplexCast:
10567   case CK_FloatingComplexToIntegralComplex:
10568   case CK_IntegralComplexToFloatingComplex:
10569     return ICK_Complex_Conversion;
10570   case CK_FloatingComplexToReal:
10571   case CK_FloatingRealToComplex:
10572   case CK_IntegralComplexToReal:
10573   case CK_IntegralRealToComplex:
10574     return ICK_Complex_Real;
10575   }
10576 }
10577 
10578 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10579                                              QualType FromType,
10580                                              SourceLocation Loc) {
10581   // Check for a narrowing implicit conversion.
10582   StandardConversionSequence SCS;
10583   SCS.setAsIdentityConversion();
10584   SCS.setToType(0, FromType);
10585   SCS.setToType(1, ToType);
10586   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10587     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10588 
10589   APValue PreNarrowingValue;
10590   QualType PreNarrowingType;
10591   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10592                                PreNarrowingType,
10593                                /*IgnoreFloatToIntegralConversion*/ true)) {
10594   case NK_Dependent_Narrowing:
10595     // Implicit conversion to a narrower type, but the expression is
10596     // value-dependent so we can't tell whether it's actually narrowing.
10597   case NK_Not_Narrowing:
10598     return false;
10599 
10600   case NK_Constant_Narrowing:
10601     // Implicit conversion to a narrower type, and the value is not a constant
10602     // expression.
10603     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10604         << /*Constant*/ 1
10605         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10606     return true;
10607 
10608   case NK_Variable_Narrowing:
10609     // Implicit conversion to a narrower type, and the value is not a constant
10610     // expression.
10611   case NK_Type_Narrowing:
10612     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10613         << /*Constant*/ 0 << FromType << ToType;
10614     // TODO: It's not a constant expression, but what if the user intended it
10615     // to be? Can we produce notes to help them figure out why it isn't?
10616     return true;
10617   }
10618   llvm_unreachable("unhandled case in switch");
10619 }
10620 
10621 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10622                                                          ExprResult &LHS,
10623                                                          ExprResult &RHS,
10624                                                          SourceLocation Loc) {
10625   QualType LHSType = LHS.get()->getType();
10626   QualType RHSType = RHS.get()->getType();
10627   // Dig out the original argument type and expression before implicit casts
10628   // were applied. These are the types/expressions we need to check the
10629   // [expr.spaceship] requirements against.
10630   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10631   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10632   QualType LHSStrippedType = LHSStripped.get()->getType();
10633   QualType RHSStrippedType = RHSStripped.get()->getType();
10634 
10635   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10636   // other is not, the program is ill-formed.
10637   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10638     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10639     return QualType();
10640   }
10641 
10642   // FIXME: Consider combining this with checkEnumArithmeticConversions.
10643   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10644                     RHSStrippedType->isEnumeralType();
10645   if (NumEnumArgs == 1) {
10646     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10647     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10648     if (OtherTy->hasFloatingRepresentation()) {
10649       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10650       return QualType();
10651     }
10652   }
10653   if (NumEnumArgs == 2) {
10654     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10655     // type E, the operator yields the result of converting the operands
10656     // to the underlying type of E and applying <=> to the converted operands.
10657     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10658       S.InvalidOperands(Loc, LHS, RHS);
10659       return QualType();
10660     }
10661     QualType IntType =
10662         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10663     assert(IntType->isArithmeticType());
10664 
10665     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10666     // promote the boolean type, and all other promotable integer types, to
10667     // avoid this.
10668     if (IntType->isPromotableIntegerType())
10669       IntType = S.Context.getPromotedIntegerType(IntType);
10670 
10671     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10672     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10673     LHSType = RHSType = IntType;
10674   }
10675 
10676   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10677   // usual arithmetic conversions are applied to the operands.
10678   QualType Type =
10679       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10680   if (LHS.isInvalid() || RHS.isInvalid())
10681     return QualType();
10682   if (Type.isNull())
10683     return S.InvalidOperands(Loc, LHS, RHS);
10684 
10685   Optional<ComparisonCategoryType> CCT =
10686       getComparisonCategoryForBuiltinCmp(Type);
10687   if (!CCT)
10688     return S.InvalidOperands(Loc, LHS, RHS);
10689 
10690   bool HasNarrowing = checkThreeWayNarrowingConversion(
10691       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10692   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10693                                                    RHS.get()->getBeginLoc());
10694   if (HasNarrowing)
10695     return QualType();
10696 
10697   assert(!Type.isNull() && "composite type for <=> has not been set");
10698 
10699   return S.CheckComparisonCategoryType(
10700       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
10701 }
10702 
10703 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10704                                                  ExprResult &RHS,
10705                                                  SourceLocation Loc,
10706                                                  BinaryOperatorKind Opc) {
10707   if (Opc == BO_Cmp)
10708     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10709 
10710   // C99 6.5.8p3 / C99 6.5.9p4
10711   QualType Type =
10712       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10713   if (LHS.isInvalid() || RHS.isInvalid())
10714     return QualType();
10715   if (Type.isNull())
10716     return S.InvalidOperands(Loc, LHS, RHS);
10717   assert(Type->isArithmeticType() || Type->isEnumeralType());
10718 
10719   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10720     return S.InvalidOperands(Loc, LHS, RHS);
10721 
10722   // Check for comparisons of floating point operands using != and ==.
10723   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10724     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10725 
10726   // The result of comparisons is 'bool' in C++, 'int' in C.
10727   return S.Context.getLogicalOperationType();
10728 }
10729 
10730 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10731   if (!NullE.get()->getType()->isAnyPointerType())
10732     return;
10733   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10734   if (!E.get()->getType()->isAnyPointerType() &&
10735       E.get()->isNullPointerConstant(Context,
10736                                      Expr::NPC_ValueDependentIsNotNull) ==
10737         Expr::NPCK_ZeroExpression) {
10738     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10739       if (CL->getValue() == 0)
10740         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10741             << NullValue
10742             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10743                                             NullValue ? "NULL" : "(void *)0");
10744     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10745         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10746         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10747         if (T == Context.CharTy)
10748           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10749               << NullValue
10750               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10751                                               NullValue ? "NULL" : "(void *)0");
10752       }
10753   }
10754 }
10755 
10756 // C99 6.5.8, C++ [expr.rel]
10757 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10758                                     SourceLocation Loc,
10759                                     BinaryOperatorKind Opc) {
10760   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10761   bool IsThreeWay = Opc == BO_Cmp;
10762   bool IsOrdered = IsRelational || IsThreeWay;
10763   auto IsAnyPointerType = [](ExprResult E) {
10764     QualType Ty = E.get()->getType();
10765     return Ty->isPointerType() || Ty->isMemberPointerType();
10766   };
10767 
10768   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10769   // type, array-to-pointer, ..., conversions are performed on both operands to
10770   // bring them to their composite type.
10771   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10772   // any type-related checks.
10773   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10774     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10775     if (LHS.isInvalid())
10776       return QualType();
10777     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10778     if (RHS.isInvalid())
10779       return QualType();
10780   } else {
10781     LHS = DefaultLvalueConversion(LHS.get());
10782     if (LHS.isInvalid())
10783       return QualType();
10784     RHS = DefaultLvalueConversion(RHS.get());
10785     if (RHS.isInvalid())
10786       return QualType();
10787   }
10788 
10789   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10790   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10791     CheckPtrComparisonWithNullChar(LHS, RHS);
10792     CheckPtrComparisonWithNullChar(RHS, LHS);
10793   }
10794 
10795   // Handle vector comparisons separately.
10796   if (LHS.get()->getType()->isVectorType() ||
10797       RHS.get()->getType()->isVectorType())
10798     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10799 
10800   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10801   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10802 
10803   QualType LHSType = LHS.get()->getType();
10804   QualType RHSType = RHS.get()->getType();
10805   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10806       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10807     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10808 
10809   const Expr::NullPointerConstantKind LHSNullKind =
10810       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10811   const Expr::NullPointerConstantKind RHSNullKind =
10812       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10813   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10814   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10815 
10816   auto computeResultTy = [&]() {
10817     if (Opc != BO_Cmp)
10818       return Context.getLogicalOperationType();
10819     assert(getLangOpts().CPlusPlus);
10820     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10821 
10822     QualType CompositeTy = LHS.get()->getType();
10823     assert(!CompositeTy->isReferenceType());
10824 
10825     Optional<ComparisonCategoryType> CCT =
10826         getComparisonCategoryForBuiltinCmp(CompositeTy);
10827     if (!CCT)
10828       return InvalidOperands(Loc, LHS, RHS);
10829 
10830     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
10831       // P0946R0: Comparisons between a null pointer constant and an object
10832       // pointer result in std::strong_equality, which is ill-formed under
10833       // P1959R0.
10834       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
10835           << (LHSIsNull ? LHS.get()->getSourceRange()
10836                         : RHS.get()->getSourceRange());
10837       return QualType();
10838     }
10839 
10840     return CheckComparisonCategoryType(
10841         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
10842   };
10843 
10844   if (!IsOrdered && LHSIsNull != RHSIsNull) {
10845     bool IsEquality = Opc == BO_EQ;
10846     if (RHSIsNull)
10847       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10848                                    RHS.get()->getSourceRange());
10849     else
10850       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10851                                    LHS.get()->getSourceRange());
10852   }
10853 
10854   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10855       (RHSType->isIntegerType() && !RHSIsNull)) {
10856     // Skip normal pointer conversion checks in this case; we have better
10857     // diagnostics for this below.
10858   } else if (getLangOpts().CPlusPlus) {
10859     // Equality comparison of a function pointer to a void pointer is invalid,
10860     // but we allow it as an extension.
10861     // FIXME: If we really want to allow this, should it be part of composite
10862     // pointer type computation so it works in conditionals too?
10863     if (!IsOrdered &&
10864         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10865          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10866       // This is a gcc extension compatibility comparison.
10867       // In a SFINAE context, we treat this as a hard error to maintain
10868       // conformance with the C++ standard.
10869       diagnoseFunctionPointerToVoidComparison(
10870           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10871 
10872       if (isSFINAEContext())
10873         return QualType();
10874 
10875       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10876       return computeResultTy();
10877     }
10878 
10879     // C++ [expr.eq]p2:
10880     //   If at least one operand is a pointer [...] bring them to their
10881     //   composite pointer type.
10882     // C++ [expr.spaceship]p6
10883     //  If at least one of the operands is of pointer type, [...] bring them
10884     //  to their composite pointer type.
10885     // C++ [expr.rel]p2:
10886     //   If both operands are pointers, [...] bring them to their composite
10887     //   pointer type.
10888     // For <=>, the only valid non-pointer types are arrays and functions, and
10889     // we already decayed those, so this is really the same as the relational
10890     // comparison rule.
10891     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10892             (IsOrdered ? 2 : 1) &&
10893         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10894                                          RHSType->isObjCObjectPointerType()))) {
10895       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10896         return QualType();
10897       return computeResultTy();
10898     }
10899   } else if (LHSType->isPointerType() &&
10900              RHSType->isPointerType()) { // C99 6.5.8p2
10901     // All of the following pointer-related warnings are GCC extensions, except
10902     // when handling null pointer constants.
10903     QualType LCanPointeeTy =
10904       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10905     QualType RCanPointeeTy =
10906       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10907 
10908     // C99 6.5.9p2 and C99 6.5.8p2
10909     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10910                                    RCanPointeeTy.getUnqualifiedType())) {
10911       // Valid unless a relational comparison of function pointers
10912       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10913         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10914           << LHSType << RHSType << LHS.get()->getSourceRange()
10915           << RHS.get()->getSourceRange();
10916       }
10917     } else if (!IsRelational &&
10918                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10919       // Valid unless comparison between non-null pointer and function pointer
10920       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10921           && !LHSIsNull && !RHSIsNull)
10922         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10923                                                 /*isError*/false);
10924     } else {
10925       // Invalid
10926       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10927     }
10928     if (LCanPointeeTy != RCanPointeeTy) {
10929       // Treat NULL constant as a special case in OpenCL.
10930       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10931         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10932         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10933           Diag(Loc,
10934                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10935               << LHSType << RHSType << 0 /* comparison */
10936               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10937         }
10938       }
10939       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10940       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10941       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10942                                                : CK_BitCast;
10943       if (LHSIsNull && !RHSIsNull)
10944         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10945       else
10946         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10947     }
10948     return computeResultTy();
10949   }
10950 
10951   if (getLangOpts().CPlusPlus) {
10952     // C++ [expr.eq]p4:
10953     //   Two operands of type std::nullptr_t or one operand of type
10954     //   std::nullptr_t and the other a null pointer constant compare equal.
10955     if (!IsOrdered && LHSIsNull && RHSIsNull) {
10956       if (LHSType->isNullPtrType()) {
10957         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10958         return computeResultTy();
10959       }
10960       if (RHSType->isNullPtrType()) {
10961         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10962         return computeResultTy();
10963       }
10964     }
10965 
10966     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10967     // These aren't covered by the composite pointer type rules.
10968     if (!IsOrdered && RHSType->isNullPtrType() &&
10969         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10970       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10971       return computeResultTy();
10972     }
10973     if (!IsOrdered && LHSType->isNullPtrType() &&
10974         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10975       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10976       return computeResultTy();
10977     }
10978 
10979     if (IsRelational &&
10980         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10981          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10982       // HACK: Relational comparison of nullptr_t against a pointer type is
10983       // invalid per DR583, but we allow it within std::less<> and friends,
10984       // since otherwise common uses of it break.
10985       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10986       // friends to have std::nullptr_t overload candidates.
10987       DeclContext *DC = CurContext;
10988       if (isa<FunctionDecl>(DC))
10989         DC = DC->getParent();
10990       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10991         if (CTSD->isInStdNamespace() &&
10992             llvm::StringSwitch<bool>(CTSD->getName())
10993                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10994                 .Default(false)) {
10995           if (RHSType->isNullPtrType())
10996             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10997           else
10998             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10999           return computeResultTy();
11000         }
11001       }
11002     }
11003 
11004     // C++ [expr.eq]p2:
11005     //   If at least one operand is a pointer to member, [...] bring them to
11006     //   their composite pointer type.
11007     if (!IsOrdered &&
11008         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11009       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11010         return QualType();
11011       else
11012         return computeResultTy();
11013     }
11014   }
11015 
11016   // Handle block pointer types.
11017   if (!IsOrdered && LHSType->isBlockPointerType() &&
11018       RHSType->isBlockPointerType()) {
11019     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11020     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11021 
11022     if (!LHSIsNull && !RHSIsNull &&
11023         !Context.typesAreCompatible(lpointee, rpointee)) {
11024       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11025         << LHSType << RHSType << LHS.get()->getSourceRange()
11026         << RHS.get()->getSourceRange();
11027     }
11028     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11029     return computeResultTy();
11030   }
11031 
11032   // Allow block pointers to be compared with null pointer constants.
11033   if (!IsOrdered
11034       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11035           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11036     if (!LHSIsNull && !RHSIsNull) {
11037       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11038              ->getPointeeType()->isVoidType())
11039             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11040                 ->getPointeeType()->isVoidType())))
11041         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11042           << LHSType << RHSType << LHS.get()->getSourceRange()
11043           << RHS.get()->getSourceRange();
11044     }
11045     if (LHSIsNull && !RHSIsNull)
11046       LHS = ImpCastExprToType(LHS.get(), RHSType,
11047                               RHSType->isPointerType() ? CK_BitCast
11048                                 : CK_AnyPointerToBlockPointerCast);
11049     else
11050       RHS = ImpCastExprToType(RHS.get(), LHSType,
11051                               LHSType->isPointerType() ? CK_BitCast
11052                                 : CK_AnyPointerToBlockPointerCast);
11053     return computeResultTy();
11054   }
11055 
11056   if (LHSType->isObjCObjectPointerType() ||
11057       RHSType->isObjCObjectPointerType()) {
11058     const PointerType *LPT = LHSType->getAs<PointerType>();
11059     const PointerType *RPT = RHSType->getAs<PointerType>();
11060     if (LPT || RPT) {
11061       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11062       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11063 
11064       if (!LPtrToVoid && !RPtrToVoid &&
11065           !Context.typesAreCompatible(LHSType, RHSType)) {
11066         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11067                                           /*isError*/false);
11068       }
11069       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11070       // the RHS, but we have test coverage for this behavior.
11071       // FIXME: Consider using convertPointersToCompositeType in C++.
11072       if (LHSIsNull && !RHSIsNull) {
11073         Expr *E = LHS.get();
11074         if (getLangOpts().ObjCAutoRefCount)
11075           CheckObjCConversion(SourceRange(), RHSType, E,
11076                               CCK_ImplicitConversion);
11077         LHS = ImpCastExprToType(E, RHSType,
11078                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11079       }
11080       else {
11081         Expr *E = RHS.get();
11082         if (getLangOpts().ObjCAutoRefCount)
11083           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11084                               /*Diagnose=*/true,
11085                               /*DiagnoseCFAudited=*/false, Opc);
11086         RHS = ImpCastExprToType(E, LHSType,
11087                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11088       }
11089       return computeResultTy();
11090     }
11091     if (LHSType->isObjCObjectPointerType() &&
11092         RHSType->isObjCObjectPointerType()) {
11093       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11094         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11095                                           /*isError*/false);
11096       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11097         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11098 
11099       if (LHSIsNull && !RHSIsNull)
11100         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11101       else
11102         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11103       return computeResultTy();
11104     }
11105 
11106     if (!IsOrdered && LHSType->isBlockPointerType() &&
11107         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11108       LHS = ImpCastExprToType(LHS.get(), RHSType,
11109                               CK_BlockPointerToObjCPointerCast);
11110       return computeResultTy();
11111     } else if (!IsOrdered &&
11112                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11113                RHSType->isBlockPointerType()) {
11114       RHS = ImpCastExprToType(RHS.get(), LHSType,
11115                               CK_BlockPointerToObjCPointerCast);
11116       return computeResultTy();
11117     }
11118   }
11119   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11120       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11121     unsigned DiagID = 0;
11122     bool isError = false;
11123     if (LangOpts.DebuggerSupport) {
11124       // Under a debugger, allow the comparison of pointers to integers,
11125       // since users tend to want to compare addresses.
11126     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11127                (RHSIsNull && RHSType->isIntegerType())) {
11128       if (IsOrdered) {
11129         isError = getLangOpts().CPlusPlus;
11130         DiagID =
11131           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11132                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11133       }
11134     } else if (getLangOpts().CPlusPlus) {
11135       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11136       isError = true;
11137     } else if (IsOrdered)
11138       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11139     else
11140       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11141 
11142     if (DiagID) {
11143       Diag(Loc, DiagID)
11144         << LHSType << RHSType << LHS.get()->getSourceRange()
11145         << RHS.get()->getSourceRange();
11146       if (isError)
11147         return QualType();
11148     }
11149 
11150     if (LHSType->isIntegerType())
11151       LHS = ImpCastExprToType(LHS.get(), RHSType,
11152                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11153     else
11154       RHS = ImpCastExprToType(RHS.get(), LHSType,
11155                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11156     return computeResultTy();
11157   }
11158 
11159   // Handle block pointers.
11160   if (!IsOrdered && RHSIsNull
11161       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11162     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11163     return computeResultTy();
11164   }
11165   if (!IsOrdered && LHSIsNull
11166       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11167     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11168     return computeResultTy();
11169   }
11170 
11171   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11172     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11173       return computeResultTy();
11174     }
11175 
11176     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11177       return computeResultTy();
11178     }
11179 
11180     if (LHSIsNull && RHSType->isQueueT()) {
11181       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11182       return computeResultTy();
11183     }
11184 
11185     if (LHSType->isQueueT() && RHSIsNull) {
11186       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11187       return computeResultTy();
11188     }
11189   }
11190 
11191   return InvalidOperands(Loc, LHS, RHS);
11192 }
11193 
11194 // Return a signed ext_vector_type that is of identical size and number of
11195 // elements. For floating point vectors, return an integer type of identical
11196 // size and number of elements. In the non ext_vector_type case, search from
11197 // the largest type to the smallest type to avoid cases where long long == long,
11198 // where long gets picked over long long.
11199 QualType Sema::GetSignedVectorType(QualType V) {
11200   const VectorType *VTy = V->castAs<VectorType>();
11201   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11202 
11203   if (isa<ExtVectorType>(VTy)) {
11204     if (TypeSize == Context.getTypeSize(Context.CharTy))
11205       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11206     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11207       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11208     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11209       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11210     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11211       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11212     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11213            "Unhandled vector element size in vector compare");
11214     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11215   }
11216 
11217   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11218     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11219                                  VectorType::GenericVector);
11220   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11221     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11222                                  VectorType::GenericVector);
11223   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11224     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11225                                  VectorType::GenericVector);
11226   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11227     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11228                                  VectorType::GenericVector);
11229   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11230          "Unhandled vector element size in vector compare");
11231   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11232                                VectorType::GenericVector);
11233 }
11234 
11235 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11236 /// operates on extended vector types.  Instead of producing an IntTy result,
11237 /// like a scalar comparison, a vector comparison produces a vector of integer
11238 /// types.
11239 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11240                                           SourceLocation Loc,
11241                                           BinaryOperatorKind Opc) {
11242   if (Opc == BO_Cmp) {
11243     Diag(Loc, diag::err_three_way_vector_comparison);
11244     return QualType();
11245   }
11246 
11247   // Check to make sure we're operating on vectors of the same type and width,
11248   // Allowing one side to be a scalar of element type.
11249   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11250                               /*AllowBothBool*/true,
11251                               /*AllowBoolConversions*/getLangOpts().ZVector);
11252   if (vType.isNull())
11253     return vType;
11254 
11255   QualType LHSType = LHS.get()->getType();
11256 
11257   // If AltiVec, the comparison results in a numeric type, i.e.
11258   // bool for C++, int for C
11259   if (getLangOpts().AltiVec &&
11260       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11261     return Context.getLogicalOperationType();
11262 
11263   // For non-floating point types, check for self-comparisons of the form
11264   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11265   // often indicate logic errors in the program.
11266   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11267 
11268   // Check for comparisons of floating point operands using != and ==.
11269   if (BinaryOperator::isEqualityOp(Opc) &&
11270       LHSType->hasFloatingRepresentation()) {
11271     assert(RHS.get()->getType()->hasFloatingRepresentation());
11272     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11273   }
11274 
11275   // Return a signed type for the vector.
11276   return GetSignedVectorType(vType);
11277 }
11278 
11279 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11280                                     const ExprResult &XorRHS,
11281                                     const SourceLocation Loc) {
11282   // Do not diagnose macros.
11283   if (Loc.isMacroID())
11284     return;
11285 
11286   bool Negative = false;
11287   bool ExplicitPlus = false;
11288   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11289   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11290 
11291   if (!LHSInt)
11292     return;
11293   if (!RHSInt) {
11294     // Check negative literals.
11295     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11296       UnaryOperatorKind Opc = UO->getOpcode();
11297       if (Opc != UO_Minus && Opc != UO_Plus)
11298         return;
11299       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11300       if (!RHSInt)
11301         return;
11302       Negative = (Opc == UO_Minus);
11303       ExplicitPlus = !Negative;
11304     } else {
11305       return;
11306     }
11307   }
11308 
11309   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11310   llvm::APInt RightSideValue = RHSInt->getValue();
11311   if (LeftSideValue != 2 && LeftSideValue != 10)
11312     return;
11313 
11314   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11315     return;
11316 
11317   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11318       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11319   llvm::StringRef ExprStr =
11320       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11321 
11322   CharSourceRange XorRange =
11323       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11324   llvm::StringRef XorStr =
11325       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11326   // Do not diagnose if xor keyword/macro is used.
11327   if (XorStr == "xor")
11328     return;
11329 
11330   std::string LHSStr = Lexer::getSourceText(
11331       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11332       S.getSourceManager(), S.getLangOpts());
11333   std::string RHSStr = Lexer::getSourceText(
11334       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11335       S.getSourceManager(), S.getLangOpts());
11336 
11337   if (Negative) {
11338     RightSideValue = -RightSideValue;
11339     RHSStr = "-" + RHSStr;
11340   } else if (ExplicitPlus) {
11341     RHSStr = "+" + RHSStr;
11342   }
11343 
11344   StringRef LHSStrRef = LHSStr;
11345   StringRef RHSStrRef = RHSStr;
11346   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11347   // literals.
11348   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11349       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11350       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11351       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11352       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11353       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11354       LHSStrRef.find('\'') != StringRef::npos ||
11355       RHSStrRef.find('\'') != StringRef::npos)
11356     return;
11357 
11358   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11359   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11360   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11361   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11362     std::string SuggestedExpr = "1 << " + RHSStr;
11363     bool Overflow = false;
11364     llvm::APInt One = (LeftSideValue - 1);
11365     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11366     if (Overflow) {
11367       if (RightSideIntValue < 64)
11368         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11369             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11370             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11371       else if (RightSideIntValue == 64)
11372         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11373       else
11374         return;
11375     } else {
11376       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11377           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11378           << PowValue.toString(10, true)
11379           << FixItHint::CreateReplacement(
11380                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11381     }
11382 
11383     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11384   } else if (LeftSideValue == 10) {
11385     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11386     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11387         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11388         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11389     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11390   }
11391 }
11392 
11393 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11394                                           SourceLocation Loc) {
11395   // Ensure that either both operands are of the same vector type, or
11396   // one operand is of a vector type and the other is of its element type.
11397   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11398                                        /*AllowBothBool*/true,
11399                                        /*AllowBoolConversions*/false);
11400   if (vType.isNull())
11401     return InvalidOperands(Loc, LHS, RHS);
11402   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11403       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11404     return InvalidOperands(Loc, LHS, RHS);
11405   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11406   //        usage of the logical operators && and || with vectors in C. This
11407   //        check could be notionally dropped.
11408   if (!getLangOpts().CPlusPlus &&
11409       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11410     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11411 
11412   return GetSignedVectorType(LHS.get()->getType());
11413 }
11414 
11415 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11416                                            SourceLocation Loc,
11417                                            BinaryOperatorKind Opc) {
11418   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11419 
11420   bool IsCompAssign =
11421       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11422 
11423   if (LHS.get()->getType()->isVectorType() ||
11424       RHS.get()->getType()->isVectorType()) {
11425     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11426         RHS.get()->getType()->hasIntegerRepresentation())
11427       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11428                         /*AllowBothBool*/true,
11429                         /*AllowBoolConversions*/getLangOpts().ZVector);
11430     return InvalidOperands(Loc, LHS, RHS);
11431   }
11432 
11433   if (Opc == BO_And)
11434     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11435 
11436   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11437       RHS.get()->getType()->hasFloatingRepresentation())
11438     return InvalidOperands(Loc, LHS, RHS);
11439 
11440   ExprResult LHSResult = LHS, RHSResult = RHS;
11441   QualType compType = UsualArithmeticConversions(
11442       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11443   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11444     return QualType();
11445   LHS = LHSResult.get();
11446   RHS = RHSResult.get();
11447 
11448   if (Opc == BO_Xor)
11449     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11450 
11451   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11452     return compType;
11453   return InvalidOperands(Loc, LHS, RHS);
11454 }
11455 
11456 // C99 6.5.[13,14]
11457 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11458                                            SourceLocation Loc,
11459                                            BinaryOperatorKind Opc) {
11460   // Check vector operands differently.
11461   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11462     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11463 
11464   bool EnumConstantInBoolContext = false;
11465   for (const ExprResult &HS : {LHS, RHS}) {
11466     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11467       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11468       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11469         EnumConstantInBoolContext = true;
11470     }
11471   }
11472 
11473   if (EnumConstantInBoolContext)
11474     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11475 
11476   // Diagnose cases where the user write a logical and/or but probably meant a
11477   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11478   // is a constant.
11479   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11480       !LHS.get()->getType()->isBooleanType() &&
11481       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11482       // Don't warn in macros or template instantiations.
11483       !Loc.isMacroID() && !inTemplateInstantiation()) {
11484     // If the RHS can be constant folded, and if it constant folds to something
11485     // that isn't 0 or 1 (which indicate a potential logical operation that
11486     // happened to fold to true/false) then warn.
11487     // Parens on the RHS are ignored.
11488     Expr::EvalResult EVResult;
11489     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11490       llvm::APSInt Result = EVResult.Val.getInt();
11491       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11492            !RHS.get()->getExprLoc().isMacroID()) ||
11493           (Result != 0 && Result != 1)) {
11494         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11495           << RHS.get()->getSourceRange()
11496           << (Opc == BO_LAnd ? "&&" : "||");
11497         // Suggest replacing the logical operator with the bitwise version
11498         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11499             << (Opc == BO_LAnd ? "&" : "|")
11500             << FixItHint::CreateReplacement(SourceRange(
11501                                                  Loc, getLocForEndOfToken(Loc)),
11502                                             Opc == BO_LAnd ? "&" : "|");
11503         if (Opc == BO_LAnd)
11504           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11505           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11506               << FixItHint::CreateRemoval(
11507                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11508                                  RHS.get()->getEndLoc()));
11509       }
11510     }
11511   }
11512 
11513   if (!Context.getLangOpts().CPlusPlus) {
11514     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11515     // not operate on the built-in scalar and vector float types.
11516     if (Context.getLangOpts().OpenCL &&
11517         Context.getLangOpts().OpenCLVersion < 120) {
11518       if (LHS.get()->getType()->isFloatingType() ||
11519           RHS.get()->getType()->isFloatingType())
11520         return InvalidOperands(Loc, LHS, RHS);
11521     }
11522 
11523     LHS = UsualUnaryConversions(LHS.get());
11524     if (LHS.isInvalid())
11525       return QualType();
11526 
11527     RHS = UsualUnaryConversions(RHS.get());
11528     if (RHS.isInvalid())
11529       return QualType();
11530 
11531     if (!LHS.get()->getType()->isScalarType() ||
11532         !RHS.get()->getType()->isScalarType())
11533       return InvalidOperands(Loc, LHS, RHS);
11534 
11535     return Context.IntTy;
11536   }
11537 
11538   // The following is safe because we only use this method for
11539   // non-overloadable operands.
11540 
11541   // C++ [expr.log.and]p1
11542   // C++ [expr.log.or]p1
11543   // The operands are both contextually converted to type bool.
11544   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11545   if (LHSRes.isInvalid())
11546     return InvalidOperands(Loc, LHS, RHS);
11547   LHS = LHSRes;
11548 
11549   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11550   if (RHSRes.isInvalid())
11551     return InvalidOperands(Loc, LHS, RHS);
11552   RHS = RHSRes;
11553 
11554   // C++ [expr.log.and]p2
11555   // C++ [expr.log.or]p2
11556   // The result is a bool.
11557   return Context.BoolTy;
11558 }
11559 
11560 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11561   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11562   if (!ME) return false;
11563   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11564   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11565       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11566   if (!Base) return false;
11567   return Base->getMethodDecl() != nullptr;
11568 }
11569 
11570 /// Is the given expression (which must be 'const') a reference to a
11571 /// variable which was originally non-const, but which has become
11572 /// 'const' due to being captured within a block?
11573 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11574 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11575   assert(E->isLValue() && E->getType().isConstQualified());
11576   E = E->IgnoreParens();
11577 
11578   // Must be a reference to a declaration from an enclosing scope.
11579   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11580   if (!DRE) return NCCK_None;
11581   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11582 
11583   // The declaration must be a variable which is not declared 'const'.
11584   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11585   if (!var) return NCCK_None;
11586   if (var->getType().isConstQualified()) return NCCK_None;
11587   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11588 
11589   // Decide whether the first capture was for a block or a lambda.
11590   DeclContext *DC = S.CurContext, *Prev = nullptr;
11591   // Decide whether the first capture was for a block or a lambda.
11592   while (DC) {
11593     // For init-capture, it is possible that the variable belongs to the
11594     // template pattern of the current context.
11595     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11596       if (var->isInitCapture() &&
11597           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11598         break;
11599     if (DC == var->getDeclContext())
11600       break;
11601     Prev = DC;
11602     DC = DC->getParent();
11603   }
11604   // Unless we have an init-capture, we've gone one step too far.
11605   if (!var->isInitCapture())
11606     DC = Prev;
11607   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11608 }
11609 
11610 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11611   Ty = Ty.getNonReferenceType();
11612   if (IsDereference && Ty->isPointerType())
11613     Ty = Ty->getPointeeType();
11614   return !Ty.isConstQualified();
11615 }
11616 
11617 // Update err_typecheck_assign_const and note_typecheck_assign_const
11618 // when this enum is changed.
11619 enum {
11620   ConstFunction,
11621   ConstVariable,
11622   ConstMember,
11623   ConstMethod,
11624   NestedConstMember,
11625   ConstUnknown,  // Keep as last element
11626 };
11627 
11628 /// Emit the "read-only variable not assignable" error and print notes to give
11629 /// more information about why the variable is not assignable, such as pointing
11630 /// to the declaration of a const variable, showing that a method is const, or
11631 /// that the function is returning a const reference.
11632 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11633                                     SourceLocation Loc) {
11634   SourceRange ExprRange = E->getSourceRange();
11635 
11636   // Only emit one error on the first const found.  All other consts will emit
11637   // a note to the error.
11638   bool DiagnosticEmitted = false;
11639 
11640   // Track if the current expression is the result of a dereference, and if the
11641   // next checked expression is the result of a dereference.
11642   bool IsDereference = false;
11643   bool NextIsDereference = false;
11644 
11645   // Loop to process MemberExpr chains.
11646   while (true) {
11647     IsDereference = NextIsDereference;
11648 
11649     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11650     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11651       NextIsDereference = ME->isArrow();
11652       const ValueDecl *VD = ME->getMemberDecl();
11653       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11654         // Mutable fields can be modified even if the class is const.
11655         if (Field->isMutable()) {
11656           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11657           break;
11658         }
11659 
11660         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11661           if (!DiagnosticEmitted) {
11662             S.Diag(Loc, diag::err_typecheck_assign_const)
11663                 << ExprRange << ConstMember << false /*static*/ << Field
11664                 << Field->getType();
11665             DiagnosticEmitted = true;
11666           }
11667           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11668               << ConstMember << false /*static*/ << Field << Field->getType()
11669               << Field->getSourceRange();
11670         }
11671         E = ME->getBase();
11672         continue;
11673       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11674         if (VDecl->getType().isConstQualified()) {
11675           if (!DiagnosticEmitted) {
11676             S.Diag(Loc, diag::err_typecheck_assign_const)
11677                 << ExprRange << ConstMember << true /*static*/ << VDecl
11678                 << VDecl->getType();
11679             DiagnosticEmitted = true;
11680           }
11681           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11682               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11683               << VDecl->getSourceRange();
11684         }
11685         // Static fields do not inherit constness from parents.
11686         break;
11687       }
11688       break; // End MemberExpr
11689     } else if (const ArraySubscriptExpr *ASE =
11690                    dyn_cast<ArraySubscriptExpr>(E)) {
11691       E = ASE->getBase()->IgnoreParenImpCasts();
11692       continue;
11693     } else if (const ExtVectorElementExpr *EVE =
11694                    dyn_cast<ExtVectorElementExpr>(E)) {
11695       E = EVE->getBase()->IgnoreParenImpCasts();
11696       continue;
11697     }
11698     break;
11699   }
11700 
11701   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11702     // Function calls
11703     const FunctionDecl *FD = CE->getDirectCallee();
11704     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11705       if (!DiagnosticEmitted) {
11706         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11707                                                       << ConstFunction << FD;
11708         DiagnosticEmitted = true;
11709       }
11710       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11711              diag::note_typecheck_assign_const)
11712           << ConstFunction << FD << FD->getReturnType()
11713           << FD->getReturnTypeSourceRange();
11714     }
11715   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11716     // Point to variable declaration.
11717     if (const ValueDecl *VD = DRE->getDecl()) {
11718       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11719         if (!DiagnosticEmitted) {
11720           S.Diag(Loc, diag::err_typecheck_assign_const)
11721               << ExprRange << ConstVariable << VD << VD->getType();
11722           DiagnosticEmitted = true;
11723         }
11724         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11725             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11726       }
11727     }
11728   } else if (isa<CXXThisExpr>(E)) {
11729     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11730       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11731         if (MD->isConst()) {
11732           if (!DiagnosticEmitted) {
11733             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11734                                                           << ConstMethod << MD;
11735             DiagnosticEmitted = true;
11736           }
11737           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11738               << ConstMethod << MD << MD->getSourceRange();
11739         }
11740       }
11741     }
11742   }
11743 
11744   if (DiagnosticEmitted)
11745     return;
11746 
11747   // Can't determine a more specific message, so display the generic error.
11748   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11749 }
11750 
11751 enum OriginalExprKind {
11752   OEK_Variable,
11753   OEK_Member,
11754   OEK_LValue
11755 };
11756 
11757 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11758                                          const RecordType *Ty,
11759                                          SourceLocation Loc, SourceRange Range,
11760                                          OriginalExprKind OEK,
11761                                          bool &DiagnosticEmitted) {
11762   std::vector<const RecordType *> RecordTypeList;
11763   RecordTypeList.push_back(Ty);
11764   unsigned NextToCheckIndex = 0;
11765   // We walk the record hierarchy breadth-first to ensure that we print
11766   // diagnostics in field nesting order.
11767   while (RecordTypeList.size() > NextToCheckIndex) {
11768     bool IsNested = NextToCheckIndex > 0;
11769     for (const FieldDecl *Field :
11770          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11771       // First, check every field for constness.
11772       QualType FieldTy = Field->getType();
11773       if (FieldTy.isConstQualified()) {
11774         if (!DiagnosticEmitted) {
11775           S.Diag(Loc, diag::err_typecheck_assign_const)
11776               << Range << NestedConstMember << OEK << VD
11777               << IsNested << Field;
11778           DiagnosticEmitted = true;
11779         }
11780         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11781             << NestedConstMember << IsNested << Field
11782             << FieldTy << Field->getSourceRange();
11783       }
11784 
11785       // Then we append it to the list to check next in order.
11786       FieldTy = FieldTy.getCanonicalType();
11787       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11788         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11789           RecordTypeList.push_back(FieldRecTy);
11790       }
11791     }
11792     ++NextToCheckIndex;
11793   }
11794 }
11795 
11796 /// Emit an error for the case where a record we are trying to assign to has a
11797 /// const-qualified field somewhere in its hierarchy.
11798 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11799                                          SourceLocation Loc) {
11800   QualType Ty = E->getType();
11801   assert(Ty->isRecordType() && "lvalue was not record?");
11802   SourceRange Range = E->getSourceRange();
11803   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11804   bool DiagEmitted = false;
11805 
11806   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11807     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11808             Range, OEK_Member, DiagEmitted);
11809   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11810     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11811             Range, OEK_Variable, DiagEmitted);
11812   else
11813     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11814             Range, OEK_LValue, DiagEmitted);
11815   if (!DiagEmitted)
11816     DiagnoseConstAssignment(S, E, Loc);
11817 }
11818 
11819 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11820 /// emit an error and return true.  If so, return false.
11821 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11822   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11823 
11824   S.CheckShadowingDeclModification(E, Loc);
11825 
11826   SourceLocation OrigLoc = Loc;
11827   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11828                                                               &Loc);
11829   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11830     IsLV = Expr::MLV_InvalidMessageExpression;
11831   if (IsLV == Expr::MLV_Valid)
11832     return false;
11833 
11834   unsigned DiagID = 0;
11835   bool NeedType = false;
11836   switch (IsLV) { // C99 6.5.16p2
11837   case Expr::MLV_ConstQualified:
11838     // Use a specialized diagnostic when we're assigning to an object
11839     // from an enclosing function or block.
11840     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11841       if (NCCK == NCCK_Block)
11842         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11843       else
11844         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11845       break;
11846     }
11847 
11848     // In ARC, use some specialized diagnostics for occasions where we
11849     // infer 'const'.  These are always pseudo-strong variables.
11850     if (S.getLangOpts().ObjCAutoRefCount) {
11851       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11852       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11853         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11854 
11855         // Use the normal diagnostic if it's pseudo-__strong but the
11856         // user actually wrote 'const'.
11857         if (var->isARCPseudoStrong() &&
11858             (!var->getTypeSourceInfo() ||
11859              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11860           // There are three pseudo-strong cases:
11861           //  - self
11862           ObjCMethodDecl *method = S.getCurMethodDecl();
11863           if (method && var == method->getSelfDecl()) {
11864             DiagID = method->isClassMethod()
11865               ? diag::err_typecheck_arc_assign_self_class_method
11866               : diag::err_typecheck_arc_assign_self;
11867 
11868           //  - Objective-C externally_retained attribute.
11869           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11870                      isa<ParmVarDecl>(var)) {
11871             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11872 
11873           //  - fast enumeration variables
11874           } else {
11875             DiagID = diag::err_typecheck_arr_assign_enumeration;
11876           }
11877 
11878           SourceRange Assign;
11879           if (Loc != OrigLoc)
11880             Assign = SourceRange(OrigLoc, OrigLoc);
11881           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11882           // We need to preserve the AST regardless, so migration tool
11883           // can do its job.
11884           return false;
11885         }
11886       }
11887     }
11888 
11889     // If none of the special cases above are triggered, then this is a
11890     // simple const assignment.
11891     if (DiagID == 0) {
11892       DiagnoseConstAssignment(S, E, Loc);
11893       return true;
11894     }
11895 
11896     break;
11897   case Expr::MLV_ConstAddrSpace:
11898     DiagnoseConstAssignment(S, E, Loc);
11899     return true;
11900   case Expr::MLV_ConstQualifiedField:
11901     DiagnoseRecursiveConstFields(S, E, Loc);
11902     return true;
11903   case Expr::MLV_ArrayType:
11904   case Expr::MLV_ArrayTemporary:
11905     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11906     NeedType = true;
11907     break;
11908   case Expr::MLV_NotObjectType:
11909     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11910     NeedType = true;
11911     break;
11912   case Expr::MLV_LValueCast:
11913     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11914     break;
11915   case Expr::MLV_Valid:
11916     llvm_unreachable("did not take early return for MLV_Valid");
11917   case Expr::MLV_InvalidExpression:
11918   case Expr::MLV_MemberFunction:
11919   case Expr::MLV_ClassTemporary:
11920     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11921     break;
11922   case Expr::MLV_IncompleteType:
11923   case Expr::MLV_IncompleteVoidType:
11924     return S.RequireCompleteType(Loc, E->getType(),
11925              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11926   case Expr::MLV_DuplicateVectorComponents:
11927     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11928     break;
11929   case Expr::MLV_NoSetterProperty:
11930     llvm_unreachable("readonly properties should be processed differently");
11931   case Expr::MLV_InvalidMessageExpression:
11932     DiagID = diag::err_readonly_message_assignment;
11933     break;
11934   case Expr::MLV_SubObjCPropertySetting:
11935     DiagID = diag::err_no_subobject_property_setting;
11936     break;
11937   }
11938 
11939   SourceRange Assign;
11940   if (Loc != OrigLoc)
11941     Assign = SourceRange(OrigLoc, OrigLoc);
11942   if (NeedType)
11943     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11944   else
11945     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11946   return true;
11947 }
11948 
11949 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11950                                          SourceLocation Loc,
11951                                          Sema &Sema) {
11952   if (Sema.inTemplateInstantiation())
11953     return;
11954   if (Sema.isUnevaluatedContext())
11955     return;
11956   if (Loc.isInvalid() || Loc.isMacroID())
11957     return;
11958   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11959     return;
11960 
11961   // C / C++ fields
11962   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11963   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11964   if (ML && MR) {
11965     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11966       return;
11967     const ValueDecl *LHSDecl =
11968         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11969     const ValueDecl *RHSDecl =
11970         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11971     if (LHSDecl != RHSDecl)
11972       return;
11973     if (LHSDecl->getType().isVolatileQualified())
11974       return;
11975     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11976       if (RefTy->getPointeeType().isVolatileQualified())
11977         return;
11978 
11979     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11980   }
11981 
11982   // Objective-C instance variables
11983   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11984   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11985   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11986     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11987     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11988     if (RL && RR && RL->getDecl() == RR->getDecl())
11989       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11990   }
11991 }
11992 
11993 // C99 6.5.16.1
11994 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11995                                        SourceLocation Loc,
11996                                        QualType CompoundType) {
11997   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11998 
11999   // Verify that LHS is a modifiable lvalue, and emit error if not.
12000   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12001     return QualType();
12002 
12003   QualType LHSType = LHSExpr->getType();
12004   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12005                                              CompoundType;
12006   // OpenCL v1.2 s6.1.1.1 p2:
12007   // The half data type can only be used to declare a pointer to a buffer that
12008   // contains half values
12009   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12010     LHSType->isHalfType()) {
12011     Diag(Loc, diag::err_opencl_half_load_store) << 1
12012         << LHSType.getUnqualifiedType();
12013     return QualType();
12014   }
12015 
12016   AssignConvertType ConvTy;
12017   if (CompoundType.isNull()) {
12018     Expr *RHSCheck = RHS.get();
12019 
12020     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12021 
12022     QualType LHSTy(LHSType);
12023     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12024     if (RHS.isInvalid())
12025       return QualType();
12026     // Special case of NSObject attributes on c-style pointer types.
12027     if (ConvTy == IncompatiblePointer &&
12028         ((Context.isObjCNSObjectType(LHSType) &&
12029           RHSType->isObjCObjectPointerType()) ||
12030          (Context.isObjCNSObjectType(RHSType) &&
12031           LHSType->isObjCObjectPointerType())))
12032       ConvTy = Compatible;
12033 
12034     if (ConvTy == Compatible &&
12035         LHSType->isObjCObjectType())
12036         Diag(Loc, diag::err_objc_object_assignment)
12037           << LHSType;
12038 
12039     // If the RHS is a unary plus or minus, check to see if they = and + are
12040     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12041     // instead of "x += 4".
12042     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12043       RHSCheck = ICE->getSubExpr();
12044     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12045       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12046           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12047           // Only if the two operators are exactly adjacent.
12048           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12049           // And there is a space or other character before the subexpr of the
12050           // unary +/-.  We don't want to warn on "x=-1".
12051           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12052           UO->getSubExpr()->getBeginLoc().isFileID()) {
12053         Diag(Loc, diag::warn_not_compound_assign)
12054           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12055           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12056       }
12057     }
12058 
12059     if (ConvTy == Compatible) {
12060       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12061         // Warn about retain cycles where a block captures the LHS, but
12062         // not if the LHS is a simple variable into which the block is
12063         // being stored...unless that variable can be captured by reference!
12064         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12065         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12066         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12067           checkRetainCycles(LHSExpr, RHS.get());
12068       }
12069 
12070       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12071           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12072         // It is safe to assign a weak reference into a strong variable.
12073         // Although this code can still have problems:
12074         //   id x = self.weakProp;
12075         //   id y = self.weakProp;
12076         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12077         // paths through the function. This should be revisited if
12078         // -Wrepeated-use-of-weak is made flow-sensitive.
12079         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12080         // variable, which will be valid for the current autorelease scope.
12081         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12082                              RHS.get()->getBeginLoc()))
12083           getCurFunction()->markSafeWeakUse(RHS.get());
12084 
12085       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12086         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12087       }
12088     }
12089   } else {
12090     // Compound assignment "x += y"
12091     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12092   }
12093 
12094   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12095                                RHS.get(), AA_Assigning))
12096     return QualType();
12097 
12098   CheckForNullPointerDereference(*this, LHSExpr);
12099 
12100   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12101     if (CompoundType.isNull()) {
12102       // C++2a [expr.ass]p5:
12103       //   A simple-assignment whose left operand is of a volatile-qualified
12104       //   type is deprecated unless the assignment is either a discarded-value
12105       //   expression or an unevaluated operand
12106       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12107     } else {
12108       // C++2a [expr.ass]p6:
12109       //   [Compound-assignment] expressions are deprecated if E1 has
12110       //   volatile-qualified type
12111       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12112     }
12113   }
12114 
12115   // C99 6.5.16p3: The type of an assignment expression is the type of the
12116   // left operand unless the left operand has qualified type, in which case
12117   // it is the unqualified version of the type of the left operand.
12118   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12119   // is converted to the type of the assignment expression (above).
12120   // C++ 5.17p1: the type of the assignment expression is that of its left
12121   // operand.
12122   return (getLangOpts().CPlusPlus
12123           ? LHSType : LHSType.getUnqualifiedType());
12124 }
12125 
12126 // Only ignore explicit casts to void.
12127 static bool IgnoreCommaOperand(const Expr *E) {
12128   E = E->IgnoreParens();
12129 
12130   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12131     if (CE->getCastKind() == CK_ToVoid) {
12132       return true;
12133     }
12134 
12135     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12136     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12137         CE->getSubExpr()->getType()->isDependentType()) {
12138       return true;
12139     }
12140   }
12141 
12142   return false;
12143 }
12144 
12145 // Look for instances where it is likely the comma operator is confused with
12146 // another operator.  There is a whitelist of acceptable expressions for the
12147 // left hand side of the comma operator, otherwise emit a warning.
12148 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12149   // No warnings in macros
12150   if (Loc.isMacroID())
12151     return;
12152 
12153   // Don't warn in template instantiations.
12154   if (inTemplateInstantiation())
12155     return;
12156 
12157   // Scope isn't fine-grained enough to whitelist the specific cases, so
12158   // instead, skip more than needed, then call back into here with the
12159   // CommaVisitor in SemaStmt.cpp.
12160   // The whitelisted locations are the initialization and increment portions
12161   // of a for loop.  The additional checks are on the condition of
12162   // if statements, do/while loops, and for loops.
12163   // Differences in scope flags for C89 mode requires the extra logic.
12164   const unsigned ForIncrementFlags =
12165       getLangOpts().C99 || getLangOpts().CPlusPlus
12166           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12167           : Scope::ContinueScope | Scope::BreakScope;
12168   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12169   const unsigned ScopeFlags = getCurScope()->getFlags();
12170   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12171       (ScopeFlags & ForInitFlags) == ForInitFlags)
12172     return;
12173 
12174   // If there are multiple comma operators used together, get the RHS of the
12175   // of the comma operator as the LHS.
12176   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12177     if (BO->getOpcode() != BO_Comma)
12178       break;
12179     LHS = BO->getRHS();
12180   }
12181 
12182   // Only allow some expressions on LHS to not warn.
12183   if (IgnoreCommaOperand(LHS))
12184     return;
12185 
12186   Diag(Loc, diag::warn_comma_operator);
12187   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12188       << LHS->getSourceRange()
12189       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12190                                     LangOpts.CPlusPlus ? "static_cast<void>("
12191                                                        : "(void)(")
12192       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12193                                     ")");
12194 }
12195 
12196 // C99 6.5.17
12197 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12198                                    SourceLocation Loc) {
12199   LHS = S.CheckPlaceholderExpr(LHS.get());
12200   RHS = S.CheckPlaceholderExpr(RHS.get());
12201   if (LHS.isInvalid() || RHS.isInvalid())
12202     return QualType();
12203 
12204   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12205   // operands, but not unary promotions.
12206   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12207 
12208   // So we treat the LHS as a ignored value, and in C++ we allow the
12209   // containing site to determine what should be done with the RHS.
12210   LHS = S.IgnoredValueConversions(LHS.get());
12211   if (LHS.isInvalid())
12212     return QualType();
12213 
12214   S.DiagnoseUnusedExprResult(LHS.get());
12215 
12216   if (!S.getLangOpts().CPlusPlus) {
12217     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12218     if (RHS.isInvalid())
12219       return QualType();
12220     if (!RHS.get()->getType()->isVoidType())
12221       S.RequireCompleteType(Loc, RHS.get()->getType(),
12222                             diag::err_incomplete_type);
12223   }
12224 
12225   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12226     S.DiagnoseCommaOperator(LHS.get(), Loc);
12227 
12228   return RHS.get()->getType();
12229 }
12230 
12231 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12232 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12233 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12234                                                ExprValueKind &VK,
12235                                                ExprObjectKind &OK,
12236                                                SourceLocation OpLoc,
12237                                                bool IsInc, bool IsPrefix) {
12238   if (Op->isTypeDependent())
12239     return S.Context.DependentTy;
12240 
12241   QualType ResType = Op->getType();
12242   // Atomic types can be used for increment / decrement where the non-atomic
12243   // versions can, so ignore the _Atomic() specifier for the purpose of
12244   // checking.
12245   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12246     ResType = ResAtomicType->getValueType();
12247 
12248   assert(!ResType.isNull() && "no type for increment/decrement expression");
12249 
12250   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12251     // Decrement of bool is not allowed.
12252     if (!IsInc) {
12253       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12254       return QualType();
12255     }
12256     // Increment of bool sets it to true, but is deprecated.
12257     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12258                                               : diag::warn_increment_bool)
12259       << Op->getSourceRange();
12260   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12261     // Error on enum increments and decrements in C++ mode
12262     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12263     return QualType();
12264   } else if (ResType->isRealType()) {
12265     // OK!
12266   } else if (ResType->isPointerType()) {
12267     // C99 6.5.2.4p2, 6.5.6p2
12268     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12269       return QualType();
12270   } else if (ResType->isObjCObjectPointerType()) {
12271     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12272     // Otherwise, we just need a complete type.
12273     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12274         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12275       return QualType();
12276   } else if (ResType->isAnyComplexType()) {
12277     // C99 does not support ++/-- on complex types, we allow as an extension.
12278     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12279       << ResType << Op->getSourceRange();
12280   } else if (ResType->isPlaceholderType()) {
12281     ExprResult PR = S.CheckPlaceholderExpr(Op);
12282     if (PR.isInvalid()) return QualType();
12283     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12284                                           IsInc, IsPrefix);
12285   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12286     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12287   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12288              (ResType->castAs<VectorType>()->getVectorKind() !=
12289               VectorType::AltiVecBool)) {
12290     // The z vector extensions allow ++ and -- for non-bool vectors.
12291   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12292             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12293     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12294   } else {
12295     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12296       << ResType << int(IsInc) << Op->getSourceRange();
12297     return QualType();
12298   }
12299   // At this point, we know we have a real, complex or pointer type.
12300   // Now make sure the operand is a modifiable lvalue.
12301   if (CheckForModifiableLvalue(Op, OpLoc, S))
12302     return QualType();
12303   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12304     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12305     //   An operand with volatile-qualified type is deprecated
12306     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12307         << IsInc << ResType;
12308   }
12309   // In C++, a prefix increment is the same type as the operand. Otherwise
12310   // (in C or with postfix), the increment is the unqualified type of the
12311   // operand.
12312   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12313     VK = VK_LValue;
12314     OK = Op->getObjectKind();
12315     return ResType;
12316   } else {
12317     VK = VK_RValue;
12318     return ResType.getUnqualifiedType();
12319   }
12320 }
12321 
12322 
12323 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12324 /// This routine allows us to typecheck complex/recursive expressions
12325 /// where the declaration is needed for type checking. We only need to
12326 /// handle cases when the expression references a function designator
12327 /// or is an lvalue. Here are some examples:
12328 ///  - &(x) => x
12329 ///  - &*****f => f for f a function designator.
12330 ///  - &s.xx => s
12331 ///  - &s.zz[1].yy -> s, if zz is an array
12332 ///  - *(x + 1) -> x, if x is an array
12333 ///  - &"123"[2] -> 0
12334 ///  - & __real__ x -> x
12335 static ValueDecl *getPrimaryDecl(Expr *E) {
12336   switch (E->getStmtClass()) {
12337   case Stmt::DeclRefExprClass:
12338     return cast<DeclRefExpr>(E)->getDecl();
12339   case Stmt::MemberExprClass:
12340     // If this is an arrow operator, the address is an offset from
12341     // the base's value, so the object the base refers to is
12342     // irrelevant.
12343     if (cast<MemberExpr>(E)->isArrow())
12344       return nullptr;
12345     // Otherwise, the expression refers to a part of the base
12346     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12347   case Stmt::ArraySubscriptExprClass: {
12348     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12349     // promotion of register arrays earlier.
12350     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12351     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12352       if (ICE->getSubExpr()->getType()->isArrayType())
12353         return getPrimaryDecl(ICE->getSubExpr());
12354     }
12355     return nullptr;
12356   }
12357   case Stmt::UnaryOperatorClass: {
12358     UnaryOperator *UO = cast<UnaryOperator>(E);
12359 
12360     switch(UO->getOpcode()) {
12361     case UO_Real:
12362     case UO_Imag:
12363     case UO_Extension:
12364       return getPrimaryDecl(UO->getSubExpr());
12365     default:
12366       return nullptr;
12367     }
12368   }
12369   case Stmt::ParenExprClass:
12370     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12371   case Stmt::ImplicitCastExprClass:
12372     // If the result of an implicit cast is an l-value, we care about
12373     // the sub-expression; otherwise, the result here doesn't matter.
12374     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12375   default:
12376     return nullptr;
12377   }
12378 }
12379 
12380 namespace {
12381   enum {
12382     AO_Bit_Field = 0,
12383     AO_Vector_Element = 1,
12384     AO_Property_Expansion = 2,
12385     AO_Register_Variable = 3,
12386     AO_No_Error = 4
12387   };
12388 }
12389 /// Diagnose invalid operand for address of operations.
12390 ///
12391 /// \param Type The type of operand which cannot have its address taken.
12392 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12393                                          Expr *E, unsigned Type) {
12394   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12395 }
12396 
12397 /// CheckAddressOfOperand - The operand of & must be either a function
12398 /// designator or an lvalue designating an object. If it is an lvalue, the
12399 /// object cannot be declared with storage class register or be a bit field.
12400 /// Note: The usual conversions are *not* applied to the operand of the &
12401 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12402 /// In C++, the operand might be an overloaded function name, in which case
12403 /// we allow the '&' but retain the overloaded-function type.
12404 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12405   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12406     if (PTy->getKind() == BuiltinType::Overload) {
12407       Expr *E = OrigOp.get()->IgnoreParens();
12408       if (!isa<OverloadExpr>(E)) {
12409         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12410         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12411           << OrigOp.get()->getSourceRange();
12412         return QualType();
12413       }
12414 
12415       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12416       if (isa<UnresolvedMemberExpr>(Ovl))
12417         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12418           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12419             << OrigOp.get()->getSourceRange();
12420           return QualType();
12421         }
12422 
12423       return Context.OverloadTy;
12424     }
12425 
12426     if (PTy->getKind() == BuiltinType::UnknownAny)
12427       return Context.UnknownAnyTy;
12428 
12429     if (PTy->getKind() == BuiltinType::BoundMember) {
12430       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12431         << OrigOp.get()->getSourceRange();
12432       return QualType();
12433     }
12434 
12435     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12436     if (OrigOp.isInvalid()) return QualType();
12437   }
12438 
12439   if (OrigOp.get()->isTypeDependent())
12440     return Context.DependentTy;
12441 
12442   assert(!OrigOp.get()->getType()->isPlaceholderType());
12443 
12444   // Make sure to ignore parentheses in subsequent checks
12445   Expr *op = OrigOp.get()->IgnoreParens();
12446 
12447   // In OpenCL captures for blocks called as lambda functions
12448   // are located in the private address space. Blocks used in
12449   // enqueue_kernel can be located in a different address space
12450   // depending on a vendor implementation. Thus preventing
12451   // taking an address of the capture to avoid invalid AS casts.
12452   if (LangOpts.OpenCL) {
12453     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12454     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12455       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12456       return QualType();
12457     }
12458   }
12459 
12460   if (getLangOpts().C99) {
12461     // Implement C99-only parts of addressof rules.
12462     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12463       if (uOp->getOpcode() == UO_Deref)
12464         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12465         // (assuming the deref expression is valid).
12466         return uOp->getSubExpr()->getType();
12467     }
12468     // Technically, there should be a check for array subscript
12469     // expressions here, but the result of one is always an lvalue anyway.
12470   }
12471   ValueDecl *dcl = getPrimaryDecl(op);
12472 
12473   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12474     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12475                                            op->getBeginLoc()))
12476       return QualType();
12477 
12478   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12479   unsigned AddressOfError = AO_No_Error;
12480 
12481   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12482     bool sfinae = (bool)isSFINAEContext();
12483     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12484                                   : diag::ext_typecheck_addrof_temporary)
12485       << op->getType() << op->getSourceRange();
12486     if (sfinae)
12487       return QualType();
12488     // Materialize the temporary as an lvalue so that we can take its address.
12489     OrigOp = op =
12490         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12491   } else if (isa<ObjCSelectorExpr>(op)) {
12492     return Context.getPointerType(op->getType());
12493   } else if (lval == Expr::LV_MemberFunction) {
12494     // If it's an instance method, make a member pointer.
12495     // The expression must have exactly the form &A::foo.
12496 
12497     // If the underlying expression isn't a decl ref, give up.
12498     if (!isa<DeclRefExpr>(op)) {
12499       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12500         << OrigOp.get()->getSourceRange();
12501       return QualType();
12502     }
12503     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12504     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12505 
12506     // The id-expression was parenthesized.
12507     if (OrigOp.get() != DRE) {
12508       Diag(OpLoc, diag::err_parens_pointer_member_function)
12509         << OrigOp.get()->getSourceRange();
12510 
12511     // The method was named without a qualifier.
12512     } else if (!DRE->getQualifier()) {
12513       if (MD->getParent()->getName().empty())
12514         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12515           << op->getSourceRange();
12516       else {
12517         SmallString<32> Str;
12518         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12519         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12520           << op->getSourceRange()
12521           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12522       }
12523     }
12524 
12525     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12526     if (isa<CXXDestructorDecl>(MD))
12527       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12528 
12529     QualType MPTy = Context.getMemberPointerType(
12530         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12531     // Under the MS ABI, lock down the inheritance model now.
12532     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12533       (void)isCompleteType(OpLoc, MPTy);
12534     return MPTy;
12535   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12536     // C99 6.5.3.2p1
12537     // The operand must be either an l-value or a function designator
12538     if (!op->getType()->isFunctionType()) {
12539       // Use a special diagnostic for loads from property references.
12540       if (isa<PseudoObjectExpr>(op)) {
12541         AddressOfError = AO_Property_Expansion;
12542       } else {
12543         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12544           << op->getType() << op->getSourceRange();
12545         return QualType();
12546       }
12547     }
12548   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12549     // The operand cannot be a bit-field
12550     AddressOfError = AO_Bit_Field;
12551   } else if (op->getObjectKind() == OK_VectorComponent) {
12552     // The operand cannot be an element of a vector
12553     AddressOfError = AO_Vector_Element;
12554   } else if (dcl) { // C99 6.5.3.2p1
12555     // We have an lvalue with a decl. Make sure the decl is not declared
12556     // with the register storage-class specifier.
12557     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12558       // in C++ it is not error to take address of a register
12559       // variable (c++03 7.1.1P3)
12560       if (vd->getStorageClass() == SC_Register &&
12561           !getLangOpts().CPlusPlus) {
12562         AddressOfError = AO_Register_Variable;
12563       }
12564     } else if (isa<MSPropertyDecl>(dcl)) {
12565       AddressOfError = AO_Property_Expansion;
12566     } else if (isa<FunctionTemplateDecl>(dcl)) {
12567       return Context.OverloadTy;
12568     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12569       // Okay: we can take the address of a field.
12570       // Could be a pointer to member, though, if there is an explicit
12571       // scope qualifier for the class.
12572       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12573         DeclContext *Ctx = dcl->getDeclContext();
12574         if (Ctx && Ctx->isRecord()) {
12575           if (dcl->getType()->isReferenceType()) {
12576             Diag(OpLoc,
12577                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12578               << dcl->getDeclName() << dcl->getType();
12579             return QualType();
12580           }
12581 
12582           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12583             Ctx = Ctx->getParent();
12584 
12585           QualType MPTy = Context.getMemberPointerType(
12586               op->getType(),
12587               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12588           // Under the MS ABI, lock down the inheritance model now.
12589           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12590             (void)isCompleteType(OpLoc, MPTy);
12591           return MPTy;
12592         }
12593       }
12594     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12595                !isa<BindingDecl>(dcl))
12596       llvm_unreachable("Unknown/unexpected decl type");
12597   }
12598 
12599   if (AddressOfError != AO_No_Error) {
12600     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12601     return QualType();
12602   }
12603 
12604   if (lval == Expr::LV_IncompleteVoidType) {
12605     // Taking the address of a void variable is technically illegal, but we
12606     // allow it in cases which are otherwise valid.
12607     // Example: "extern void x; void* y = &x;".
12608     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12609   }
12610 
12611   // If the operand has type "type", the result has type "pointer to type".
12612   if (op->getType()->isObjCObjectType())
12613     return Context.getObjCObjectPointerType(op->getType());
12614 
12615   CheckAddressOfPackedMember(op);
12616 
12617   return Context.getPointerType(op->getType());
12618 }
12619 
12620 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12621   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12622   if (!DRE)
12623     return;
12624   const Decl *D = DRE->getDecl();
12625   if (!D)
12626     return;
12627   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12628   if (!Param)
12629     return;
12630   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12631     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12632       return;
12633   if (FunctionScopeInfo *FD = S.getCurFunction())
12634     if (!FD->ModifiedNonNullParams.count(Param))
12635       FD->ModifiedNonNullParams.insert(Param);
12636 }
12637 
12638 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12639 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12640                                         SourceLocation OpLoc) {
12641   if (Op->isTypeDependent())
12642     return S.Context.DependentTy;
12643 
12644   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12645   if (ConvResult.isInvalid())
12646     return QualType();
12647   Op = ConvResult.get();
12648   QualType OpTy = Op->getType();
12649   QualType Result;
12650 
12651   if (isa<CXXReinterpretCastExpr>(Op)) {
12652     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12653     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12654                                      Op->getSourceRange());
12655   }
12656 
12657   if (const PointerType *PT = OpTy->getAs<PointerType>())
12658   {
12659     Result = PT->getPointeeType();
12660   }
12661   else if (const ObjCObjectPointerType *OPT =
12662              OpTy->getAs<ObjCObjectPointerType>())
12663     Result = OPT->getPointeeType();
12664   else {
12665     ExprResult PR = S.CheckPlaceholderExpr(Op);
12666     if (PR.isInvalid()) return QualType();
12667     if (PR.get() != Op)
12668       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12669   }
12670 
12671   if (Result.isNull()) {
12672     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12673       << OpTy << Op->getSourceRange();
12674     return QualType();
12675   }
12676 
12677   // Note that per both C89 and C99, indirection is always legal, even if Result
12678   // is an incomplete type or void.  It would be possible to warn about
12679   // dereferencing a void pointer, but it's completely well-defined, and such a
12680   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12681   // for pointers to 'void' but is fine for any other pointer type:
12682   //
12683   // C++ [expr.unary.op]p1:
12684   //   [...] the expression to which [the unary * operator] is applied shall
12685   //   be a pointer to an object type, or a pointer to a function type
12686   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12687     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12688       << OpTy << Op->getSourceRange();
12689 
12690   // Dereferences are usually l-values...
12691   VK = VK_LValue;
12692 
12693   // ...except that certain expressions are never l-values in C.
12694   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12695     VK = VK_RValue;
12696 
12697   return Result;
12698 }
12699 
12700 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12701   BinaryOperatorKind Opc;
12702   switch (Kind) {
12703   default: llvm_unreachable("Unknown binop!");
12704   case tok::periodstar:           Opc = BO_PtrMemD; break;
12705   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12706   case tok::star:                 Opc = BO_Mul; break;
12707   case tok::slash:                Opc = BO_Div; break;
12708   case tok::percent:              Opc = BO_Rem; break;
12709   case tok::plus:                 Opc = BO_Add; break;
12710   case tok::minus:                Opc = BO_Sub; break;
12711   case tok::lessless:             Opc = BO_Shl; break;
12712   case tok::greatergreater:       Opc = BO_Shr; break;
12713   case tok::lessequal:            Opc = BO_LE; break;
12714   case tok::less:                 Opc = BO_LT; break;
12715   case tok::greaterequal:         Opc = BO_GE; break;
12716   case tok::greater:              Opc = BO_GT; break;
12717   case tok::exclaimequal:         Opc = BO_NE; break;
12718   case tok::equalequal:           Opc = BO_EQ; break;
12719   case tok::spaceship:            Opc = BO_Cmp; break;
12720   case tok::amp:                  Opc = BO_And; break;
12721   case tok::caret:                Opc = BO_Xor; break;
12722   case tok::pipe:                 Opc = BO_Or; break;
12723   case tok::ampamp:               Opc = BO_LAnd; break;
12724   case tok::pipepipe:             Opc = BO_LOr; break;
12725   case tok::equal:                Opc = BO_Assign; break;
12726   case tok::starequal:            Opc = BO_MulAssign; break;
12727   case tok::slashequal:           Opc = BO_DivAssign; break;
12728   case tok::percentequal:         Opc = BO_RemAssign; break;
12729   case tok::plusequal:            Opc = BO_AddAssign; break;
12730   case tok::minusequal:           Opc = BO_SubAssign; break;
12731   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12732   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12733   case tok::ampequal:             Opc = BO_AndAssign; break;
12734   case tok::caretequal:           Opc = BO_XorAssign; break;
12735   case tok::pipeequal:            Opc = BO_OrAssign; break;
12736   case tok::comma:                Opc = BO_Comma; break;
12737   }
12738   return Opc;
12739 }
12740 
12741 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12742   tok::TokenKind Kind) {
12743   UnaryOperatorKind Opc;
12744   switch (Kind) {
12745   default: llvm_unreachable("Unknown unary op!");
12746   case tok::plusplus:     Opc = UO_PreInc; break;
12747   case tok::minusminus:   Opc = UO_PreDec; break;
12748   case tok::amp:          Opc = UO_AddrOf; break;
12749   case tok::star:         Opc = UO_Deref; break;
12750   case tok::plus:         Opc = UO_Plus; break;
12751   case tok::minus:        Opc = UO_Minus; break;
12752   case tok::tilde:        Opc = UO_Not; break;
12753   case tok::exclaim:      Opc = UO_LNot; break;
12754   case tok::kw___real:    Opc = UO_Real; break;
12755   case tok::kw___imag:    Opc = UO_Imag; break;
12756   case tok::kw___extension__: Opc = UO_Extension; break;
12757   }
12758   return Opc;
12759 }
12760 
12761 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12762 /// This warning suppressed in the event of macro expansions.
12763 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12764                                    SourceLocation OpLoc, bool IsBuiltin) {
12765   if (S.inTemplateInstantiation())
12766     return;
12767   if (S.isUnevaluatedContext())
12768     return;
12769   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12770     return;
12771   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12772   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12773   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12774   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12775   if (!LHSDeclRef || !RHSDeclRef ||
12776       LHSDeclRef->getLocation().isMacroID() ||
12777       RHSDeclRef->getLocation().isMacroID())
12778     return;
12779   const ValueDecl *LHSDecl =
12780     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12781   const ValueDecl *RHSDecl =
12782     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12783   if (LHSDecl != RHSDecl)
12784     return;
12785   if (LHSDecl->getType().isVolatileQualified())
12786     return;
12787   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12788     if (RefTy->getPointeeType().isVolatileQualified())
12789       return;
12790 
12791   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12792                           : diag::warn_self_assignment_overloaded)
12793       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12794       << RHSExpr->getSourceRange();
12795 }
12796 
12797 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12798 /// is usually indicative of introspection within the Objective-C pointer.
12799 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12800                                           SourceLocation OpLoc) {
12801   if (!S.getLangOpts().ObjC)
12802     return;
12803 
12804   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12805   const Expr *LHS = L.get();
12806   const Expr *RHS = R.get();
12807 
12808   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12809     ObjCPointerExpr = LHS;
12810     OtherExpr = RHS;
12811   }
12812   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12813     ObjCPointerExpr = RHS;
12814     OtherExpr = LHS;
12815   }
12816 
12817   // This warning is deliberately made very specific to reduce false
12818   // positives with logic that uses '&' for hashing.  This logic mainly
12819   // looks for code trying to introspect into tagged pointers, which
12820   // code should generally never do.
12821   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12822     unsigned Diag = diag::warn_objc_pointer_masking;
12823     // Determine if we are introspecting the result of performSelectorXXX.
12824     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12825     // Special case messages to -performSelector and friends, which
12826     // can return non-pointer values boxed in a pointer value.
12827     // Some clients may wish to silence warnings in this subcase.
12828     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12829       Selector S = ME->getSelector();
12830       StringRef SelArg0 = S.getNameForSlot(0);
12831       if (SelArg0.startswith("performSelector"))
12832         Diag = diag::warn_objc_pointer_masking_performSelector;
12833     }
12834 
12835     S.Diag(OpLoc, Diag)
12836       << ObjCPointerExpr->getSourceRange();
12837   }
12838 }
12839 
12840 static NamedDecl *getDeclFromExpr(Expr *E) {
12841   if (!E)
12842     return nullptr;
12843   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12844     return DRE->getDecl();
12845   if (auto *ME = dyn_cast<MemberExpr>(E))
12846     return ME->getMemberDecl();
12847   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12848     return IRE->getDecl();
12849   return nullptr;
12850 }
12851 
12852 // This helper function promotes a binary operator's operands (which are of a
12853 // half vector type) to a vector of floats and then truncates the result to
12854 // a vector of either half or short.
12855 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12856                                       BinaryOperatorKind Opc, QualType ResultTy,
12857                                       ExprValueKind VK, ExprObjectKind OK,
12858                                       bool IsCompAssign, SourceLocation OpLoc,
12859                                       FPOptions FPFeatures) {
12860   auto &Context = S.getASTContext();
12861   assert((isVector(ResultTy, Context.HalfTy) ||
12862           isVector(ResultTy, Context.ShortTy)) &&
12863          "Result must be a vector of half or short");
12864   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12865          isVector(RHS.get()->getType(), Context.HalfTy) &&
12866          "both operands expected to be a half vector");
12867 
12868   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12869   QualType BinOpResTy = RHS.get()->getType();
12870 
12871   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12872   // change BinOpResTy to a vector of ints.
12873   if (isVector(ResultTy, Context.ShortTy))
12874     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12875 
12876   if (IsCompAssign)
12877     return new (Context) CompoundAssignOperator(
12878         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12879         OpLoc, FPFeatures);
12880 
12881   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12882   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12883                                           VK, OK, OpLoc, FPFeatures);
12884   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12885 }
12886 
12887 static std::pair<ExprResult, ExprResult>
12888 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12889                            Expr *RHSExpr) {
12890   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12891   if (!S.getLangOpts().CPlusPlus) {
12892     // C cannot handle TypoExpr nodes on either side of a binop because it
12893     // doesn't handle dependent types properly, so make sure any TypoExprs have
12894     // been dealt with before checking the operands.
12895     LHS = S.CorrectDelayedTyposInExpr(LHS);
12896     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12897       if (Opc != BO_Assign)
12898         return ExprResult(E);
12899       // Avoid correcting the RHS to the same Expr as the LHS.
12900       Decl *D = getDeclFromExpr(E);
12901       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12902     });
12903   }
12904   return std::make_pair(LHS, RHS);
12905 }
12906 
12907 /// Returns true if conversion between vectors of halfs and vectors of floats
12908 /// is needed.
12909 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12910                                      QualType SrcType) {
12911   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12912          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12913          isVector(SrcType, Ctx.HalfTy);
12914 }
12915 
12916 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12917 /// operator @p Opc at location @c TokLoc. This routine only supports
12918 /// built-in operations; ActOnBinOp handles overloaded operators.
12919 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12920                                     BinaryOperatorKind Opc,
12921                                     Expr *LHSExpr, Expr *RHSExpr) {
12922   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12923     // The syntax only allows initializer lists on the RHS of assignment,
12924     // so we don't need to worry about accepting invalid code for
12925     // non-assignment operators.
12926     // C++11 5.17p9:
12927     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12928     //   of x = {} is x = T().
12929     InitializationKind Kind = InitializationKind::CreateDirectList(
12930         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12931     InitializedEntity Entity =
12932         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12933     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12934     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12935     if (Init.isInvalid())
12936       return Init;
12937     RHSExpr = Init.get();
12938   }
12939 
12940   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12941   QualType ResultTy;     // Result type of the binary operator.
12942   // The following two variables are used for compound assignment operators
12943   QualType CompLHSTy;    // Type of LHS after promotions for computation
12944   QualType CompResultTy; // Type of computation result
12945   ExprValueKind VK = VK_RValue;
12946   ExprObjectKind OK = OK_Ordinary;
12947   bool ConvertHalfVec = false;
12948 
12949   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12950   if (!LHS.isUsable() || !RHS.isUsable())
12951     return ExprError();
12952 
12953   if (getLangOpts().OpenCL) {
12954     QualType LHSTy = LHSExpr->getType();
12955     QualType RHSTy = RHSExpr->getType();
12956     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12957     // the ATOMIC_VAR_INIT macro.
12958     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12959       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12960       if (BO_Assign == Opc)
12961         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12962       else
12963         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12964       return ExprError();
12965     }
12966 
12967     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12968     // only with a builtin functions and therefore should be disallowed here.
12969     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12970         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12971         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12972         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12973       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12974       return ExprError();
12975     }
12976   }
12977 
12978   // Diagnose operations on the unsupported types for OpenMP device compilation.
12979   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12980     if (Opc != BO_Assign && Opc != BO_Comma) {
12981       checkOpenMPDeviceExpr(LHSExpr);
12982       checkOpenMPDeviceExpr(RHSExpr);
12983     }
12984   }
12985 
12986   switch (Opc) {
12987   case BO_Assign:
12988     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12989     if (getLangOpts().CPlusPlus &&
12990         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12991       VK = LHS.get()->getValueKind();
12992       OK = LHS.get()->getObjectKind();
12993     }
12994     if (!ResultTy.isNull()) {
12995       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12996       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12997 
12998       // Avoid copying a block to the heap if the block is assigned to a local
12999       // auto variable that is declared in the same scope as the block. This
13000       // optimization is unsafe if the local variable is declared in an outer
13001       // scope. For example:
13002       //
13003       // BlockTy b;
13004       // {
13005       //   b = ^{...};
13006       // }
13007       // // It is unsafe to invoke the block here if it wasn't copied to the
13008       // // heap.
13009       // b();
13010 
13011       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13012         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13013           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13014             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13015               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13016 
13017       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13018         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13019                               NTCUC_Assignment, NTCUK_Copy);
13020     }
13021     RecordModifiableNonNullParam(*this, LHS.get());
13022     break;
13023   case BO_PtrMemD:
13024   case BO_PtrMemI:
13025     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13026                                             Opc == BO_PtrMemI);
13027     break;
13028   case BO_Mul:
13029   case BO_Div:
13030     ConvertHalfVec = true;
13031     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13032                                            Opc == BO_Div);
13033     break;
13034   case BO_Rem:
13035     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13036     break;
13037   case BO_Add:
13038     ConvertHalfVec = true;
13039     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13040     break;
13041   case BO_Sub:
13042     ConvertHalfVec = true;
13043     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13044     break;
13045   case BO_Shl:
13046   case BO_Shr:
13047     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13048     break;
13049   case BO_LE:
13050   case BO_LT:
13051   case BO_GE:
13052   case BO_GT:
13053     ConvertHalfVec = true;
13054     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13055     break;
13056   case BO_EQ:
13057   case BO_NE:
13058     ConvertHalfVec = true;
13059     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13060     break;
13061   case BO_Cmp:
13062     ConvertHalfVec = true;
13063     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13064     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13065     break;
13066   case BO_And:
13067     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13068     LLVM_FALLTHROUGH;
13069   case BO_Xor:
13070   case BO_Or:
13071     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13072     break;
13073   case BO_LAnd:
13074   case BO_LOr:
13075     ConvertHalfVec = true;
13076     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13077     break;
13078   case BO_MulAssign:
13079   case BO_DivAssign:
13080     ConvertHalfVec = true;
13081     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13082                                                Opc == BO_DivAssign);
13083     CompLHSTy = CompResultTy;
13084     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13085       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13086     break;
13087   case BO_RemAssign:
13088     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13089     CompLHSTy = CompResultTy;
13090     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13091       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13092     break;
13093   case BO_AddAssign:
13094     ConvertHalfVec = true;
13095     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13096     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13097       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13098     break;
13099   case BO_SubAssign:
13100     ConvertHalfVec = true;
13101     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13102     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13103       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13104     break;
13105   case BO_ShlAssign:
13106   case BO_ShrAssign:
13107     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13108     CompLHSTy = CompResultTy;
13109     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13110       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13111     break;
13112   case BO_AndAssign:
13113   case BO_OrAssign: // fallthrough
13114     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13115     LLVM_FALLTHROUGH;
13116   case BO_XorAssign:
13117     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13118     CompLHSTy = CompResultTy;
13119     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13120       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13121     break;
13122   case BO_Comma:
13123     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13124     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13125       VK = RHS.get()->getValueKind();
13126       OK = RHS.get()->getObjectKind();
13127     }
13128     break;
13129   }
13130   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13131     return ExprError();
13132 
13133   if (ResultTy->isRealFloatingType() &&
13134       (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13135        getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13136     // Mark the current function as usng floating point constrained intrinsics
13137     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13138       F->setUsesFPIntrin(true);
13139     }
13140 
13141   // Some of the binary operations require promoting operands of half vector to
13142   // float vectors and truncating the result back to half vector. For now, we do
13143   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13144   // arm64).
13145   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13146          isVector(LHS.get()->getType(), Context.HalfTy) &&
13147          "both sides are half vectors or neither sides are");
13148   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13149                                             LHS.get()->getType());
13150 
13151   // Check for array bounds violations for both sides of the BinaryOperator
13152   CheckArrayAccess(LHS.get());
13153   CheckArrayAccess(RHS.get());
13154 
13155   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13156     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13157                                                  &Context.Idents.get("object_setClass"),
13158                                                  SourceLocation(), LookupOrdinaryName);
13159     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13160       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13161       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13162           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13163                                         "object_setClass(")
13164           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13165                                           ",")
13166           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13167     }
13168     else
13169       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13170   }
13171   else if (const ObjCIvarRefExpr *OIRE =
13172            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13173     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13174 
13175   // Opc is not a compound assignment if CompResultTy is null.
13176   if (CompResultTy.isNull()) {
13177     if (ConvertHalfVec)
13178       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13179                                  OpLoc, FPFeatures);
13180     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13181                                         OK, OpLoc, FPFeatures);
13182   }
13183 
13184   // Handle compound assignments.
13185   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13186       OK_ObjCProperty) {
13187     VK = VK_LValue;
13188     OK = LHS.get()->getObjectKind();
13189   }
13190 
13191   if (ConvertHalfVec)
13192     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13193                                OpLoc, FPFeatures);
13194 
13195   return new (Context) CompoundAssignOperator(
13196       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13197       OpLoc, FPFeatures);
13198 }
13199 
13200 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13201 /// operators are mixed in a way that suggests that the programmer forgot that
13202 /// comparison operators have higher precedence. The most typical example of
13203 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13204 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13205                                       SourceLocation OpLoc, Expr *LHSExpr,
13206                                       Expr *RHSExpr) {
13207   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13208   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13209 
13210   // Check that one of the sides is a comparison operator and the other isn't.
13211   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13212   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13213   if (isLeftComp == isRightComp)
13214     return;
13215 
13216   // Bitwise operations are sometimes used as eager logical ops.
13217   // Don't diagnose this.
13218   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13219   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13220   if (isLeftBitwise || isRightBitwise)
13221     return;
13222 
13223   SourceRange DiagRange = isLeftComp
13224                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13225                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13226   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13227   SourceRange ParensRange =
13228       isLeftComp
13229           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13230           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13231 
13232   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13233     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13234   SuggestParentheses(Self, OpLoc,
13235     Self.PDiag(diag::note_precedence_silence) << OpStr,
13236     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13237   SuggestParentheses(Self, OpLoc,
13238     Self.PDiag(diag::note_precedence_bitwise_first)
13239       << BinaryOperator::getOpcodeStr(Opc),
13240     ParensRange);
13241 }
13242 
13243 /// It accepts a '&&' expr that is inside a '||' one.
13244 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13245 /// in parentheses.
13246 static void
13247 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13248                                        BinaryOperator *Bop) {
13249   assert(Bop->getOpcode() == BO_LAnd);
13250   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13251       << Bop->getSourceRange() << OpLoc;
13252   SuggestParentheses(Self, Bop->getOperatorLoc(),
13253     Self.PDiag(diag::note_precedence_silence)
13254       << Bop->getOpcodeStr(),
13255     Bop->getSourceRange());
13256 }
13257 
13258 /// Returns true if the given expression can be evaluated as a constant
13259 /// 'true'.
13260 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13261   bool Res;
13262   return !E->isValueDependent() &&
13263          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13264 }
13265 
13266 /// Returns true if the given expression can be evaluated as a constant
13267 /// 'false'.
13268 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13269   bool Res;
13270   return !E->isValueDependent() &&
13271          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13272 }
13273 
13274 /// Look for '&&' in the left hand of a '||' expr.
13275 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13276                                              Expr *LHSExpr, Expr *RHSExpr) {
13277   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13278     if (Bop->getOpcode() == BO_LAnd) {
13279       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13280       if (EvaluatesAsFalse(S, RHSExpr))
13281         return;
13282       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13283       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13284         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13285     } else if (Bop->getOpcode() == BO_LOr) {
13286       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13287         // If it's "a || b && 1 || c" we didn't warn earlier for
13288         // "a || b && 1", but warn now.
13289         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13290           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13291       }
13292     }
13293   }
13294 }
13295 
13296 /// Look for '&&' in the right hand of a '||' expr.
13297 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13298                                              Expr *LHSExpr, Expr *RHSExpr) {
13299   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13300     if (Bop->getOpcode() == BO_LAnd) {
13301       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13302       if (EvaluatesAsFalse(S, LHSExpr))
13303         return;
13304       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13305       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13306         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13307     }
13308   }
13309 }
13310 
13311 /// Look for bitwise op in the left or right hand of a bitwise op with
13312 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13313 /// the '&' expression in parentheses.
13314 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13315                                          SourceLocation OpLoc, Expr *SubExpr) {
13316   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13317     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13318       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13319         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13320         << Bop->getSourceRange() << OpLoc;
13321       SuggestParentheses(S, Bop->getOperatorLoc(),
13322         S.PDiag(diag::note_precedence_silence)
13323           << Bop->getOpcodeStr(),
13324         Bop->getSourceRange());
13325     }
13326   }
13327 }
13328 
13329 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13330                                     Expr *SubExpr, StringRef Shift) {
13331   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13332     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13333       StringRef Op = Bop->getOpcodeStr();
13334       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13335           << Bop->getSourceRange() << OpLoc << Shift << Op;
13336       SuggestParentheses(S, Bop->getOperatorLoc(),
13337           S.PDiag(diag::note_precedence_silence) << Op,
13338           Bop->getSourceRange());
13339     }
13340   }
13341 }
13342 
13343 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13344                                  Expr *LHSExpr, Expr *RHSExpr) {
13345   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13346   if (!OCE)
13347     return;
13348 
13349   FunctionDecl *FD = OCE->getDirectCallee();
13350   if (!FD || !FD->isOverloadedOperator())
13351     return;
13352 
13353   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13354   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13355     return;
13356 
13357   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13358       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13359       << (Kind == OO_LessLess);
13360   SuggestParentheses(S, OCE->getOperatorLoc(),
13361                      S.PDiag(diag::note_precedence_silence)
13362                          << (Kind == OO_LessLess ? "<<" : ">>"),
13363                      OCE->getSourceRange());
13364   SuggestParentheses(
13365       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13366       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13367 }
13368 
13369 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13370 /// precedence.
13371 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13372                                     SourceLocation OpLoc, Expr *LHSExpr,
13373                                     Expr *RHSExpr){
13374   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13375   if (BinaryOperator::isBitwiseOp(Opc))
13376     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13377 
13378   // Diagnose "arg1 & arg2 | arg3"
13379   if ((Opc == BO_Or || Opc == BO_Xor) &&
13380       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13381     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13382     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13383   }
13384 
13385   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13386   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13387   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13388     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13389     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13390   }
13391 
13392   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13393       || Opc == BO_Shr) {
13394     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13395     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13396     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13397   }
13398 
13399   // Warn on overloaded shift operators and comparisons, such as:
13400   // cout << 5 == 4;
13401   if (BinaryOperator::isComparisonOp(Opc))
13402     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13403 }
13404 
13405 // Binary Operators.  'Tok' is the token for the operator.
13406 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13407                             tok::TokenKind Kind,
13408                             Expr *LHSExpr, Expr *RHSExpr) {
13409   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13410   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13411   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13412 
13413   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13414   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13415 
13416   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13417 }
13418 
13419 /// Build an overloaded binary operator expression in the given scope.
13420 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13421                                        BinaryOperatorKind Opc,
13422                                        Expr *LHS, Expr *RHS) {
13423   switch (Opc) {
13424   case BO_Assign:
13425   case BO_DivAssign:
13426   case BO_RemAssign:
13427   case BO_SubAssign:
13428   case BO_AndAssign:
13429   case BO_OrAssign:
13430   case BO_XorAssign:
13431     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13432     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13433     break;
13434   default:
13435     break;
13436   }
13437 
13438   // Find all of the overloaded operators visible from this
13439   // point. We perform both an operator-name lookup from the local
13440   // scope and an argument-dependent lookup based on the types of
13441   // the arguments.
13442   UnresolvedSet<16> Functions;
13443   OverloadedOperatorKind OverOp
13444     = BinaryOperator::getOverloadedOperator(Opc);
13445   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13446     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13447                                    RHS->getType(), Functions);
13448 
13449   // In C++20 onwards, we may have a second operator to look up.
13450   if (S.getLangOpts().CPlusPlus2a) {
13451     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13452       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13453                                      RHS->getType(), Functions);
13454   }
13455 
13456   // Build the (potentially-overloaded, potentially-dependent)
13457   // binary operation.
13458   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13459 }
13460 
13461 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13462                             BinaryOperatorKind Opc,
13463                             Expr *LHSExpr, Expr *RHSExpr) {
13464   ExprResult LHS, RHS;
13465   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13466   if (!LHS.isUsable() || !RHS.isUsable())
13467     return ExprError();
13468   LHSExpr = LHS.get();
13469   RHSExpr = RHS.get();
13470 
13471   // We want to end up calling one of checkPseudoObjectAssignment
13472   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13473   // both expressions are overloadable or either is type-dependent),
13474   // or CreateBuiltinBinOp (in any other case).  We also want to get
13475   // any placeholder types out of the way.
13476 
13477   // Handle pseudo-objects in the LHS.
13478   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13479     // Assignments with a pseudo-object l-value need special analysis.
13480     if (pty->getKind() == BuiltinType::PseudoObject &&
13481         BinaryOperator::isAssignmentOp(Opc))
13482       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13483 
13484     // Don't resolve overloads if the other type is overloadable.
13485     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13486       // We can't actually test that if we still have a placeholder,
13487       // though.  Fortunately, none of the exceptions we see in that
13488       // code below are valid when the LHS is an overload set.  Note
13489       // that an overload set can be dependently-typed, but it never
13490       // instantiates to having an overloadable type.
13491       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13492       if (resolvedRHS.isInvalid()) return ExprError();
13493       RHSExpr = resolvedRHS.get();
13494 
13495       if (RHSExpr->isTypeDependent() ||
13496           RHSExpr->getType()->isOverloadableType())
13497         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13498     }
13499 
13500     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13501     // template, diagnose the missing 'template' keyword instead of diagnosing
13502     // an invalid use of a bound member function.
13503     //
13504     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13505     // to C++1z [over.over]/1.4, but we already checked for that case above.
13506     if (Opc == BO_LT && inTemplateInstantiation() &&
13507         (pty->getKind() == BuiltinType::BoundMember ||
13508          pty->getKind() == BuiltinType::Overload)) {
13509       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13510       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13511           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13512             return isa<FunctionTemplateDecl>(ND);
13513           })) {
13514         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13515                                 : OE->getNameLoc(),
13516              diag::err_template_kw_missing)
13517           << OE->getName().getAsString() << "";
13518         return ExprError();
13519       }
13520     }
13521 
13522     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13523     if (LHS.isInvalid()) return ExprError();
13524     LHSExpr = LHS.get();
13525   }
13526 
13527   // Handle pseudo-objects in the RHS.
13528   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13529     // An overload in the RHS can potentially be resolved by the type
13530     // being assigned to.
13531     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13532       if (getLangOpts().CPlusPlus &&
13533           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13534            LHSExpr->getType()->isOverloadableType()))
13535         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13536 
13537       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13538     }
13539 
13540     // Don't resolve overloads if the other type is overloadable.
13541     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13542         LHSExpr->getType()->isOverloadableType())
13543       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13544 
13545     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13546     if (!resolvedRHS.isUsable()) return ExprError();
13547     RHSExpr = resolvedRHS.get();
13548   }
13549 
13550   if (getLangOpts().CPlusPlus) {
13551     // If either expression is type-dependent, always build an
13552     // overloaded op.
13553     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13554       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13555 
13556     // Otherwise, build an overloaded op if either expression has an
13557     // overloadable type.
13558     if (LHSExpr->getType()->isOverloadableType() ||
13559         RHSExpr->getType()->isOverloadableType())
13560       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13561   }
13562 
13563   // Build a built-in binary operation.
13564   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13565 }
13566 
13567 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13568   if (T.isNull() || T->isDependentType())
13569     return false;
13570 
13571   if (!T->isPromotableIntegerType())
13572     return true;
13573 
13574   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13575 }
13576 
13577 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13578                                       UnaryOperatorKind Opc,
13579                                       Expr *InputExpr) {
13580   ExprResult Input = InputExpr;
13581   ExprValueKind VK = VK_RValue;
13582   ExprObjectKind OK = OK_Ordinary;
13583   QualType resultType;
13584   bool CanOverflow = false;
13585 
13586   bool ConvertHalfVec = false;
13587   if (getLangOpts().OpenCL) {
13588     QualType Ty = InputExpr->getType();
13589     // The only legal unary operation for atomics is '&'.
13590     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13591     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13592     // only with a builtin functions and therefore should be disallowed here.
13593         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13594         || Ty->isBlockPointerType())) {
13595       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13596                        << InputExpr->getType()
13597                        << Input.get()->getSourceRange());
13598     }
13599   }
13600   // Diagnose operations on the unsupported types for OpenMP device compilation.
13601   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13602     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13603         UnaryOperator::isArithmeticOp(Opc))
13604       checkOpenMPDeviceExpr(InputExpr);
13605   }
13606 
13607   switch (Opc) {
13608   case UO_PreInc:
13609   case UO_PreDec:
13610   case UO_PostInc:
13611   case UO_PostDec:
13612     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13613                                                 OpLoc,
13614                                                 Opc == UO_PreInc ||
13615                                                 Opc == UO_PostInc,
13616                                                 Opc == UO_PreInc ||
13617                                                 Opc == UO_PreDec);
13618     CanOverflow = isOverflowingIntegerType(Context, resultType);
13619     break;
13620   case UO_AddrOf:
13621     resultType = CheckAddressOfOperand(Input, OpLoc);
13622     CheckAddressOfNoDeref(InputExpr);
13623     RecordModifiableNonNullParam(*this, InputExpr);
13624     break;
13625   case UO_Deref: {
13626     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13627     if (Input.isInvalid()) return ExprError();
13628     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13629     break;
13630   }
13631   case UO_Plus:
13632   case UO_Minus:
13633     CanOverflow = Opc == UO_Minus &&
13634                   isOverflowingIntegerType(Context, Input.get()->getType());
13635     Input = UsualUnaryConversions(Input.get());
13636     if (Input.isInvalid()) return ExprError();
13637     // Unary plus and minus require promoting an operand of half vector to a
13638     // float vector and truncating the result back to a half vector. For now, we
13639     // do this only when HalfArgsAndReturns is set (that is, when the target is
13640     // arm or arm64).
13641     ConvertHalfVec =
13642         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13643 
13644     // If the operand is a half vector, promote it to a float vector.
13645     if (ConvertHalfVec)
13646       Input = convertVector(Input.get(), Context.FloatTy, *this);
13647     resultType = Input.get()->getType();
13648     if (resultType->isDependentType())
13649       break;
13650     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13651       break;
13652     else if (resultType->isVectorType() &&
13653              // The z vector extensions don't allow + or - with bool vectors.
13654              (!Context.getLangOpts().ZVector ||
13655               resultType->castAs<VectorType>()->getVectorKind() !=
13656               VectorType::AltiVecBool))
13657       break;
13658     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13659              Opc == UO_Plus &&
13660              resultType->isPointerType())
13661       break;
13662 
13663     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13664       << resultType << Input.get()->getSourceRange());
13665 
13666   case UO_Not: // bitwise complement
13667     Input = UsualUnaryConversions(Input.get());
13668     if (Input.isInvalid())
13669       return ExprError();
13670     resultType = Input.get()->getType();
13671     if (resultType->isDependentType())
13672       break;
13673     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13674     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13675       // C99 does not support '~' for complex conjugation.
13676       Diag(OpLoc, diag::ext_integer_complement_complex)
13677           << resultType << Input.get()->getSourceRange();
13678     else if (resultType->hasIntegerRepresentation())
13679       break;
13680     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13681       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13682       // on vector float types.
13683       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13684       if (!T->isIntegerType())
13685         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13686                           << resultType << Input.get()->getSourceRange());
13687     } else {
13688       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13689                        << resultType << Input.get()->getSourceRange());
13690     }
13691     break;
13692 
13693   case UO_LNot: // logical negation
13694     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13695     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13696     if (Input.isInvalid()) return ExprError();
13697     resultType = Input.get()->getType();
13698 
13699     // Though we still have to promote half FP to float...
13700     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13701       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13702       resultType = Context.FloatTy;
13703     }
13704 
13705     if (resultType->isDependentType())
13706       break;
13707     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13708       // C99 6.5.3.3p1: ok, fallthrough;
13709       if (Context.getLangOpts().CPlusPlus) {
13710         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13711         // operand contextually converted to bool.
13712         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13713                                   ScalarTypeToBooleanCastKind(resultType));
13714       } else if (Context.getLangOpts().OpenCL &&
13715                  Context.getLangOpts().OpenCLVersion < 120) {
13716         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13717         // operate on scalar float types.
13718         if (!resultType->isIntegerType() && !resultType->isPointerType())
13719           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13720                            << resultType << Input.get()->getSourceRange());
13721       }
13722     } else if (resultType->isExtVectorType()) {
13723       if (Context.getLangOpts().OpenCL &&
13724           Context.getLangOpts().OpenCLVersion < 120 &&
13725           !Context.getLangOpts().OpenCLCPlusPlus) {
13726         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13727         // operate on vector float types.
13728         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13729         if (!T->isIntegerType())
13730           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13731                            << resultType << Input.get()->getSourceRange());
13732       }
13733       // Vector logical not returns the signed variant of the operand type.
13734       resultType = GetSignedVectorType(resultType);
13735       break;
13736     } else {
13737       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13738       //        type in C++. We should allow that here too.
13739       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13740         << resultType << Input.get()->getSourceRange());
13741     }
13742 
13743     // LNot always has type int. C99 6.5.3.3p5.
13744     // In C++, it's bool. C++ 5.3.1p8
13745     resultType = Context.getLogicalOperationType();
13746     break;
13747   case UO_Real:
13748   case UO_Imag:
13749     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13750     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13751     // complex l-values to ordinary l-values and all other values to r-values.
13752     if (Input.isInvalid()) return ExprError();
13753     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13754       if (Input.get()->getValueKind() != VK_RValue &&
13755           Input.get()->getObjectKind() == OK_Ordinary)
13756         VK = Input.get()->getValueKind();
13757     } else if (!getLangOpts().CPlusPlus) {
13758       // In C, a volatile scalar is read by __imag. In C++, it is not.
13759       Input = DefaultLvalueConversion(Input.get());
13760     }
13761     break;
13762   case UO_Extension:
13763     resultType = Input.get()->getType();
13764     VK = Input.get()->getValueKind();
13765     OK = Input.get()->getObjectKind();
13766     break;
13767   case UO_Coawait:
13768     // It's unnecessary to represent the pass-through operator co_await in the
13769     // AST; just return the input expression instead.
13770     assert(!Input.get()->getType()->isDependentType() &&
13771                    "the co_await expression must be non-dependant before "
13772                    "building operator co_await");
13773     return Input;
13774   }
13775   if (resultType.isNull() || Input.isInvalid())
13776     return ExprError();
13777 
13778   // Check for array bounds violations in the operand of the UnaryOperator,
13779   // except for the '*' and '&' operators that have to be handled specially
13780   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13781   // that are explicitly defined as valid by the standard).
13782   if (Opc != UO_AddrOf && Opc != UO_Deref)
13783     CheckArrayAccess(Input.get());
13784 
13785   auto *UO = new (Context)
13786       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13787 
13788   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13789       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13790     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13791 
13792   // Convert the result back to a half vector.
13793   if (ConvertHalfVec)
13794     return convertVector(UO, Context.HalfTy, *this);
13795   return UO;
13796 }
13797 
13798 /// Determine whether the given expression is a qualified member
13799 /// access expression, of a form that could be turned into a pointer to member
13800 /// with the address-of operator.
13801 bool Sema::isQualifiedMemberAccess(Expr *E) {
13802   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13803     if (!DRE->getQualifier())
13804       return false;
13805 
13806     ValueDecl *VD = DRE->getDecl();
13807     if (!VD->isCXXClassMember())
13808       return false;
13809 
13810     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13811       return true;
13812     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13813       return Method->isInstance();
13814 
13815     return false;
13816   }
13817 
13818   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13819     if (!ULE->getQualifier())
13820       return false;
13821 
13822     for (NamedDecl *D : ULE->decls()) {
13823       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13824         if (Method->isInstance())
13825           return true;
13826       } else {
13827         // Overload set does not contain methods.
13828         break;
13829       }
13830     }
13831 
13832     return false;
13833   }
13834 
13835   return false;
13836 }
13837 
13838 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13839                               UnaryOperatorKind Opc, Expr *Input) {
13840   // First things first: handle placeholders so that the
13841   // overloaded-operator check considers the right type.
13842   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13843     // Increment and decrement of pseudo-object references.
13844     if (pty->getKind() == BuiltinType::PseudoObject &&
13845         UnaryOperator::isIncrementDecrementOp(Opc))
13846       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13847 
13848     // extension is always a builtin operator.
13849     if (Opc == UO_Extension)
13850       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13851 
13852     // & gets special logic for several kinds of placeholder.
13853     // The builtin code knows what to do.
13854     if (Opc == UO_AddrOf &&
13855         (pty->getKind() == BuiltinType::Overload ||
13856          pty->getKind() == BuiltinType::UnknownAny ||
13857          pty->getKind() == BuiltinType::BoundMember))
13858       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13859 
13860     // Anything else needs to be handled now.
13861     ExprResult Result = CheckPlaceholderExpr(Input);
13862     if (Result.isInvalid()) return ExprError();
13863     Input = Result.get();
13864   }
13865 
13866   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13867       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13868       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13869     // Find all of the overloaded operators visible from this
13870     // point. We perform both an operator-name lookup from the local
13871     // scope and an argument-dependent lookup based on the types of
13872     // the arguments.
13873     UnresolvedSet<16> Functions;
13874     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13875     if (S && OverOp != OO_None)
13876       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13877                                    Functions);
13878 
13879     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13880   }
13881 
13882   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13883 }
13884 
13885 // Unary Operators.  'Tok' is the token for the operator.
13886 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13887                               tok::TokenKind Op, Expr *Input) {
13888   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13889 }
13890 
13891 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13892 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13893                                 LabelDecl *TheDecl) {
13894   TheDecl->markUsed(Context);
13895   // Create the AST node.  The address of a label always has type 'void*'.
13896   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13897                                      Context.getPointerType(Context.VoidTy));
13898 }
13899 
13900 void Sema::ActOnStartStmtExpr() {
13901   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13902 }
13903 
13904 void Sema::ActOnStmtExprError() {
13905   // Note that function is also called by TreeTransform when leaving a
13906   // StmtExpr scope without rebuilding anything.
13907 
13908   DiscardCleanupsInEvaluationContext();
13909   PopExpressionEvaluationContext();
13910 }
13911 
13912 ExprResult
13913 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13914                     SourceLocation RPLoc) { // "({..})"
13915   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13916   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13917 
13918   if (hasAnyUnrecoverableErrorsInThisFunction())
13919     DiscardCleanupsInEvaluationContext();
13920   assert(!Cleanup.exprNeedsCleanups() &&
13921          "cleanups within StmtExpr not correctly bound!");
13922   PopExpressionEvaluationContext();
13923 
13924   // FIXME: there are a variety of strange constraints to enforce here, for
13925   // example, it is not possible to goto into a stmt expression apparently.
13926   // More semantic analysis is needed.
13927 
13928   // If there are sub-stmts in the compound stmt, take the type of the last one
13929   // as the type of the stmtexpr.
13930   QualType Ty = Context.VoidTy;
13931   bool StmtExprMayBindToTemp = false;
13932   if (!Compound->body_empty()) {
13933     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13934     if (const auto *LastStmt =
13935             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13936       if (const Expr *Value = LastStmt->getExprStmt()) {
13937         StmtExprMayBindToTemp = true;
13938         Ty = Value->getType();
13939       }
13940     }
13941   }
13942 
13943   // FIXME: Check that expression type is complete/non-abstract; statement
13944   // expressions are not lvalues.
13945   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13946   if (StmtExprMayBindToTemp)
13947     return MaybeBindToTemporary(ResStmtExpr);
13948   return ResStmtExpr;
13949 }
13950 
13951 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13952   if (ER.isInvalid())
13953     return ExprError();
13954 
13955   // Do function/array conversion on the last expression, but not
13956   // lvalue-to-rvalue.  However, initialize an unqualified type.
13957   ER = DefaultFunctionArrayConversion(ER.get());
13958   if (ER.isInvalid())
13959     return ExprError();
13960   Expr *E = ER.get();
13961 
13962   if (E->isTypeDependent())
13963     return E;
13964 
13965   // In ARC, if the final expression ends in a consume, splice
13966   // the consume out and bind it later.  In the alternate case
13967   // (when dealing with a retainable type), the result
13968   // initialization will create a produce.  In both cases the
13969   // result will be +1, and we'll need to balance that out with
13970   // a bind.
13971   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13972   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13973     return Cast->getSubExpr();
13974 
13975   // FIXME: Provide a better location for the initialization.
13976   return PerformCopyInitialization(
13977       InitializedEntity::InitializeStmtExprResult(
13978           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13979       SourceLocation(), E);
13980 }
13981 
13982 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13983                                       TypeSourceInfo *TInfo,
13984                                       ArrayRef<OffsetOfComponent> Components,
13985                                       SourceLocation RParenLoc) {
13986   QualType ArgTy = TInfo->getType();
13987   bool Dependent = ArgTy->isDependentType();
13988   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13989 
13990   // We must have at least one component that refers to the type, and the first
13991   // one is known to be a field designator.  Verify that the ArgTy represents
13992   // a struct/union/class.
13993   if (!Dependent && !ArgTy->isRecordType())
13994     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13995                        << ArgTy << TypeRange);
13996 
13997   // Type must be complete per C99 7.17p3 because a declaring a variable
13998   // with an incomplete type would be ill-formed.
13999   if (!Dependent
14000       && RequireCompleteType(BuiltinLoc, ArgTy,
14001                              diag::err_offsetof_incomplete_type, TypeRange))
14002     return ExprError();
14003 
14004   bool DidWarnAboutNonPOD = false;
14005   QualType CurrentType = ArgTy;
14006   SmallVector<OffsetOfNode, 4> Comps;
14007   SmallVector<Expr*, 4> Exprs;
14008   for (const OffsetOfComponent &OC : Components) {
14009     if (OC.isBrackets) {
14010       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14011       if (!CurrentType->isDependentType()) {
14012         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14013         if(!AT)
14014           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14015                            << CurrentType);
14016         CurrentType = AT->getElementType();
14017       } else
14018         CurrentType = Context.DependentTy;
14019 
14020       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14021       if (IdxRval.isInvalid())
14022         return ExprError();
14023       Expr *Idx = IdxRval.get();
14024 
14025       // The expression must be an integral expression.
14026       // FIXME: An integral constant expression?
14027       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14028           !Idx->getType()->isIntegerType())
14029         return ExprError(
14030             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14031             << Idx->getSourceRange());
14032 
14033       // Record this array index.
14034       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14035       Exprs.push_back(Idx);
14036       continue;
14037     }
14038 
14039     // Offset of a field.
14040     if (CurrentType->isDependentType()) {
14041       // We have the offset of a field, but we can't look into the dependent
14042       // type. Just record the identifier of the field.
14043       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14044       CurrentType = Context.DependentTy;
14045       continue;
14046     }
14047 
14048     // We need to have a complete type to look into.
14049     if (RequireCompleteType(OC.LocStart, CurrentType,
14050                             diag::err_offsetof_incomplete_type))
14051       return ExprError();
14052 
14053     // Look for the designated field.
14054     const RecordType *RC = CurrentType->getAs<RecordType>();
14055     if (!RC)
14056       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14057                        << CurrentType);
14058     RecordDecl *RD = RC->getDecl();
14059 
14060     // C++ [lib.support.types]p5:
14061     //   The macro offsetof accepts a restricted set of type arguments in this
14062     //   International Standard. type shall be a POD structure or a POD union
14063     //   (clause 9).
14064     // C++11 [support.types]p4:
14065     //   If type is not a standard-layout class (Clause 9), the results are
14066     //   undefined.
14067     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14068       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14069       unsigned DiagID =
14070         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14071                             : diag::ext_offsetof_non_pod_type;
14072 
14073       if (!IsSafe && !DidWarnAboutNonPOD &&
14074           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14075                               PDiag(DiagID)
14076                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14077                               << CurrentType))
14078         DidWarnAboutNonPOD = true;
14079     }
14080 
14081     // Look for the field.
14082     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14083     LookupQualifiedName(R, RD);
14084     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14085     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14086     if (!MemberDecl) {
14087       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14088         MemberDecl = IndirectMemberDecl->getAnonField();
14089     }
14090 
14091     if (!MemberDecl)
14092       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14093                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14094                                                               OC.LocEnd));
14095 
14096     // C99 7.17p3:
14097     //   (If the specified member is a bit-field, the behavior is undefined.)
14098     //
14099     // We diagnose this as an error.
14100     if (MemberDecl->isBitField()) {
14101       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14102         << MemberDecl->getDeclName()
14103         << SourceRange(BuiltinLoc, RParenLoc);
14104       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14105       return ExprError();
14106     }
14107 
14108     RecordDecl *Parent = MemberDecl->getParent();
14109     if (IndirectMemberDecl)
14110       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14111 
14112     // If the member was found in a base class, introduce OffsetOfNodes for
14113     // the base class indirections.
14114     CXXBasePaths Paths;
14115     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14116                       Paths)) {
14117       if (Paths.getDetectedVirtual()) {
14118         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14119           << MemberDecl->getDeclName()
14120           << SourceRange(BuiltinLoc, RParenLoc);
14121         return ExprError();
14122       }
14123 
14124       CXXBasePath &Path = Paths.front();
14125       for (const CXXBasePathElement &B : Path)
14126         Comps.push_back(OffsetOfNode(B.Base));
14127     }
14128 
14129     if (IndirectMemberDecl) {
14130       for (auto *FI : IndirectMemberDecl->chain()) {
14131         assert(isa<FieldDecl>(FI));
14132         Comps.push_back(OffsetOfNode(OC.LocStart,
14133                                      cast<FieldDecl>(FI), OC.LocEnd));
14134       }
14135     } else
14136       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14137 
14138     CurrentType = MemberDecl->getType().getNonReferenceType();
14139   }
14140 
14141   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14142                               Comps, Exprs, RParenLoc);
14143 }
14144 
14145 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14146                                       SourceLocation BuiltinLoc,
14147                                       SourceLocation TypeLoc,
14148                                       ParsedType ParsedArgTy,
14149                                       ArrayRef<OffsetOfComponent> Components,
14150                                       SourceLocation RParenLoc) {
14151 
14152   TypeSourceInfo *ArgTInfo;
14153   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14154   if (ArgTy.isNull())
14155     return ExprError();
14156 
14157   if (!ArgTInfo)
14158     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14159 
14160   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14161 }
14162 
14163 
14164 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14165                                  Expr *CondExpr,
14166                                  Expr *LHSExpr, Expr *RHSExpr,
14167                                  SourceLocation RPLoc) {
14168   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14169 
14170   ExprValueKind VK = VK_RValue;
14171   ExprObjectKind OK = OK_Ordinary;
14172   QualType resType;
14173   bool ValueDependent = false;
14174   bool CondIsTrue = false;
14175   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14176     resType = Context.DependentTy;
14177     ValueDependent = true;
14178   } else {
14179     // The conditional expression is required to be a constant expression.
14180     llvm::APSInt condEval(32);
14181     ExprResult CondICE
14182       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14183           diag::err_typecheck_choose_expr_requires_constant, false);
14184     if (CondICE.isInvalid())
14185       return ExprError();
14186     CondExpr = CondICE.get();
14187     CondIsTrue = condEval.getZExtValue();
14188 
14189     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14190     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14191 
14192     resType = ActiveExpr->getType();
14193     ValueDependent = ActiveExpr->isValueDependent();
14194     VK = ActiveExpr->getValueKind();
14195     OK = ActiveExpr->getObjectKind();
14196   }
14197 
14198   return new (Context)
14199       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14200                  CondIsTrue, resType->isDependentType(), ValueDependent);
14201 }
14202 
14203 //===----------------------------------------------------------------------===//
14204 // Clang Extensions.
14205 //===----------------------------------------------------------------------===//
14206 
14207 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14208 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14209   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14210 
14211   if (LangOpts.CPlusPlus) {
14212     MangleNumberingContext *MCtx;
14213     Decl *ManglingContextDecl;
14214     std::tie(MCtx, ManglingContextDecl) =
14215         getCurrentMangleNumberContext(Block->getDeclContext());
14216     if (MCtx) {
14217       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14218       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14219     }
14220   }
14221 
14222   PushBlockScope(CurScope, Block);
14223   CurContext->addDecl(Block);
14224   if (CurScope)
14225     PushDeclContext(CurScope, Block);
14226   else
14227     CurContext = Block;
14228 
14229   getCurBlock()->HasImplicitReturnType = true;
14230 
14231   // Enter a new evaluation context to insulate the block from any
14232   // cleanups from the enclosing full-expression.
14233   PushExpressionEvaluationContext(
14234       ExpressionEvaluationContext::PotentiallyEvaluated);
14235 }
14236 
14237 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14238                                Scope *CurScope) {
14239   assert(ParamInfo.getIdentifier() == nullptr &&
14240          "block-id should have no identifier!");
14241   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14242   BlockScopeInfo *CurBlock = getCurBlock();
14243 
14244   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14245   QualType T = Sig->getType();
14246 
14247   // FIXME: We should allow unexpanded parameter packs here, but that would,
14248   // in turn, make the block expression contain unexpanded parameter packs.
14249   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14250     // Drop the parameters.
14251     FunctionProtoType::ExtProtoInfo EPI;
14252     EPI.HasTrailingReturn = false;
14253     EPI.TypeQuals.addConst();
14254     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14255     Sig = Context.getTrivialTypeSourceInfo(T);
14256   }
14257 
14258   // GetTypeForDeclarator always produces a function type for a block
14259   // literal signature.  Furthermore, it is always a FunctionProtoType
14260   // unless the function was written with a typedef.
14261   assert(T->isFunctionType() &&
14262          "GetTypeForDeclarator made a non-function block signature");
14263 
14264   // Look for an explicit signature in that function type.
14265   FunctionProtoTypeLoc ExplicitSignature;
14266 
14267   if ((ExplicitSignature = Sig->getTypeLoc()
14268                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14269 
14270     // Check whether that explicit signature was synthesized by
14271     // GetTypeForDeclarator.  If so, don't save that as part of the
14272     // written signature.
14273     if (ExplicitSignature.getLocalRangeBegin() ==
14274         ExplicitSignature.getLocalRangeEnd()) {
14275       // This would be much cheaper if we stored TypeLocs instead of
14276       // TypeSourceInfos.
14277       TypeLoc Result = ExplicitSignature.getReturnLoc();
14278       unsigned Size = Result.getFullDataSize();
14279       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14280       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14281 
14282       ExplicitSignature = FunctionProtoTypeLoc();
14283     }
14284   }
14285 
14286   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14287   CurBlock->FunctionType = T;
14288 
14289   const FunctionType *Fn = T->getAs<FunctionType>();
14290   QualType RetTy = Fn->getReturnType();
14291   bool isVariadic =
14292     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14293 
14294   CurBlock->TheDecl->setIsVariadic(isVariadic);
14295 
14296   // Context.DependentTy is used as a placeholder for a missing block
14297   // return type.  TODO:  what should we do with declarators like:
14298   //   ^ * { ... }
14299   // If the answer is "apply template argument deduction"....
14300   if (RetTy != Context.DependentTy) {
14301     CurBlock->ReturnType = RetTy;
14302     CurBlock->TheDecl->setBlockMissingReturnType(false);
14303     CurBlock->HasImplicitReturnType = false;
14304   }
14305 
14306   // Push block parameters from the declarator if we had them.
14307   SmallVector<ParmVarDecl*, 8> Params;
14308   if (ExplicitSignature) {
14309     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14310       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14311       if (Param->getIdentifier() == nullptr &&
14312           !Param->isImplicit() &&
14313           !Param->isInvalidDecl() &&
14314           !getLangOpts().CPlusPlus)
14315         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14316       Params.push_back(Param);
14317     }
14318 
14319   // Fake up parameter variables if we have a typedef, like
14320   //   ^ fntype { ... }
14321   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14322     for (const auto &I : Fn->param_types()) {
14323       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14324           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14325       Params.push_back(Param);
14326     }
14327   }
14328 
14329   // Set the parameters on the block decl.
14330   if (!Params.empty()) {
14331     CurBlock->TheDecl->setParams(Params);
14332     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14333                              /*CheckParameterNames=*/false);
14334   }
14335 
14336   // Finally we can process decl attributes.
14337   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14338 
14339   // Put the parameter variables in scope.
14340   for (auto AI : CurBlock->TheDecl->parameters()) {
14341     AI->setOwningFunction(CurBlock->TheDecl);
14342 
14343     // If this has an identifier, add it to the scope stack.
14344     if (AI->getIdentifier()) {
14345       CheckShadow(CurBlock->TheScope, AI);
14346 
14347       PushOnScopeChains(AI, CurBlock->TheScope);
14348     }
14349   }
14350 }
14351 
14352 /// ActOnBlockError - If there is an error parsing a block, this callback
14353 /// is invoked to pop the information about the block from the action impl.
14354 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14355   // Leave the expression-evaluation context.
14356   DiscardCleanupsInEvaluationContext();
14357   PopExpressionEvaluationContext();
14358 
14359   // Pop off CurBlock, handle nested blocks.
14360   PopDeclContext();
14361   PopFunctionScopeInfo();
14362 }
14363 
14364 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14365 /// literal was successfully completed.  ^(int x){...}
14366 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14367                                     Stmt *Body, Scope *CurScope) {
14368   // If blocks are disabled, emit an error.
14369   if (!LangOpts.Blocks)
14370     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14371 
14372   // Leave the expression-evaluation context.
14373   if (hasAnyUnrecoverableErrorsInThisFunction())
14374     DiscardCleanupsInEvaluationContext();
14375   assert(!Cleanup.exprNeedsCleanups() &&
14376          "cleanups within block not correctly bound!");
14377   PopExpressionEvaluationContext();
14378 
14379   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14380   BlockDecl *BD = BSI->TheDecl;
14381 
14382   if (BSI->HasImplicitReturnType)
14383     deduceClosureReturnType(*BSI);
14384 
14385   QualType RetTy = Context.VoidTy;
14386   if (!BSI->ReturnType.isNull())
14387     RetTy = BSI->ReturnType;
14388 
14389   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14390   QualType BlockTy;
14391 
14392   // If the user wrote a function type in some form, try to use that.
14393   if (!BSI->FunctionType.isNull()) {
14394     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14395 
14396     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14397     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14398 
14399     // Turn protoless block types into nullary block types.
14400     if (isa<FunctionNoProtoType>(FTy)) {
14401       FunctionProtoType::ExtProtoInfo EPI;
14402       EPI.ExtInfo = Ext;
14403       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14404 
14405     // Otherwise, if we don't need to change anything about the function type,
14406     // preserve its sugar structure.
14407     } else if (FTy->getReturnType() == RetTy &&
14408                (!NoReturn || FTy->getNoReturnAttr())) {
14409       BlockTy = BSI->FunctionType;
14410 
14411     // Otherwise, make the minimal modifications to the function type.
14412     } else {
14413       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14414       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14415       EPI.TypeQuals = Qualifiers();
14416       EPI.ExtInfo = Ext;
14417       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14418     }
14419 
14420   // If we don't have a function type, just build one from nothing.
14421   } else {
14422     FunctionProtoType::ExtProtoInfo EPI;
14423     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14424     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14425   }
14426 
14427   DiagnoseUnusedParameters(BD->parameters());
14428   BlockTy = Context.getBlockPointerType(BlockTy);
14429 
14430   // If needed, diagnose invalid gotos and switches in the block.
14431   if (getCurFunction()->NeedsScopeChecking() &&
14432       !PP.isCodeCompletionEnabled())
14433     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14434 
14435   BD->setBody(cast<CompoundStmt>(Body));
14436 
14437   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14438     DiagnoseUnguardedAvailabilityViolations(BD);
14439 
14440   // Try to apply the named return value optimization. We have to check again
14441   // if we can do this, though, because blocks keep return statements around
14442   // to deduce an implicit return type.
14443   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14444       !BD->isDependentContext())
14445     computeNRVO(Body, BSI);
14446 
14447   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14448       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14449     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14450                           NTCUK_Destruct|NTCUK_Copy);
14451 
14452   PopDeclContext();
14453 
14454   // Pop the block scope now but keep it alive to the end of this function.
14455   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14456   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14457 
14458   // Set the captured variables on the block.
14459   SmallVector<BlockDecl::Capture, 4> Captures;
14460   for (Capture &Cap : BSI->Captures) {
14461     if (Cap.isInvalid() || Cap.isThisCapture())
14462       continue;
14463 
14464     VarDecl *Var = Cap.getVariable();
14465     Expr *CopyExpr = nullptr;
14466     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14467       if (const RecordType *Record =
14468               Cap.getCaptureType()->getAs<RecordType>()) {
14469         // The capture logic needs the destructor, so make sure we mark it.
14470         // Usually this is unnecessary because most local variables have
14471         // their destructors marked at declaration time, but parameters are
14472         // an exception because it's technically only the call site that
14473         // actually requires the destructor.
14474         if (isa<ParmVarDecl>(Var))
14475           FinalizeVarWithDestructor(Var, Record);
14476 
14477         // Enter a separate potentially-evaluated context while building block
14478         // initializers to isolate their cleanups from those of the block
14479         // itself.
14480         // FIXME: Is this appropriate even when the block itself occurs in an
14481         // unevaluated operand?
14482         EnterExpressionEvaluationContext EvalContext(
14483             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14484 
14485         SourceLocation Loc = Cap.getLocation();
14486 
14487         ExprResult Result = BuildDeclarationNameExpr(
14488             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14489 
14490         // According to the blocks spec, the capture of a variable from
14491         // the stack requires a const copy constructor.  This is not true
14492         // of the copy/move done to move a __block variable to the heap.
14493         if (!Result.isInvalid() &&
14494             !Result.get()->getType().isConstQualified()) {
14495           Result = ImpCastExprToType(Result.get(),
14496                                      Result.get()->getType().withConst(),
14497                                      CK_NoOp, VK_LValue);
14498         }
14499 
14500         if (!Result.isInvalid()) {
14501           Result = PerformCopyInitialization(
14502               InitializedEntity::InitializeBlock(Var->getLocation(),
14503                                                  Cap.getCaptureType(), false),
14504               Loc, Result.get());
14505         }
14506 
14507         // Build a full-expression copy expression if initialization
14508         // succeeded and used a non-trivial constructor.  Recover from
14509         // errors by pretending that the copy isn't necessary.
14510         if (!Result.isInvalid() &&
14511             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14512                 ->isTrivial()) {
14513           Result = MaybeCreateExprWithCleanups(Result);
14514           CopyExpr = Result.get();
14515         }
14516       }
14517     }
14518 
14519     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14520                               CopyExpr);
14521     Captures.push_back(NewCap);
14522   }
14523   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14524 
14525   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14526 
14527   // If the block isn't obviously global, i.e. it captures anything at
14528   // all, then we need to do a few things in the surrounding context:
14529   if (Result->getBlockDecl()->hasCaptures()) {
14530     // First, this expression has a new cleanup object.
14531     ExprCleanupObjects.push_back(Result->getBlockDecl());
14532     Cleanup.setExprNeedsCleanups(true);
14533 
14534     // It also gets a branch-protected scope if any of the captured
14535     // variables needs destruction.
14536     for (const auto &CI : Result->getBlockDecl()->captures()) {
14537       const VarDecl *var = CI.getVariable();
14538       if (var->getType().isDestructedType() != QualType::DK_none) {
14539         setFunctionHasBranchProtectedScope();
14540         break;
14541       }
14542     }
14543   }
14544 
14545   if (getCurFunction())
14546     getCurFunction()->addBlock(BD);
14547 
14548   return Result;
14549 }
14550 
14551 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14552                             SourceLocation RPLoc) {
14553   TypeSourceInfo *TInfo;
14554   GetTypeFromParser(Ty, &TInfo);
14555   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14556 }
14557 
14558 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14559                                 Expr *E, TypeSourceInfo *TInfo,
14560                                 SourceLocation RPLoc) {
14561   Expr *OrigExpr = E;
14562   bool IsMS = false;
14563 
14564   // CUDA device code does not support varargs.
14565   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14566     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14567       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14568       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14569         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14570     }
14571   }
14572 
14573   // NVPTX does not support va_arg expression.
14574   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14575       Context.getTargetInfo().getTriple().isNVPTX())
14576     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14577 
14578   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14579   // as Microsoft ABI on an actual Microsoft platform, where
14580   // __builtin_ms_va_list and __builtin_va_list are the same.)
14581   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14582       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14583     QualType MSVaListType = Context.getBuiltinMSVaListType();
14584     if (Context.hasSameType(MSVaListType, E->getType())) {
14585       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14586         return ExprError();
14587       IsMS = true;
14588     }
14589   }
14590 
14591   // Get the va_list type
14592   QualType VaListType = Context.getBuiltinVaListType();
14593   if (!IsMS) {
14594     if (VaListType->isArrayType()) {
14595       // Deal with implicit array decay; for example, on x86-64,
14596       // va_list is an array, but it's supposed to decay to
14597       // a pointer for va_arg.
14598       VaListType = Context.getArrayDecayedType(VaListType);
14599       // Make sure the input expression also decays appropriately.
14600       ExprResult Result = UsualUnaryConversions(E);
14601       if (Result.isInvalid())
14602         return ExprError();
14603       E = Result.get();
14604     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14605       // If va_list is a record type and we are compiling in C++ mode,
14606       // check the argument using reference binding.
14607       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14608           Context, Context.getLValueReferenceType(VaListType), false);
14609       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14610       if (Init.isInvalid())
14611         return ExprError();
14612       E = Init.getAs<Expr>();
14613     } else {
14614       // Otherwise, the va_list argument must be an l-value because
14615       // it is modified by va_arg.
14616       if (!E->isTypeDependent() &&
14617           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14618         return ExprError();
14619     }
14620   }
14621 
14622   if (!IsMS && !E->isTypeDependent() &&
14623       !Context.hasSameType(VaListType, E->getType()))
14624     return ExprError(
14625         Diag(E->getBeginLoc(),
14626              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14627         << OrigExpr->getType() << E->getSourceRange());
14628 
14629   if (!TInfo->getType()->isDependentType()) {
14630     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14631                             diag::err_second_parameter_to_va_arg_incomplete,
14632                             TInfo->getTypeLoc()))
14633       return ExprError();
14634 
14635     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14636                                TInfo->getType(),
14637                                diag::err_second_parameter_to_va_arg_abstract,
14638                                TInfo->getTypeLoc()))
14639       return ExprError();
14640 
14641     if (!TInfo->getType().isPODType(Context)) {
14642       Diag(TInfo->getTypeLoc().getBeginLoc(),
14643            TInfo->getType()->isObjCLifetimeType()
14644              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14645              : diag::warn_second_parameter_to_va_arg_not_pod)
14646         << TInfo->getType()
14647         << TInfo->getTypeLoc().getSourceRange();
14648     }
14649 
14650     // Check for va_arg where arguments of the given type will be promoted
14651     // (i.e. this va_arg is guaranteed to have undefined behavior).
14652     QualType PromoteType;
14653     if (TInfo->getType()->isPromotableIntegerType()) {
14654       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14655       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14656         PromoteType = QualType();
14657     }
14658     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14659       PromoteType = Context.DoubleTy;
14660     if (!PromoteType.isNull())
14661       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14662                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14663                           << TInfo->getType()
14664                           << PromoteType
14665                           << TInfo->getTypeLoc().getSourceRange());
14666   }
14667 
14668   QualType T = TInfo->getType().getNonLValueExprType(Context);
14669   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14670 }
14671 
14672 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14673   // The type of __null will be int or long, depending on the size of
14674   // pointers on the target.
14675   QualType Ty;
14676   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14677   if (pw == Context.getTargetInfo().getIntWidth())
14678     Ty = Context.IntTy;
14679   else if (pw == Context.getTargetInfo().getLongWidth())
14680     Ty = Context.LongTy;
14681   else if (pw == Context.getTargetInfo().getLongLongWidth())
14682     Ty = Context.LongLongTy;
14683   else {
14684     llvm_unreachable("I don't know size of pointer!");
14685   }
14686 
14687   return new (Context) GNUNullExpr(Ty, TokenLoc);
14688 }
14689 
14690 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14691                                     SourceLocation BuiltinLoc,
14692                                     SourceLocation RPLoc) {
14693   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14694 }
14695 
14696 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14697                                     SourceLocation BuiltinLoc,
14698                                     SourceLocation RPLoc,
14699                                     DeclContext *ParentContext) {
14700   return new (Context)
14701       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14702 }
14703 
14704 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14705                                               bool Diagnose) {
14706   if (!getLangOpts().ObjC)
14707     return false;
14708 
14709   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14710   if (!PT)
14711     return false;
14712 
14713   if (!PT->isObjCIdType()) {
14714     // Check if the destination is the 'NSString' interface.
14715     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14716     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14717       return false;
14718   }
14719 
14720   // Ignore any parens, implicit casts (should only be
14721   // array-to-pointer decays), and not-so-opaque values.  The last is
14722   // important for making this trigger for property assignments.
14723   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14724   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14725     if (OV->getSourceExpr())
14726       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14727 
14728   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14729   if (!SL || !SL->isAscii())
14730     return false;
14731   if (Diagnose) {
14732     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14733         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14734     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14735   }
14736   return true;
14737 }
14738 
14739 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14740                                               const Expr *SrcExpr) {
14741   if (!DstType->isFunctionPointerType() ||
14742       !SrcExpr->getType()->isFunctionType())
14743     return false;
14744 
14745   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14746   if (!DRE)
14747     return false;
14748 
14749   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14750   if (!FD)
14751     return false;
14752 
14753   return !S.checkAddressOfFunctionIsAvailable(FD,
14754                                               /*Complain=*/true,
14755                                               SrcExpr->getBeginLoc());
14756 }
14757 
14758 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14759                                     SourceLocation Loc,
14760                                     QualType DstType, QualType SrcType,
14761                                     Expr *SrcExpr, AssignmentAction Action,
14762                                     bool *Complained) {
14763   if (Complained)
14764     *Complained = false;
14765 
14766   // Decode the result (notice that AST's are still created for extensions).
14767   bool CheckInferredResultType = false;
14768   bool isInvalid = false;
14769   unsigned DiagKind = 0;
14770   FixItHint Hint;
14771   ConversionFixItGenerator ConvHints;
14772   bool MayHaveConvFixit = false;
14773   bool MayHaveFunctionDiff = false;
14774   const ObjCInterfaceDecl *IFace = nullptr;
14775   const ObjCProtocolDecl *PDecl = nullptr;
14776 
14777   switch (ConvTy) {
14778   case Compatible:
14779       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14780       return false;
14781 
14782   case PointerToInt:
14783     DiagKind = diag::ext_typecheck_convert_pointer_int;
14784     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14785     MayHaveConvFixit = true;
14786     break;
14787   case IntToPointer:
14788     DiagKind = diag::ext_typecheck_convert_int_pointer;
14789     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14790     MayHaveConvFixit = true;
14791     break;
14792   case IncompatiblePointer:
14793     if (Action == AA_Passing_CFAudited)
14794       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14795     else if (SrcType->isFunctionPointerType() &&
14796              DstType->isFunctionPointerType())
14797       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14798     else
14799       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14800 
14801     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14802       SrcType->isObjCObjectPointerType();
14803     if (Hint.isNull() && !CheckInferredResultType) {
14804       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14805     }
14806     else if (CheckInferredResultType) {
14807       SrcType = SrcType.getUnqualifiedType();
14808       DstType = DstType.getUnqualifiedType();
14809     }
14810     MayHaveConvFixit = true;
14811     break;
14812   case IncompatiblePointerSign:
14813     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14814     break;
14815   case FunctionVoidPointer:
14816     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14817     break;
14818   case IncompatiblePointerDiscardsQualifiers: {
14819     // Perform array-to-pointer decay if necessary.
14820     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14821 
14822     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14823     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14824     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14825       DiagKind = diag::err_typecheck_incompatible_address_space;
14826       break;
14827 
14828     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14829       DiagKind = diag::err_typecheck_incompatible_ownership;
14830       break;
14831     }
14832 
14833     llvm_unreachable("unknown error case for discarding qualifiers!");
14834     // fallthrough
14835   }
14836   case CompatiblePointerDiscardsQualifiers:
14837     // If the qualifiers lost were because we were applying the
14838     // (deprecated) C++ conversion from a string literal to a char*
14839     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14840     // Ideally, this check would be performed in
14841     // checkPointerTypesForAssignment. However, that would require a
14842     // bit of refactoring (so that the second argument is an
14843     // expression, rather than a type), which should be done as part
14844     // of a larger effort to fix checkPointerTypesForAssignment for
14845     // C++ semantics.
14846     if (getLangOpts().CPlusPlus &&
14847         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14848       return false;
14849     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14850     break;
14851   case IncompatibleNestedPointerQualifiers:
14852     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14853     break;
14854   case IncompatibleNestedPointerAddressSpaceMismatch:
14855     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14856     break;
14857   case IntToBlockPointer:
14858     DiagKind = diag::err_int_to_block_pointer;
14859     break;
14860   case IncompatibleBlockPointer:
14861     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14862     break;
14863   case IncompatibleObjCQualifiedId: {
14864     if (SrcType->isObjCQualifiedIdType()) {
14865       const ObjCObjectPointerType *srcOPT =
14866                 SrcType->castAs<ObjCObjectPointerType>();
14867       for (auto *srcProto : srcOPT->quals()) {
14868         PDecl = srcProto;
14869         break;
14870       }
14871       if (const ObjCInterfaceType *IFaceT =
14872             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14873         IFace = IFaceT->getDecl();
14874     }
14875     else if (DstType->isObjCQualifiedIdType()) {
14876       const ObjCObjectPointerType *dstOPT =
14877         DstType->castAs<ObjCObjectPointerType>();
14878       for (auto *dstProto : dstOPT->quals()) {
14879         PDecl = dstProto;
14880         break;
14881       }
14882       if (const ObjCInterfaceType *IFaceT =
14883             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14884         IFace = IFaceT->getDecl();
14885     }
14886     DiagKind = diag::warn_incompatible_qualified_id;
14887     break;
14888   }
14889   case IncompatibleVectors:
14890     DiagKind = diag::warn_incompatible_vectors;
14891     break;
14892   case IncompatibleObjCWeakRef:
14893     DiagKind = diag::err_arc_weak_unavailable_assign;
14894     break;
14895   case Incompatible:
14896     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14897       if (Complained)
14898         *Complained = true;
14899       return true;
14900     }
14901 
14902     DiagKind = diag::err_typecheck_convert_incompatible;
14903     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14904     MayHaveConvFixit = true;
14905     isInvalid = true;
14906     MayHaveFunctionDiff = true;
14907     break;
14908   }
14909 
14910   QualType FirstType, SecondType;
14911   switch (Action) {
14912   case AA_Assigning:
14913   case AA_Initializing:
14914     // The destination type comes first.
14915     FirstType = DstType;
14916     SecondType = SrcType;
14917     break;
14918 
14919   case AA_Returning:
14920   case AA_Passing:
14921   case AA_Passing_CFAudited:
14922   case AA_Converting:
14923   case AA_Sending:
14924   case AA_Casting:
14925     // The source type comes first.
14926     FirstType = SrcType;
14927     SecondType = DstType;
14928     break;
14929   }
14930 
14931   PartialDiagnostic FDiag = PDiag(DiagKind);
14932   if (Action == AA_Passing_CFAudited)
14933     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14934   else
14935     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14936 
14937   // If we can fix the conversion, suggest the FixIts.
14938   assert(ConvHints.isNull() || Hint.isNull());
14939   if (!ConvHints.isNull()) {
14940     for (FixItHint &H : ConvHints.Hints)
14941       FDiag << H;
14942   } else {
14943     FDiag << Hint;
14944   }
14945   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14946 
14947   if (MayHaveFunctionDiff)
14948     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14949 
14950   Diag(Loc, FDiag);
14951   if (DiagKind == diag::warn_incompatible_qualified_id &&
14952       PDecl && IFace && !IFace->hasDefinition())
14953       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14954         << IFace << PDecl;
14955 
14956   if (SecondType == Context.OverloadTy)
14957     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14958                               FirstType, /*TakingAddress=*/true);
14959 
14960   if (CheckInferredResultType)
14961     EmitRelatedResultTypeNote(SrcExpr);
14962 
14963   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14964     EmitRelatedResultTypeNoteForReturn(DstType);
14965 
14966   if (Complained)
14967     *Complained = true;
14968   return isInvalid;
14969 }
14970 
14971 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14972                                                  llvm::APSInt *Result) {
14973   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14974   public:
14975     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14976       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14977     }
14978   } Diagnoser;
14979 
14980   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14981 }
14982 
14983 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14984                                                  llvm::APSInt *Result,
14985                                                  unsigned DiagID,
14986                                                  bool AllowFold) {
14987   class IDDiagnoser : public VerifyICEDiagnoser {
14988     unsigned DiagID;
14989 
14990   public:
14991     IDDiagnoser(unsigned DiagID)
14992       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14993 
14994     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14995       S.Diag(Loc, DiagID) << SR;
14996     }
14997   } Diagnoser(DiagID);
14998 
14999   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15000 }
15001 
15002 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15003                                             SourceRange SR) {
15004   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15005 }
15006 
15007 ExprResult
15008 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15009                                       VerifyICEDiagnoser &Diagnoser,
15010                                       bool AllowFold) {
15011   SourceLocation DiagLoc = E->getBeginLoc();
15012 
15013   if (getLangOpts().CPlusPlus11) {
15014     // C++11 [expr.const]p5:
15015     //   If an expression of literal class type is used in a context where an
15016     //   integral constant expression is required, then that class type shall
15017     //   have a single non-explicit conversion function to an integral or
15018     //   unscoped enumeration type
15019     ExprResult Converted;
15020     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15021     public:
15022       CXX11ConvertDiagnoser(bool Silent)
15023           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15024                                 Silent, true) {}
15025 
15026       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15027                                            QualType T) override {
15028         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15029       }
15030 
15031       SemaDiagnosticBuilder diagnoseIncomplete(
15032           Sema &S, SourceLocation Loc, QualType T) override {
15033         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15034       }
15035 
15036       SemaDiagnosticBuilder diagnoseExplicitConv(
15037           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15038         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15039       }
15040 
15041       SemaDiagnosticBuilder noteExplicitConv(
15042           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15043         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15044                  << ConvTy->isEnumeralType() << ConvTy;
15045       }
15046 
15047       SemaDiagnosticBuilder diagnoseAmbiguous(
15048           Sema &S, SourceLocation Loc, QualType T) override {
15049         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15050       }
15051 
15052       SemaDiagnosticBuilder noteAmbiguous(
15053           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15054         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15055                  << ConvTy->isEnumeralType() << ConvTy;
15056       }
15057 
15058       SemaDiagnosticBuilder diagnoseConversion(
15059           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15060         llvm_unreachable("conversion functions are permitted");
15061       }
15062     } ConvertDiagnoser(Diagnoser.Suppress);
15063 
15064     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15065                                                     ConvertDiagnoser);
15066     if (Converted.isInvalid())
15067       return Converted;
15068     E = Converted.get();
15069     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15070       return ExprError();
15071   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15072     // An ICE must be of integral or unscoped enumeration type.
15073     if (!Diagnoser.Suppress)
15074       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15075     return ExprError();
15076   }
15077 
15078   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15079   // in the non-ICE case.
15080   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15081     if (Result)
15082       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15083     if (!isa<ConstantExpr>(E))
15084       E = ConstantExpr::Create(Context, E);
15085     return E;
15086   }
15087 
15088   Expr::EvalResult EvalResult;
15089   SmallVector<PartialDiagnosticAt, 8> Notes;
15090   EvalResult.Diag = &Notes;
15091 
15092   // Try to evaluate the expression, and produce diagnostics explaining why it's
15093   // not a constant expression as a side-effect.
15094   bool Folded =
15095       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15096       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15097 
15098   if (!isa<ConstantExpr>(E))
15099     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15100 
15101   // In C++11, we can rely on diagnostics being produced for any expression
15102   // which is not a constant expression. If no diagnostics were produced, then
15103   // this is a constant expression.
15104   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15105     if (Result)
15106       *Result = EvalResult.Val.getInt();
15107     return E;
15108   }
15109 
15110   // If our only note is the usual "invalid subexpression" note, just point
15111   // the caret at its location rather than producing an essentially
15112   // redundant note.
15113   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15114         diag::note_invalid_subexpr_in_const_expr) {
15115     DiagLoc = Notes[0].first;
15116     Notes.clear();
15117   }
15118 
15119   if (!Folded || !AllowFold) {
15120     if (!Diagnoser.Suppress) {
15121       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15122       for (const PartialDiagnosticAt &Note : Notes)
15123         Diag(Note.first, Note.second);
15124     }
15125 
15126     return ExprError();
15127   }
15128 
15129   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15130   for (const PartialDiagnosticAt &Note : Notes)
15131     Diag(Note.first, Note.second);
15132 
15133   if (Result)
15134     *Result = EvalResult.Val.getInt();
15135   return E;
15136 }
15137 
15138 namespace {
15139   // Handle the case where we conclude a expression which we speculatively
15140   // considered to be unevaluated is actually evaluated.
15141   class TransformToPE : public TreeTransform<TransformToPE> {
15142     typedef TreeTransform<TransformToPE> BaseTransform;
15143 
15144   public:
15145     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15146 
15147     // Make sure we redo semantic analysis
15148     bool AlwaysRebuild() { return true; }
15149     bool ReplacingOriginal() { return true; }
15150 
15151     // We need to special-case DeclRefExprs referring to FieldDecls which
15152     // are not part of a member pointer formation; normal TreeTransforming
15153     // doesn't catch this case because of the way we represent them in the AST.
15154     // FIXME: This is a bit ugly; is it really the best way to handle this
15155     // case?
15156     //
15157     // Error on DeclRefExprs referring to FieldDecls.
15158     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15159       if (isa<FieldDecl>(E->getDecl()) &&
15160           !SemaRef.isUnevaluatedContext())
15161         return SemaRef.Diag(E->getLocation(),
15162                             diag::err_invalid_non_static_member_use)
15163             << E->getDecl() << E->getSourceRange();
15164 
15165       return BaseTransform::TransformDeclRefExpr(E);
15166     }
15167 
15168     // Exception: filter out member pointer formation
15169     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15170       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15171         return E;
15172 
15173       return BaseTransform::TransformUnaryOperator(E);
15174     }
15175 
15176     // The body of a lambda-expression is in a separate expression evaluation
15177     // context so never needs to be transformed.
15178     // FIXME: Ideally we wouldn't transform the closure type either, and would
15179     // just recreate the capture expressions and lambda expression.
15180     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15181       return SkipLambdaBody(E, Body);
15182     }
15183   };
15184 }
15185 
15186 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15187   assert(isUnevaluatedContext() &&
15188          "Should only transform unevaluated expressions");
15189   ExprEvalContexts.back().Context =
15190       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15191   if (isUnevaluatedContext())
15192     return E;
15193   return TransformToPE(*this).TransformExpr(E);
15194 }
15195 
15196 void
15197 Sema::PushExpressionEvaluationContext(
15198     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15199     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15200   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15201                                 LambdaContextDecl, ExprContext);
15202   Cleanup.reset();
15203   if (!MaybeODRUseExprs.empty())
15204     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15205 }
15206 
15207 void
15208 Sema::PushExpressionEvaluationContext(
15209     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15210     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15211   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15212   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15213 }
15214 
15215 namespace {
15216 
15217 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15218   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15219   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15220     if (E->getOpcode() == UO_Deref)
15221       return CheckPossibleDeref(S, E->getSubExpr());
15222   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15223     return CheckPossibleDeref(S, E->getBase());
15224   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15225     return CheckPossibleDeref(S, E->getBase());
15226   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15227     QualType Inner;
15228     QualType Ty = E->getType();
15229     if (const auto *Ptr = Ty->getAs<PointerType>())
15230       Inner = Ptr->getPointeeType();
15231     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15232       Inner = Arr->getElementType();
15233     else
15234       return nullptr;
15235 
15236     if (Inner->hasAttr(attr::NoDeref))
15237       return E;
15238   }
15239   return nullptr;
15240 }
15241 
15242 } // namespace
15243 
15244 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15245   for (const Expr *E : Rec.PossibleDerefs) {
15246     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15247     if (DeclRef) {
15248       const ValueDecl *Decl = DeclRef->getDecl();
15249       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15250           << Decl->getName() << E->getSourceRange();
15251       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15252     } else {
15253       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15254           << E->getSourceRange();
15255     }
15256   }
15257   Rec.PossibleDerefs.clear();
15258 }
15259 
15260 /// Check whether E, which is either a discarded-value expression or an
15261 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15262 /// and if so, remove it from the list of volatile-qualified assignments that
15263 /// we are going to warn are deprecated.
15264 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15265   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15266     return;
15267 
15268   // Note: ignoring parens here is not justified by the standard rules, but
15269   // ignoring parentheses seems like a more reasonable approach, and this only
15270   // drives a deprecation warning so doesn't affect conformance.
15271   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15272     if (BO->getOpcode() == BO_Assign) {
15273       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15274       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15275                  LHSs.end());
15276     }
15277   }
15278 }
15279 
15280 void Sema::PopExpressionEvaluationContext() {
15281   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15282   unsigned NumTypos = Rec.NumTypos;
15283 
15284   if (!Rec.Lambdas.empty()) {
15285     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15286     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15287         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15288       unsigned D;
15289       if (Rec.isUnevaluated()) {
15290         // C++11 [expr.prim.lambda]p2:
15291         //   A lambda-expression shall not appear in an unevaluated operand
15292         //   (Clause 5).
15293         D = diag::err_lambda_unevaluated_operand;
15294       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15295         // C++1y [expr.const]p2:
15296         //   A conditional-expression e is a core constant expression unless the
15297         //   evaluation of e, following the rules of the abstract machine, would
15298         //   evaluate [...] a lambda-expression.
15299         D = diag::err_lambda_in_constant_expression;
15300       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15301         // C++17 [expr.prim.lamda]p2:
15302         // A lambda-expression shall not appear [...] in a template-argument.
15303         D = diag::err_lambda_in_invalid_context;
15304       } else
15305         llvm_unreachable("Couldn't infer lambda error message.");
15306 
15307       for (const auto *L : Rec.Lambdas)
15308         Diag(L->getBeginLoc(), D);
15309     }
15310   }
15311 
15312   WarnOnPendingNoDerefs(Rec);
15313 
15314   // Warn on any volatile-qualified simple-assignments that are not discarded-
15315   // value expressions nor unevaluated operands (those cases get removed from
15316   // this list by CheckUnusedVolatileAssignment).
15317   for (auto *BO : Rec.VolatileAssignmentLHSs)
15318     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15319         << BO->getType();
15320 
15321   // When are coming out of an unevaluated context, clear out any
15322   // temporaries that we may have created as part of the evaluation of
15323   // the expression in that context: they aren't relevant because they
15324   // will never be constructed.
15325   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15326     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15327                              ExprCleanupObjects.end());
15328     Cleanup = Rec.ParentCleanup;
15329     CleanupVarDeclMarking();
15330     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15331   // Otherwise, merge the contexts together.
15332   } else {
15333     Cleanup.mergeFrom(Rec.ParentCleanup);
15334     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15335                             Rec.SavedMaybeODRUseExprs.end());
15336   }
15337 
15338   // Pop the current expression evaluation context off the stack.
15339   ExprEvalContexts.pop_back();
15340 
15341   // The global expression evaluation context record is never popped.
15342   ExprEvalContexts.back().NumTypos += NumTypos;
15343 }
15344 
15345 void Sema::DiscardCleanupsInEvaluationContext() {
15346   ExprCleanupObjects.erase(
15347          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15348          ExprCleanupObjects.end());
15349   Cleanup.reset();
15350   MaybeODRUseExprs.clear();
15351 }
15352 
15353 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15354   ExprResult Result = CheckPlaceholderExpr(E);
15355   if (Result.isInvalid())
15356     return ExprError();
15357   E = Result.get();
15358   if (!E->getType()->isVariablyModifiedType())
15359     return E;
15360   return TransformToPotentiallyEvaluated(E);
15361 }
15362 
15363 /// Are we in a context that is potentially constant evaluated per C++20
15364 /// [expr.const]p12?
15365 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15366   /// C++2a [expr.const]p12:
15367   //   An expression or conversion is potentially constant evaluated if it is
15368   switch (SemaRef.ExprEvalContexts.back().Context) {
15369     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15370       // -- a manifestly constant-evaluated expression,
15371     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15372     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15373     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15374       // -- a potentially-evaluated expression,
15375     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15376       // -- an immediate subexpression of a braced-init-list,
15377 
15378       // -- [FIXME] an expression of the form & cast-expression that occurs
15379       //    within a templated entity
15380       // -- a subexpression of one of the above that is not a subexpression of
15381       // a nested unevaluated operand.
15382       return true;
15383 
15384     case Sema::ExpressionEvaluationContext::Unevaluated:
15385     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15386       // Expressions in this context are never evaluated.
15387       return false;
15388   }
15389   llvm_unreachable("Invalid context");
15390 }
15391 
15392 /// Return true if this function has a calling convention that requires mangling
15393 /// in the size of the parameter pack.
15394 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15395   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15396   // we don't need parameter type sizes.
15397   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15398   if (!TT.isOSWindows() || !TT.isX86())
15399     return false;
15400 
15401   // If this is C++ and this isn't an extern "C" function, parameters do not
15402   // need to be complete. In this case, C++ mangling will apply, which doesn't
15403   // use the size of the parameters.
15404   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15405     return false;
15406 
15407   // Stdcall, fastcall, and vectorcall need this special treatment.
15408   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15409   switch (CC) {
15410   case CC_X86StdCall:
15411   case CC_X86FastCall:
15412   case CC_X86VectorCall:
15413     return true;
15414   default:
15415     break;
15416   }
15417   return false;
15418 }
15419 
15420 /// Require that all of the parameter types of function be complete. Normally,
15421 /// parameter types are only required to be complete when a function is called
15422 /// or defined, but to mangle functions with certain calling conventions, the
15423 /// mangler needs to know the size of the parameter list. In this situation,
15424 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15425 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15426 /// result in a linker error. Clang doesn't implement this behavior, and instead
15427 /// attempts to error at compile time.
15428 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15429                                                   SourceLocation Loc) {
15430   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15431     FunctionDecl *FD;
15432     ParmVarDecl *Param;
15433 
15434   public:
15435     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15436         : FD(FD), Param(Param) {}
15437 
15438     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15439       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15440       StringRef CCName;
15441       switch (CC) {
15442       case CC_X86StdCall:
15443         CCName = "stdcall";
15444         break;
15445       case CC_X86FastCall:
15446         CCName = "fastcall";
15447         break;
15448       case CC_X86VectorCall:
15449         CCName = "vectorcall";
15450         break;
15451       default:
15452         llvm_unreachable("CC does not need mangling");
15453       }
15454 
15455       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15456           << Param->getDeclName() << FD->getDeclName() << CCName;
15457     }
15458   };
15459 
15460   for (ParmVarDecl *Param : FD->parameters()) {
15461     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15462     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15463   }
15464 }
15465 
15466 namespace {
15467 enum class OdrUseContext {
15468   /// Declarations in this context are not odr-used.
15469   None,
15470   /// Declarations in this context are formally odr-used, but this is a
15471   /// dependent context.
15472   Dependent,
15473   /// Declarations in this context are odr-used but not actually used (yet).
15474   FormallyOdrUsed,
15475   /// Declarations in this context are used.
15476   Used
15477 };
15478 }
15479 
15480 /// Are we within a context in which references to resolved functions or to
15481 /// variables result in odr-use?
15482 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15483   OdrUseContext Result;
15484 
15485   switch (SemaRef.ExprEvalContexts.back().Context) {
15486     case Sema::ExpressionEvaluationContext::Unevaluated:
15487     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15488     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15489       return OdrUseContext::None;
15490 
15491     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15492     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15493       Result = OdrUseContext::Used;
15494       break;
15495 
15496     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15497       Result = OdrUseContext::FormallyOdrUsed;
15498       break;
15499 
15500     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15501       // A default argument formally results in odr-use, but doesn't actually
15502       // result in a use in any real sense until it itself is used.
15503       Result = OdrUseContext::FormallyOdrUsed;
15504       break;
15505   }
15506 
15507   if (SemaRef.CurContext->isDependentContext())
15508     return OdrUseContext::Dependent;
15509 
15510   return Result;
15511 }
15512 
15513 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15514   return Func->isConstexpr() &&
15515          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
15516 }
15517 
15518 /// Mark a function referenced, and check whether it is odr-used
15519 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15520 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15521                                   bool MightBeOdrUse) {
15522   assert(Func && "No function?");
15523 
15524   Func->setReferenced();
15525 
15526   // Recursive functions aren't really used until they're used from some other
15527   // context.
15528   bool IsRecursiveCall = CurContext == Func;
15529 
15530   // C++11 [basic.def.odr]p3:
15531   //   A function whose name appears as a potentially-evaluated expression is
15532   //   odr-used if it is the unique lookup result or the selected member of a
15533   //   set of overloaded functions [...].
15534   //
15535   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15536   // can just check that here.
15537   OdrUseContext OdrUse =
15538       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15539   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15540     OdrUse = OdrUseContext::FormallyOdrUsed;
15541 
15542   // Trivial default constructors and destructors are never actually used.
15543   // FIXME: What about other special members?
15544   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15545       OdrUse == OdrUseContext::Used) {
15546     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15547       if (Constructor->isDefaultConstructor())
15548         OdrUse = OdrUseContext::FormallyOdrUsed;
15549     if (isa<CXXDestructorDecl>(Func))
15550       OdrUse = OdrUseContext::FormallyOdrUsed;
15551   }
15552 
15553   // C++20 [expr.const]p12:
15554   //   A function [...] is needed for constant evaluation if it is [...] a
15555   //   constexpr function that is named by an expression that is potentially
15556   //   constant evaluated
15557   bool NeededForConstantEvaluation =
15558       isPotentiallyConstantEvaluatedContext(*this) &&
15559       isImplicitlyDefinableConstexprFunction(Func);
15560 
15561   // Determine whether we require a function definition to exist, per
15562   // C++11 [temp.inst]p3:
15563   //   Unless a function template specialization has been explicitly
15564   //   instantiated or explicitly specialized, the function template
15565   //   specialization is implicitly instantiated when the specialization is
15566   //   referenced in a context that requires a function definition to exist.
15567   // C++20 [temp.inst]p7:
15568   //   The existence of a definition of a [...] function is considered to
15569   //   affect the semantics of the program if the [...] function is needed for
15570   //   constant evaluation by an expression
15571   // C++20 [basic.def.odr]p10:
15572   //   Every program shall contain exactly one definition of every non-inline
15573   //   function or variable that is odr-used in that program outside of a
15574   //   discarded statement
15575   // C++20 [special]p1:
15576   //   The implementation will implicitly define [defaulted special members]
15577   //   if they are odr-used or needed for constant evaluation.
15578   //
15579   // Note that we skip the implicit instantiation of templates that are only
15580   // used in unused default arguments or by recursive calls to themselves.
15581   // This is formally non-conforming, but seems reasonable in practice.
15582   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15583                                              NeededForConstantEvaluation);
15584 
15585   // C++14 [temp.expl.spec]p6:
15586   //   If a template [...] is explicitly specialized then that specialization
15587   //   shall be declared before the first use of that specialization that would
15588   //   cause an implicit instantiation to take place, in every translation unit
15589   //   in which such a use occurs
15590   if (NeedDefinition &&
15591       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15592        Func->getMemberSpecializationInfo()))
15593     checkSpecializationVisibility(Loc, Func);
15594 
15595   if (getLangOpts().CUDA)
15596     CheckCUDACall(Loc, Func);
15597 
15598   // If we need a definition, try to create one.
15599   if (NeedDefinition && !Func->getBody()) {
15600     runWithSufficientStackSpace(Loc, [&] {
15601       if (CXXConstructorDecl *Constructor =
15602               dyn_cast<CXXConstructorDecl>(Func)) {
15603         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15604         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15605           if (Constructor->isDefaultConstructor()) {
15606             if (Constructor->isTrivial() &&
15607                 !Constructor->hasAttr<DLLExportAttr>())
15608               return;
15609             DefineImplicitDefaultConstructor(Loc, Constructor);
15610           } else if (Constructor->isCopyConstructor()) {
15611             DefineImplicitCopyConstructor(Loc, Constructor);
15612           } else if (Constructor->isMoveConstructor()) {
15613             DefineImplicitMoveConstructor(Loc, Constructor);
15614           }
15615         } else if (Constructor->getInheritedConstructor()) {
15616           DefineInheritingConstructor(Loc, Constructor);
15617         }
15618       } else if (CXXDestructorDecl *Destructor =
15619                      dyn_cast<CXXDestructorDecl>(Func)) {
15620         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15621         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15622           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15623             return;
15624           DefineImplicitDestructor(Loc, Destructor);
15625         }
15626         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15627           MarkVTableUsed(Loc, Destructor->getParent());
15628       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15629         if (MethodDecl->isOverloadedOperator() &&
15630             MethodDecl->getOverloadedOperator() == OO_Equal) {
15631           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15632           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15633             if (MethodDecl->isCopyAssignmentOperator())
15634               DefineImplicitCopyAssignment(Loc, MethodDecl);
15635             else if (MethodDecl->isMoveAssignmentOperator())
15636               DefineImplicitMoveAssignment(Loc, MethodDecl);
15637           }
15638         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15639                    MethodDecl->getParent()->isLambda()) {
15640           CXXConversionDecl *Conversion =
15641               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15642           if (Conversion->isLambdaToBlockPointerConversion())
15643             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15644           else
15645             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15646         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15647           MarkVTableUsed(Loc, MethodDecl->getParent());
15648       }
15649 
15650       if (Func->isDefaulted() && !Func->isDeleted()) {
15651         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
15652         if (DCK != DefaultedComparisonKind::None)
15653           DefineDefaultedComparison(Loc, Func, DCK);
15654       }
15655 
15656       // Implicit instantiation of function templates and member functions of
15657       // class templates.
15658       if (Func->isImplicitlyInstantiable()) {
15659         TemplateSpecializationKind TSK =
15660             Func->getTemplateSpecializationKindForInstantiation();
15661         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15662         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15663         if (FirstInstantiation) {
15664           PointOfInstantiation = Loc;
15665           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15666         } else if (TSK != TSK_ImplicitInstantiation) {
15667           // Use the point of use as the point of instantiation, instead of the
15668           // point of explicit instantiation (which we track as the actual point
15669           // of instantiation). This gives better backtraces in diagnostics.
15670           PointOfInstantiation = Loc;
15671         }
15672 
15673         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15674             Func->isConstexpr()) {
15675           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15676               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15677               CodeSynthesisContexts.size())
15678             PendingLocalImplicitInstantiations.push_back(
15679                 std::make_pair(Func, PointOfInstantiation));
15680           else if (Func->isConstexpr())
15681             // Do not defer instantiations of constexpr functions, to avoid the
15682             // expression evaluator needing to call back into Sema if it sees a
15683             // call to such a function.
15684             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15685           else {
15686             Func->setInstantiationIsPending(true);
15687             PendingInstantiations.push_back(
15688                 std::make_pair(Func, PointOfInstantiation));
15689             // Notify the consumer that a function was implicitly instantiated.
15690             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15691           }
15692         }
15693       } else {
15694         // Walk redefinitions, as some of them may be instantiable.
15695         for (auto i : Func->redecls()) {
15696           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15697             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15698         }
15699       }
15700     });
15701   }
15702 
15703   // C++14 [except.spec]p17:
15704   //   An exception-specification is considered to be needed when:
15705   //   - the function is odr-used or, if it appears in an unevaluated operand,
15706   //     would be odr-used if the expression were potentially-evaluated;
15707   //
15708   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15709   // function is a pure virtual function we're calling, and in that case the
15710   // function was selected by overload resolution and we need to resolve its
15711   // exception specification for a different reason.
15712   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15713   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15714     ResolveExceptionSpec(Loc, FPT);
15715 
15716   // If this is the first "real" use, act on that.
15717   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15718     // Keep track of used but undefined functions.
15719     if (!Func->isDefined()) {
15720       if (mightHaveNonExternalLinkage(Func))
15721         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15722       else if (Func->getMostRecentDecl()->isInlined() &&
15723                !LangOpts.GNUInline &&
15724                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15725         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15726       else if (isExternalWithNoLinkageType(Func))
15727         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15728     }
15729 
15730     // Some x86 Windows calling conventions mangle the size of the parameter
15731     // pack into the name. Computing the size of the parameters requires the
15732     // parameter types to be complete. Check that now.
15733     if (funcHasParameterSizeMangling(*this, Func))
15734       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15735 
15736     Func->markUsed(Context);
15737   }
15738 
15739   if (LangOpts.OpenMP) {
15740     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15741     if (LangOpts.OpenMPIsDevice)
15742       checkOpenMPDeviceFunction(Loc, Func);
15743     else
15744       checkOpenMPHostFunction(Loc, Func);
15745   }
15746 }
15747 
15748 /// Directly mark a variable odr-used. Given a choice, prefer to use
15749 /// MarkVariableReferenced since it does additional checks and then
15750 /// calls MarkVarDeclODRUsed.
15751 /// If the variable must be captured:
15752 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15753 ///  - else capture it in the DeclContext that maps to the
15754 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15755 static void
15756 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15757                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15758   // Keep track of used but undefined variables.
15759   // FIXME: We shouldn't suppress this warning for static data members.
15760   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15761       (!Var->isExternallyVisible() || Var->isInline() ||
15762        SemaRef.isExternalWithNoLinkageType(Var)) &&
15763       !(Var->isStaticDataMember() && Var->hasInit())) {
15764     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15765     if (old.isInvalid())
15766       old = Loc;
15767   }
15768   QualType CaptureType, DeclRefType;
15769   if (SemaRef.LangOpts.OpenMP)
15770     SemaRef.tryCaptureOpenMPLambdas(Var);
15771   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15772     /*EllipsisLoc*/ SourceLocation(),
15773     /*BuildAndDiagnose*/ true,
15774     CaptureType, DeclRefType,
15775     FunctionScopeIndexToStopAt);
15776 
15777   Var->markUsed(SemaRef.Context);
15778 }
15779 
15780 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15781                                              SourceLocation Loc,
15782                                              unsigned CapturingScopeIndex) {
15783   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15784 }
15785 
15786 static void
15787 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15788                                    ValueDecl *var, DeclContext *DC) {
15789   DeclContext *VarDC = var->getDeclContext();
15790 
15791   //  If the parameter still belongs to the translation unit, then
15792   //  we're actually just using one parameter in the declaration of
15793   //  the next.
15794   if (isa<ParmVarDecl>(var) &&
15795       isa<TranslationUnitDecl>(VarDC))
15796     return;
15797 
15798   // For C code, don't diagnose about capture if we're not actually in code
15799   // right now; it's impossible to write a non-constant expression outside of
15800   // function context, so we'll get other (more useful) diagnostics later.
15801   //
15802   // For C++, things get a bit more nasty... it would be nice to suppress this
15803   // diagnostic for certain cases like using a local variable in an array bound
15804   // for a member of a local class, but the correct predicate is not obvious.
15805   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15806     return;
15807 
15808   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15809   unsigned ContextKind = 3; // unknown
15810   if (isa<CXXMethodDecl>(VarDC) &&
15811       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15812     ContextKind = 2;
15813   } else if (isa<FunctionDecl>(VarDC)) {
15814     ContextKind = 0;
15815   } else if (isa<BlockDecl>(VarDC)) {
15816     ContextKind = 1;
15817   }
15818 
15819   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15820     << var << ValueKind << ContextKind << VarDC;
15821   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15822       << var;
15823 
15824   // FIXME: Add additional diagnostic info about class etc. which prevents
15825   // capture.
15826 }
15827 
15828 
15829 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15830                                       bool &SubCapturesAreNested,
15831                                       QualType &CaptureType,
15832                                       QualType &DeclRefType) {
15833    // Check whether we've already captured it.
15834   if (CSI->CaptureMap.count(Var)) {
15835     // If we found a capture, any subcaptures are nested.
15836     SubCapturesAreNested = true;
15837 
15838     // Retrieve the capture type for this variable.
15839     CaptureType = CSI->getCapture(Var).getCaptureType();
15840 
15841     // Compute the type of an expression that refers to this variable.
15842     DeclRefType = CaptureType.getNonReferenceType();
15843 
15844     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15845     // are mutable in the sense that user can change their value - they are
15846     // private instances of the captured declarations.
15847     const Capture &Cap = CSI->getCapture(Var);
15848     if (Cap.isCopyCapture() &&
15849         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15850         !(isa<CapturedRegionScopeInfo>(CSI) &&
15851           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15852       DeclRefType.addConst();
15853     return true;
15854   }
15855   return false;
15856 }
15857 
15858 // Only block literals, captured statements, and lambda expressions can
15859 // capture; other scopes don't work.
15860 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15861                                  SourceLocation Loc,
15862                                  const bool Diagnose, Sema &S) {
15863   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15864     return getLambdaAwareParentOfDeclContext(DC);
15865   else if (Var->hasLocalStorage()) {
15866     if (Diagnose)
15867        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15868   }
15869   return nullptr;
15870 }
15871 
15872 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15873 // certain types of variables (unnamed, variably modified types etc.)
15874 // so check for eligibility.
15875 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15876                                  SourceLocation Loc,
15877                                  const bool Diagnose, Sema &S) {
15878 
15879   bool IsBlock = isa<BlockScopeInfo>(CSI);
15880   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15881 
15882   // Lambdas are not allowed to capture unnamed variables
15883   // (e.g. anonymous unions).
15884   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15885   // assuming that's the intent.
15886   if (IsLambda && !Var->getDeclName()) {
15887     if (Diagnose) {
15888       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15889       S.Diag(Var->getLocation(), diag::note_declared_at);
15890     }
15891     return false;
15892   }
15893 
15894   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15895   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15896     if (Diagnose) {
15897       S.Diag(Loc, diag::err_ref_vm_type);
15898       S.Diag(Var->getLocation(), diag::note_previous_decl)
15899         << Var->getDeclName();
15900     }
15901     return false;
15902   }
15903   // Prohibit structs with flexible array members too.
15904   // We cannot capture what is in the tail end of the struct.
15905   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15906     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15907       if (Diagnose) {
15908         if (IsBlock)
15909           S.Diag(Loc, diag::err_ref_flexarray_type);
15910         else
15911           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15912             << Var->getDeclName();
15913         S.Diag(Var->getLocation(), diag::note_previous_decl)
15914           << Var->getDeclName();
15915       }
15916       return false;
15917     }
15918   }
15919   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15920   // Lambdas and captured statements are not allowed to capture __block
15921   // variables; they don't support the expected semantics.
15922   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15923     if (Diagnose) {
15924       S.Diag(Loc, diag::err_capture_block_variable)
15925         << Var->getDeclName() << !IsLambda;
15926       S.Diag(Var->getLocation(), diag::note_previous_decl)
15927         << Var->getDeclName();
15928     }
15929     return false;
15930   }
15931   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15932   if (S.getLangOpts().OpenCL && IsBlock &&
15933       Var->getType()->isBlockPointerType()) {
15934     if (Diagnose)
15935       S.Diag(Loc, diag::err_opencl_block_ref_block);
15936     return false;
15937   }
15938 
15939   return true;
15940 }
15941 
15942 // Returns true if the capture by block was successful.
15943 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15944                                  SourceLocation Loc,
15945                                  const bool BuildAndDiagnose,
15946                                  QualType &CaptureType,
15947                                  QualType &DeclRefType,
15948                                  const bool Nested,
15949                                  Sema &S, bool Invalid) {
15950   bool ByRef = false;
15951 
15952   // Blocks are not allowed to capture arrays, excepting OpenCL.
15953   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15954   // (decayed to pointers).
15955   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15956     if (BuildAndDiagnose) {
15957       S.Diag(Loc, diag::err_ref_array_type);
15958       S.Diag(Var->getLocation(), diag::note_previous_decl)
15959       << Var->getDeclName();
15960       Invalid = true;
15961     } else {
15962       return false;
15963     }
15964   }
15965 
15966   // Forbid the block-capture of autoreleasing variables.
15967   if (!Invalid &&
15968       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15969     if (BuildAndDiagnose) {
15970       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15971         << /*block*/ 0;
15972       S.Diag(Var->getLocation(), diag::note_previous_decl)
15973         << Var->getDeclName();
15974       Invalid = true;
15975     } else {
15976       return false;
15977     }
15978   }
15979 
15980   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15981   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15982     QualType PointeeTy = PT->getPointeeType();
15983 
15984     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15985         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15986         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15987       if (BuildAndDiagnose) {
15988         SourceLocation VarLoc = Var->getLocation();
15989         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15990         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15991       }
15992     }
15993   }
15994 
15995   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15996   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15997       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15998     // Block capture by reference does not change the capture or
15999     // declaration reference types.
16000     ByRef = true;
16001   } else {
16002     // Block capture by copy introduces 'const'.
16003     CaptureType = CaptureType.getNonReferenceType().withConst();
16004     DeclRefType = CaptureType;
16005   }
16006 
16007   // Actually capture the variable.
16008   if (BuildAndDiagnose)
16009     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16010                     CaptureType, Invalid);
16011 
16012   return !Invalid;
16013 }
16014 
16015 
16016 /// Capture the given variable in the captured region.
16017 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16018                                     VarDecl *Var,
16019                                     SourceLocation Loc,
16020                                     const bool BuildAndDiagnose,
16021                                     QualType &CaptureType,
16022                                     QualType &DeclRefType,
16023                                     const bool RefersToCapturedVariable,
16024                                     Sema &S, bool Invalid) {
16025   // By default, capture variables by reference.
16026   bool ByRef = true;
16027   // Using an LValue reference type is consistent with Lambdas (see below).
16028   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16029     if (S.isOpenMPCapturedDecl(Var)) {
16030       bool HasConst = DeclRefType.isConstQualified();
16031       DeclRefType = DeclRefType.getUnqualifiedType();
16032       // Don't lose diagnostics about assignments to const.
16033       if (HasConst)
16034         DeclRefType.addConst();
16035     }
16036     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16037                                     RSI->OpenMPCaptureLevel);
16038   }
16039 
16040   if (ByRef)
16041     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16042   else
16043     CaptureType = DeclRefType;
16044 
16045   // Actually capture the variable.
16046   if (BuildAndDiagnose)
16047     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16048                     Loc, SourceLocation(), CaptureType, Invalid);
16049 
16050   return !Invalid;
16051 }
16052 
16053 /// Capture the given variable in the lambda.
16054 static bool captureInLambda(LambdaScopeInfo *LSI,
16055                             VarDecl *Var,
16056                             SourceLocation Loc,
16057                             const bool BuildAndDiagnose,
16058                             QualType &CaptureType,
16059                             QualType &DeclRefType,
16060                             const bool RefersToCapturedVariable,
16061                             const Sema::TryCaptureKind Kind,
16062                             SourceLocation EllipsisLoc,
16063                             const bool IsTopScope,
16064                             Sema &S, bool Invalid) {
16065   // Determine whether we are capturing by reference or by value.
16066   bool ByRef = false;
16067   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16068     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16069   } else {
16070     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16071   }
16072 
16073   // Compute the type of the field that will capture this variable.
16074   if (ByRef) {
16075     // C++11 [expr.prim.lambda]p15:
16076     //   An entity is captured by reference if it is implicitly or
16077     //   explicitly captured but not captured by copy. It is
16078     //   unspecified whether additional unnamed non-static data
16079     //   members are declared in the closure type for entities
16080     //   captured by reference.
16081     //
16082     // FIXME: It is not clear whether we want to build an lvalue reference
16083     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16084     // to do the former, while EDG does the latter. Core issue 1249 will
16085     // clarify, but for now we follow GCC because it's a more permissive and
16086     // easily defensible position.
16087     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16088   } else {
16089     // C++11 [expr.prim.lambda]p14:
16090     //   For each entity captured by copy, an unnamed non-static
16091     //   data member is declared in the closure type. The
16092     //   declaration order of these members is unspecified. The type
16093     //   of such a data member is the type of the corresponding
16094     //   captured entity if the entity is not a reference to an
16095     //   object, or the referenced type otherwise. [Note: If the
16096     //   captured entity is a reference to a function, the
16097     //   corresponding data member is also a reference to a
16098     //   function. - end note ]
16099     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16100       if (!RefType->getPointeeType()->isFunctionType())
16101         CaptureType = RefType->getPointeeType();
16102     }
16103 
16104     // Forbid the lambda copy-capture of autoreleasing variables.
16105     if (!Invalid &&
16106         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16107       if (BuildAndDiagnose) {
16108         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16109         S.Diag(Var->getLocation(), diag::note_previous_decl)
16110           << Var->getDeclName();
16111         Invalid = true;
16112       } else {
16113         return false;
16114       }
16115     }
16116 
16117     // Make sure that by-copy captures are of a complete and non-abstract type.
16118     if (!Invalid && BuildAndDiagnose) {
16119       if (!CaptureType->isDependentType() &&
16120           S.RequireCompleteType(Loc, CaptureType,
16121                                 diag::err_capture_of_incomplete_type,
16122                                 Var->getDeclName()))
16123         Invalid = true;
16124       else if (S.RequireNonAbstractType(Loc, CaptureType,
16125                                         diag::err_capture_of_abstract_type))
16126         Invalid = true;
16127     }
16128   }
16129 
16130   // Compute the type of a reference to this captured variable.
16131   if (ByRef)
16132     DeclRefType = CaptureType.getNonReferenceType();
16133   else {
16134     // C++ [expr.prim.lambda]p5:
16135     //   The closure type for a lambda-expression has a public inline
16136     //   function call operator [...]. This function call operator is
16137     //   declared const (9.3.1) if and only if the lambda-expression's
16138     //   parameter-declaration-clause is not followed by mutable.
16139     DeclRefType = CaptureType.getNonReferenceType();
16140     if (!LSI->Mutable && !CaptureType->isReferenceType())
16141       DeclRefType.addConst();
16142   }
16143 
16144   // Add the capture.
16145   if (BuildAndDiagnose)
16146     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16147                     Loc, EllipsisLoc, CaptureType, Invalid);
16148 
16149   return !Invalid;
16150 }
16151 
16152 bool Sema::tryCaptureVariable(
16153     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16154     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16155     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16156   // An init-capture is notionally from the context surrounding its
16157   // declaration, but its parent DC is the lambda class.
16158   DeclContext *VarDC = Var->getDeclContext();
16159   if (Var->isInitCapture())
16160     VarDC = VarDC->getParent();
16161 
16162   DeclContext *DC = CurContext;
16163   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16164       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16165   // We need to sync up the Declaration Context with the
16166   // FunctionScopeIndexToStopAt
16167   if (FunctionScopeIndexToStopAt) {
16168     unsigned FSIndex = FunctionScopes.size() - 1;
16169     while (FSIndex != MaxFunctionScopesIndex) {
16170       DC = getLambdaAwareParentOfDeclContext(DC);
16171       --FSIndex;
16172     }
16173   }
16174 
16175 
16176   // If the variable is declared in the current context, there is no need to
16177   // capture it.
16178   if (VarDC == DC) return true;
16179 
16180   // Capture global variables if it is required to use private copy of this
16181   // variable.
16182   bool IsGlobal = !Var->hasLocalStorage();
16183   if (IsGlobal &&
16184       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16185                                                 MaxFunctionScopesIndex)))
16186     return true;
16187   Var = Var->getCanonicalDecl();
16188 
16189   // Walk up the stack to determine whether we can capture the variable,
16190   // performing the "simple" checks that don't depend on type. We stop when
16191   // we've either hit the declared scope of the variable or find an existing
16192   // capture of that variable.  We start from the innermost capturing-entity
16193   // (the DC) and ensure that all intervening capturing-entities
16194   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16195   // declcontext can either capture the variable or have already captured
16196   // the variable.
16197   CaptureType = Var->getType();
16198   DeclRefType = CaptureType.getNonReferenceType();
16199   bool Nested = false;
16200   bool Explicit = (Kind != TryCapture_Implicit);
16201   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16202   do {
16203     // Only block literals, captured statements, and lambda expressions can
16204     // capture; other scopes don't work.
16205     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16206                                                               ExprLoc,
16207                                                               BuildAndDiagnose,
16208                                                               *this);
16209     // We need to check for the parent *first* because, if we *have*
16210     // private-captured a global variable, we need to recursively capture it in
16211     // intermediate blocks, lambdas, etc.
16212     if (!ParentDC) {
16213       if (IsGlobal) {
16214         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16215         break;
16216       }
16217       return true;
16218     }
16219 
16220     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16221     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16222 
16223 
16224     // Check whether we've already captured it.
16225     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16226                                              DeclRefType)) {
16227       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16228       break;
16229     }
16230     // If we are instantiating a generic lambda call operator body,
16231     // we do not want to capture new variables.  What was captured
16232     // during either a lambdas transformation or initial parsing
16233     // should be used.
16234     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16235       if (BuildAndDiagnose) {
16236         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16237         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16238           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16239           Diag(Var->getLocation(), diag::note_previous_decl)
16240              << Var->getDeclName();
16241           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16242         } else
16243           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16244       }
16245       return true;
16246     }
16247 
16248     // Try to capture variable-length arrays types.
16249     if (Var->getType()->isVariablyModifiedType()) {
16250       // We're going to walk down into the type and look for VLA
16251       // expressions.
16252       QualType QTy = Var->getType();
16253       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16254         QTy = PVD->getOriginalType();
16255       captureVariablyModifiedType(Context, QTy, CSI);
16256     }
16257 
16258     if (getLangOpts().OpenMP) {
16259       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16260         // OpenMP private variables should not be captured in outer scope, so
16261         // just break here. Similarly, global variables that are captured in a
16262         // target region should not be captured outside the scope of the region.
16263         if (RSI->CapRegionKind == CR_OpenMP) {
16264           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16265           // If the variable is private (i.e. not captured) and has variably
16266           // modified type, we still need to capture the type for correct
16267           // codegen in all regions, associated with the construct. Currently,
16268           // it is captured in the innermost captured region only.
16269           if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16270             QualType QTy = Var->getType();
16271             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16272               QTy = PVD->getOriginalType();
16273             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16274                  I < E; ++I) {
16275               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16276                   FunctionScopes[FunctionScopesIndex - I]);
16277               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16278                      "Wrong number of captured regions associated with the "
16279                      "OpenMP construct.");
16280               captureVariablyModifiedType(Context, QTy, OuterRSI);
16281             }
16282           }
16283           bool IsTargetCap = !IsOpenMPPrivateDecl &&
16284                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16285           // When we detect target captures we are looking from inside the
16286           // target region, therefore we need to propagate the capture from the
16287           // enclosing region. Therefore, the capture is not initially nested.
16288           if (IsTargetCap)
16289             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16290 
16291           if (IsTargetCap || IsOpenMPPrivateDecl) {
16292             Nested = !IsTargetCap;
16293             DeclRefType = DeclRefType.getUnqualifiedType();
16294             CaptureType = Context.getLValueReferenceType(DeclRefType);
16295             break;
16296           }
16297         }
16298       }
16299     }
16300     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16301       // No capture-default, and this is not an explicit capture
16302       // so cannot capture this variable.
16303       if (BuildAndDiagnose) {
16304         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16305         Diag(Var->getLocation(), diag::note_previous_decl)
16306           << Var->getDeclName();
16307         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16308           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16309                diag::note_lambda_decl);
16310         // FIXME: If we error out because an outer lambda can not implicitly
16311         // capture a variable that an inner lambda explicitly captures, we
16312         // should have the inner lambda do the explicit capture - because
16313         // it makes for cleaner diagnostics later.  This would purely be done
16314         // so that the diagnostic does not misleadingly claim that a variable
16315         // can not be captured by a lambda implicitly even though it is captured
16316         // explicitly.  Suggestion:
16317         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16318         //    at the function head
16319         //  - cache the StartingDeclContext - this must be a lambda
16320         //  - captureInLambda in the innermost lambda the variable.
16321       }
16322       return true;
16323     }
16324 
16325     FunctionScopesIndex--;
16326     DC = ParentDC;
16327     Explicit = false;
16328   } while (!VarDC->Equals(DC));
16329 
16330   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16331   // computing the type of the capture at each step, checking type-specific
16332   // requirements, and adding captures if requested.
16333   // If the variable had already been captured previously, we start capturing
16334   // at the lambda nested within that one.
16335   bool Invalid = false;
16336   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16337        ++I) {
16338     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16339 
16340     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16341     // certain types of variables (unnamed, variably modified types etc.)
16342     // so check for eligibility.
16343     if (!Invalid)
16344       Invalid =
16345           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16346 
16347     // After encountering an error, if we're actually supposed to capture, keep
16348     // capturing in nested contexts to suppress any follow-on diagnostics.
16349     if (Invalid && !BuildAndDiagnose)
16350       return true;
16351 
16352     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16353       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16354                                DeclRefType, Nested, *this, Invalid);
16355       Nested = true;
16356     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16357       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16358                                          CaptureType, DeclRefType, Nested,
16359                                          *this, Invalid);
16360       Nested = true;
16361     } else {
16362       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16363       Invalid =
16364           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16365                            DeclRefType, Nested, Kind, EllipsisLoc,
16366                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16367       Nested = true;
16368     }
16369 
16370     if (Invalid && !BuildAndDiagnose)
16371       return true;
16372   }
16373   return Invalid;
16374 }
16375 
16376 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16377                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16378   QualType CaptureType;
16379   QualType DeclRefType;
16380   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16381                             /*BuildAndDiagnose=*/true, CaptureType,
16382                             DeclRefType, nullptr);
16383 }
16384 
16385 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16386   QualType CaptureType;
16387   QualType DeclRefType;
16388   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16389                              /*BuildAndDiagnose=*/false, CaptureType,
16390                              DeclRefType, nullptr);
16391 }
16392 
16393 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16394   QualType CaptureType;
16395   QualType DeclRefType;
16396 
16397   // Determine whether we can capture this variable.
16398   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16399                          /*BuildAndDiagnose=*/false, CaptureType,
16400                          DeclRefType, nullptr))
16401     return QualType();
16402 
16403   return DeclRefType;
16404 }
16405 
16406 namespace {
16407 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16408 // The produced TemplateArgumentListInfo* points to data stored within this
16409 // object, so should only be used in contexts where the pointer will not be
16410 // used after the CopiedTemplateArgs object is destroyed.
16411 class CopiedTemplateArgs {
16412   bool HasArgs;
16413   TemplateArgumentListInfo TemplateArgStorage;
16414 public:
16415   template<typename RefExpr>
16416   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16417     if (HasArgs)
16418       E->copyTemplateArgumentsInto(TemplateArgStorage);
16419   }
16420   operator TemplateArgumentListInfo*()
16421 #ifdef __has_cpp_attribute
16422 #if __has_cpp_attribute(clang::lifetimebound)
16423   [[clang::lifetimebound]]
16424 #endif
16425 #endif
16426   {
16427     return HasArgs ? &TemplateArgStorage : nullptr;
16428   }
16429 };
16430 }
16431 
16432 /// Walk the set of potential results of an expression and mark them all as
16433 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16434 ///
16435 /// \return A new expression if we found any potential results, ExprEmpty() if
16436 ///         not, and ExprError() if we diagnosed an error.
16437 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16438                                                       NonOdrUseReason NOUR) {
16439   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16440   // an object that satisfies the requirements for appearing in a
16441   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16442   // is immediately applied."  This function handles the lvalue-to-rvalue
16443   // conversion part.
16444   //
16445   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16446   // transform it into the relevant kind of non-odr-use node and rebuild the
16447   // tree of nodes leading to it.
16448   //
16449   // This is a mini-TreeTransform that only transforms a restricted subset of
16450   // nodes (and only certain operands of them).
16451 
16452   // Rebuild a subexpression.
16453   auto Rebuild = [&](Expr *Sub) {
16454     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16455   };
16456 
16457   // Check whether a potential result satisfies the requirements of NOUR.
16458   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16459     // Any entity other than a VarDecl is always odr-used whenever it's named
16460     // in a potentially-evaluated expression.
16461     auto *VD = dyn_cast<VarDecl>(D);
16462     if (!VD)
16463       return true;
16464 
16465     // C++2a [basic.def.odr]p4:
16466     //   A variable x whose name appears as a potentially-evalauted expression
16467     //   e is odr-used by e unless
16468     //   -- x is a reference that is usable in constant expressions, or
16469     //   -- x is a variable of non-reference type that is usable in constant
16470     //      expressions and has no mutable subobjects, and e is an element of
16471     //      the set of potential results of an expression of
16472     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16473     //      conversion is applied, or
16474     //   -- x is a variable of non-reference type, and e is an element of the
16475     //      set of potential results of a discarded-value expression to which
16476     //      the lvalue-to-rvalue conversion is not applied
16477     //
16478     // We check the first bullet and the "potentially-evaluated" condition in
16479     // BuildDeclRefExpr. We check the type requirements in the second bullet
16480     // in CheckLValueToRValueConversionOperand below.
16481     switch (NOUR) {
16482     case NOUR_None:
16483     case NOUR_Unevaluated:
16484       llvm_unreachable("unexpected non-odr-use-reason");
16485 
16486     case NOUR_Constant:
16487       // Constant references were handled when they were built.
16488       if (VD->getType()->isReferenceType())
16489         return true;
16490       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16491         if (RD->hasMutableFields())
16492           return true;
16493       if (!VD->isUsableInConstantExpressions(S.Context))
16494         return true;
16495       break;
16496 
16497     case NOUR_Discarded:
16498       if (VD->getType()->isReferenceType())
16499         return true;
16500       break;
16501     }
16502     return false;
16503   };
16504 
16505   // Mark that this expression does not constitute an odr-use.
16506   auto MarkNotOdrUsed = [&] {
16507     S.MaybeODRUseExprs.erase(E);
16508     if (LambdaScopeInfo *LSI = S.getCurLambda())
16509       LSI->markVariableExprAsNonODRUsed(E);
16510   };
16511 
16512   // C++2a [basic.def.odr]p2:
16513   //   The set of potential results of an expression e is defined as follows:
16514   switch (E->getStmtClass()) {
16515   //   -- If e is an id-expression, ...
16516   case Expr::DeclRefExprClass: {
16517     auto *DRE = cast<DeclRefExpr>(E);
16518     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16519       break;
16520 
16521     // Rebuild as a non-odr-use DeclRefExpr.
16522     MarkNotOdrUsed();
16523     return DeclRefExpr::Create(
16524         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16525         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16526         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16527         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16528   }
16529 
16530   case Expr::FunctionParmPackExprClass: {
16531     auto *FPPE = cast<FunctionParmPackExpr>(E);
16532     // If any of the declarations in the pack is odr-used, then the expression
16533     // as a whole constitutes an odr-use.
16534     for (VarDecl *D : *FPPE)
16535       if (IsPotentialResultOdrUsed(D))
16536         return ExprEmpty();
16537 
16538     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16539     // nothing cares about whether we marked this as an odr-use, but it might
16540     // be useful for non-compiler tools.
16541     MarkNotOdrUsed();
16542     break;
16543   }
16544 
16545   //   -- If e is a subscripting operation with an array operand...
16546   case Expr::ArraySubscriptExprClass: {
16547     auto *ASE = cast<ArraySubscriptExpr>(E);
16548     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16549     if (!OldBase->getType()->isArrayType())
16550       break;
16551     ExprResult Base = Rebuild(OldBase);
16552     if (!Base.isUsable())
16553       return Base;
16554     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16555     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16556     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16557     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16558                                      ASE->getRBracketLoc());
16559   }
16560 
16561   case Expr::MemberExprClass: {
16562     auto *ME = cast<MemberExpr>(E);
16563     // -- If e is a class member access expression [...] naming a non-static
16564     //    data member...
16565     if (isa<FieldDecl>(ME->getMemberDecl())) {
16566       ExprResult Base = Rebuild(ME->getBase());
16567       if (!Base.isUsable())
16568         return Base;
16569       return MemberExpr::Create(
16570           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16571           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16572           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16573           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16574           ME->getObjectKind(), ME->isNonOdrUse());
16575     }
16576 
16577     if (ME->getMemberDecl()->isCXXInstanceMember())
16578       break;
16579 
16580     // -- If e is a class member access expression naming a static data member,
16581     //    ...
16582     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16583       break;
16584 
16585     // Rebuild as a non-odr-use MemberExpr.
16586     MarkNotOdrUsed();
16587     return MemberExpr::Create(
16588         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16589         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16590         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16591         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16592     return ExprEmpty();
16593   }
16594 
16595   case Expr::BinaryOperatorClass: {
16596     auto *BO = cast<BinaryOperator>(E);
16597     Expr *LHS = BO->getLHS();
16598     Expr *RHS = BO->getRHS();
16599     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16600     if (BO->getOpcode() == BO_PtrMemD) {
16601       ExprResult Sub = Rebuild(LHS);
16602       if (!Sub.isUsable())
16603         return Sub;
16604       LHS = Sub.get();
16605     //   -- If e is a comma expression, ...
16606     } else if (BO->getOpcode() == BO_Comma) {
16607       ExprResult Sub = Rebuild(RHS);
16608       if (!Sub.isUsable())
16609         return Sub;
16610       RHS = Sub.get();
16611     } else {
16612       break;
16613     }
16614     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16615                         LHS, RHS);
16616   }
16617 
16618   //   -- If e has the form (e1)...
16619   case Expr::ParenExprClass: {
16620     auto *PE = cast<ParenExpr>(E);
16621     ExprResult Sub = Rebuild(PE->getSubExpr());
16622     if (!Sub.isUsable())
16623       return Sub;
16624     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16625   }
16626 
16627   //   -- If e is a glvalue conditional expression, ...
16628   // We don't apply this to a binary conditional operator. FIXME: Should we?
16629   case Expr::ConditionalOperatorClass: {
16630     auto *CO = cast<ConditionalOperator>(E);
16631     ExprResult LHS = Rebuild(CO->getLHS());
16632     if (LHS.isInvalid())
16633       return ExprError();
16634     ExprResult RHS = Rebuild(CO->getRHS());
16635     if (RHS.isInvalid())
16636       return ExprError();
16637     if (!LHS.isUsable() && !RHS.isUsable())
16638       return ExprEmpty();
16639     if (!LHS.isUsable())
16640       LHS = CO->getLHS();
16641     if (!RHS.isUsable())
16642       RHS = CO->getRHS();
16643     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16644                                 CO->getCond(), LHS.get(), RHS.get());
16645   }
16646 
16647   // [Clang extension]
16648   //   -- If e has the form __extension__ e1...
16649   case Expr::UnaryOperatorClass: {
16650     auto *UO = cast<UnaryOperator>(E);
16651     if (UO->getOpcode() != UO_Extension)
16652       break;
16653     ExprResult Sub = Rebuild(UO->getSubExpr());
16654     if (!Sub.isUsable())
16655       return Sub;
16656     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16657                           Sub.get());
16658   }
16659 
16660   // [Clang extension]
16661   //   -- If e has the form _Generic(...), the set of potential results is the
16662   //      union of the sets of potential results of the associated expressions.
16663   case Expr::GenericSelectionExprClass: {
16664     auto *GSE = cast<GenericSelectionExpr>(E);
16665 
16666     SmallVector<Expr *, 4> AssocExprs;
16667     bool AnyChanged = false;
16668     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16669       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16670       if (AssocExpr.isInvalid())
16671         return ExprError();
16672       if (AssocExpr.isUsable()) {
16673         AssocExprs.push_back(AssocExpr.get());
16674         AnyChanged = true;
16675       } else {
16676         AssocExprs.push_back(OrigAssocExpr);
16677       }
16678     }
16679 
16680     return AnyChanged ? S.CreateGenericSelectionExpr(
16681                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16682                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16683                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16684                       : ExprEmpty();
16685   }
16686 
16687   // [Clang extension]
16688   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16689   //      results is the union of the sets of potential results of the
16690   //      second and third subexpressions.
16691   case Expr::ChooseExprClass: {
16692     auto *CE = cast<ChooseExpr>(E);
16693 
16694     ExprResult LHS = Rebuild(CE->getLHS());
16695     if (LHS.isInvalid())
16696       return ExprError();
16697 
16698     ExprResult RHS = Rebuild(CE->getLHS());
16699     if (RHS.isInvalid())
16700       return ExprError();
16701 
16702     if (!LHS.get() && !RHS.get())
16703       return ExprEmpty();
16704     if (!LHS.isUsable())
16705       LHS = CE->getLHS();
16706     if (!RHS.isUsable())
16707       RHS = CE->getRHS();
16708 
16709     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16710                              RHS.get(), CE->getRParenLoc());
16711   }
16712 
16713   // Step through non-syntactic nodes.
16714   case Expr::ConstantExprClass: {
16715     auto *CE = cast<ConstantExpr>(E);
16716     ExprResult Sub = Rebuild(CE->getSubExpr());
16717     if (!Sub.isUsable())
16718       return Sub;
16719     return ConstantExpr::Create(S.Context, Sub.get());
16720   }
16721 
16722   // We could mostly rely on the recursive rebuilding to rebuild implicit
16723   // casts, but not at the top level, so rebuild them here.
16724   case Expr::ImplicitCastExprClass: {
16725     auto *ICE = cast<ImplicitCastExpr>(E);
16726     // Only step through the narrow set of cast kinds we expect to encounter.
16727     // Anything else suggests we've left the region in which potential results
16728     // can be found.
16729     switch (ICE->getCastKind()) {
16730     case CK_NoOp:
16731     case CK_DerivedToBase:
16732     case CK_UncheckedDerivedToBase: {
16733       ExprResult Sub = Rebuild(ICE->getSubExpr());
16734       if (!Sub.isUsable())
16735         return Sub;
16736       CXXCastPath Path(ICE->path());
16737       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16738                                  ICE->getValueKind(), &Path);
16739     }
16740 
16741     default:
16742       break;
16743     }
16744     break;
16745   }
16746 
16747   default:
16748     break;
16749   }
16750 
16751   // Can't traverse through this node. Nothing to do.
16752   return ExprEmpty();
16753 }
16754 
16755 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16756   // Check whether the operand is or contains an object of non-trivial C union
16757   // type.
16758   if (E->getType().isVolatileQualified() &&
16759       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16760        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16761     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16762                           Sema::NTCUC_LValueToRValueVolatile,
16763                           NTCUK_Destruct|NTCUK_Copy);
16764 
16765   // C++2a [basic.def.odr]p4:
16766   //   [...] an expression of non-volatile-qualified non-class type to which
16767   //   the lvalue-to-rvalue conversion is applied [...]
16768   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16769     return E;
16770 
16771   ExprResult Result =
16772       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16773   if (Result.isInvalid())
16774     return ExprError();
16775   return Result.get() ? Result : E;
16776 }
16777 
16778 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16779   Res = CorrectDelayedTyposInExpr(Res);
16780 
16781   if (!Res.isUsable())
16782     return Res;
16783 
16784   // If a constant-expression is a reference to a variable where we delay
16785   // deciding whether it is an odr-use, just assume we will apply the
16786   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16787   // (a non-type template argument), we have special handling anyway.
16788   return CheckLValueToRValueConversionOperand(Res.get());
16789 }
16790 
16791 void Sema::CleanupVarDeclMarking() {
16792   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16793   // call.
16794   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16795   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16796 
16797   for (Expr *E : LocalMaybeODRUseExprs) {
16798     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16799       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16800                          DRE->getLocation(), *this);
16801     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16802       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16803                          *this);
16804     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16805       for (VarDecl *VD : *FP)
16806         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16807     } else {
16808       llvm_unreachable("Unexpected expression");
16809     }
16810   }
16811 
16812   assert(MaybeODRUseExprs.empty() &&
16813          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16814 }
16815 
16816 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16817                                     VarDecl *Var, Expr *E) {
16818   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16819           isa<FunctionParmPackExpr>(E)) &&
16820          "Invalid Expr argument to DoMarkVarDeclReferenced");
16821   Var->setReferenced();
16822 
16823   if (Var->isInvalidDecl())
16824     return;
16825 
16826   auto *MSI = Var->getMemberSpecializationInfo();
16827   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16828                                        : Var->getTemplateSpecializationKind();
16829 
16830   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16831   bool UsableInConstantExpr =
16832       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16833 
16834   // C++20 [expr.const]p12:
16835   //   A variable [...] is needed for constant evaluation if it is [...] a
16836   //   variable whose name appears as a potentially constant evaluated
16837   //   expression that is either a contexpr variable or is of non-volatile
16838   //   const-qualified integral type or of reference type
16839   bool NeededForConstantEvaluation =
16840       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16841 
16842   bool NeedDefinition =
16843       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16844 
16845   VarTemplateSpecializationDecl *VarSpec =
16846       dyn_cast<VarTemplateSpecializationDecl>(Var);
16847   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16848          "Can't instantiate a partial template specialization.");
16849 
16850   // If this might be a member specialization of a static data member, check
16851   // the specialization is visible. We already did the checks for variable
16852   // template specializations when we created them.
16853   if (NeedDefinition && TSK != TSK_Undeclared &&
16854       !isa<VarTemplateSpecializationDecl>(Var))
16855     SemaRef.checkSpecializationVisibility(Loc, Var);
16856 
16857   // Perform implicit instantiation of static data members, static data member
16858   // templates of class templates, and variable template specializations. Delay
16859   // instantiations of variable templates, except for those that could be used
16860   // in a constant expression.
16861   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16862     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16863     // instantiation declaration if a variable is usable in a constant
16864     // expression (among other cases).
16865     bool TryInstantiating =
16866         TSK == TSK_ImplicitInstantiation ||
16867         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16868 
16869     if (TryInstantiating) {
16870       SourceLocation PointOfInstantiation =
16871           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16872       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16873       if (FirstInstantiation) {
16874         PointOfInstantiation = Loc;
16875         if (MSI)
16876           MSI->setPointOfInstantiation(PointOfInstantiation);
16877         else
16878           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16879       }
16880 
16881       bool InstantiationDependent = false;
16882       bool IsNonDependent =
16883           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16884                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16885                   : true;
16886 
16887       // Do not instantiate specializations that are still type-dependent.
16888       if (IsNonDependent) {
16889         if (UsableInConstantExpr) {
16890           // Do not defer instantiations of variables that could be used in a
16891           // constant expression.
16892           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16893             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16894           });
16895         } else if (FirstInstantiation ||
16896                    isa<VarTemplateSpecializationDecl>(Var)) {
16897           // FIXME: For a specialization of a variable template, we don't
16898           // distinguish between "declaration and type implicitly instantiated"
16899           // and "implicit instantiation of definition requested", so we have
16900           // no direct way to avoid enqueueing the pending instantiation
16901           // multiple times.
16902           SemaRef.PendingInstantiations
16903               .push_back(std::make_pair(Var, PointOfInstantiation));
16904         }
16905       }
16906     }
16907   }
16908 
16909   // C++2a [basic.def.odr]p4:
16910   //   A variable x whose name appears as a potentially-evaluated expression e
16911   //   is odr-used by e unless
16912   //   -- x is a reference that is usable in constant expressions
16913   //   -- x is a variable of non-reference type that is usable in constant
16914   //      expressions and has no mutable subobjects [FIXME], and e is an
16915   //      element of the set of potential results of an expression of
16916   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16917   //      conversion is applied
16918   //   -- x is a variable of non-reference type, and e is an element of the set
16919   //      of potential results of a discarded-value expression to which the
16920   //      lvalue-to-rvalue conversion is not applied [FIXME]
16921   //
16922   // We check the first part of the second bullet here, and
16923   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16924   // FIXME: To get the third bullet right, we need to delay this even for
16925   // variables that are not usable in constant expressions.
16926 
16927   // If we already know this isn't an odr-use, there's nothing more to do.
16928   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16929     if (DRE->isNonOdrUse())
16930       return;
16931   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16932     if (ME->isNonOdrUse())
16933       return;
16934 
16935   switch (OdrUse) {
16936   case OdrUseContext::None:
16937     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16938            "missing non-odr-use marking for unevaluated decl ref");
16939     break;
16940 
16941   case OdrUseContext::FormallyOdrUsed:
16942     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16943     // behavior.
16944     break;
16945 
16946   case OdrUseContext::Used:
16947     // If we might later find that this expression isn't actually an odr-use,
16948     // delay the marking.
16949     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16950       SemaRef.MaybeODRUseExprs.insert(E);
16951     else
16952       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16953     break;
16954 
16955   case OdrUseContext::Dependent:
16956     // If this is a dependent context, we don't need to mark variables as
16957     // odr-used, but we may still need to track them for lambda capture.
16958     // FIXME: Do we also need to do this inside dependent typeid expressions
16959     // (which are modeled as unevaluated at this point)?
16960     const bool RefersToEnclosingScope =
16961         (SemaRef.CurContext != Var->getDeclContext() &&
16962          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16963     if (RefersToEnclosingScope) {
16964       LambdaScopeInfo *const LSI =
16965           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16966       if (LSI && (!LSI->CallOperator ||
16967                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16968         // If a variable could potentially be odr-used, defer marking it so
16969         // until we finish analyzing the full expression for any
16970         // lvalue-to-rvalue
16971         // or discarded value conversions that would obviate odr-use.
16972         // Add it to the list of potential captures that will be analyzed
16973         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16974         // unless the variable is a reference that was initialized by a constant
16975         // expression (this will never need to be captured or odr-used).
16976         //
16977         // FIXME: We can simplify this a lot after implementing P0588R1.
16978         assert(E && "Capture variable should be used in an expression.");
16979         if (!Var->getType()->isReferenceType() ||
16980             !Var->isUsableInConstantExpressions(SemaRef.Context))
16981           LSI->addPotentialCapture(E->IgnoreParens());
16982       }
16983     }
16984     break;
16985   }
16986 }
16987 
16988 /// Mark a variable referenced, and check whether it is odr-used
16989 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16990 /// used directly for normal expressions referring to VarDecl.
16991 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16992   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16993 }
16994 
16995 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16996                                Decl *D, Expr *E, bool MightBeOdrUse) {
16997   if (SemaRef.isInOpenMPDeclareTargetContext())
16998     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16999 
17000   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17001     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17002     return;
17003   }
17004 
17005   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17006 
17007   // If this is a call to a method via a cast, also mark the method in the
17008   // derived class used in case codegen can devirtualize the call.
17009   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17010   if (!ME)
17011     return;
17012   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17013   if (!MD)
17014     return;
17015   // Only attempt to devirtualize if this is truly a virtual call.
17016   bool IsVirtualCall = MD->isVirtual() &&
17017                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17018   if (!IsVirtualCall)
17019     return;
17020 
17021   // If it's possible to devirtualize the call, mark the called function
17022   // referenced.
17023   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17024       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17025   if (DM)
17026     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17027 }
17028 
17029 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17030 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17031   // TODO: update this with DR# once a defect report is filed.
17032   // C++11 defect. The address of a pure member should not be an ODR use, even
17033   // if it's a qualified reference.
17034   bool OdrUse = true;
17035   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17036     if (Method->isVirtual() &&
17037         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17038       OdrUse = false;
17039   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17040 }
17041 
17042 /// Perform reference-marking and odr-use handling for a MemberExpr.
17043 void Sema::MarkMemberReferenced(MemberExpr *E) {
17044   // C++11 [basic.def.odr]p2:
17045   //   A non-overloaded function whose name appears as a potentially-evaluated
17046   //   expression or a member of a set of candidate functions, if selected by
17047   //   overload resolution when referred to from a potentially-evaluated
17048   //   expression, is odr-used, unless it is a pure virtual function and its
17049   //   name is not explicitly qualified.
17050   bool MightBeOdrUse = true;
17051   if (E->performsVirtualDispatch(getLangOpts())) {
17052     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17053       if (Method->isPure())
17054         MightBeOdrUse = false;
17055   }
17056   SourceLocation Loc =
17057       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17058   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17059 }
17060 
17061 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17062 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17063   for (VarDecl *VD : *E)
17064     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17065 }
17066 
17067 /// Perform marking for a reference to an arbitrary declaration.  It
17068 /// marks the declaration referenced, and performs odr-use checking for
17069 /// functions and variables. This method should not be used when building a
17070 /// normal expression which refers to a variable.
17071 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17072                                  bool MightBeOdrUse) {
17073   if (MightBeOdrUse) {
17074     if (auto *VD = dyn_cast<VarDecl>(D)) {
17075       MarkVariableReferenced(Loc, VD);
17076       return;
17077     }
17078   }
17079   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17080     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17081     return;
17082   }
17083   D->setReferenced();
17084 }
17085 
17086 namespace {
17087   // Mark all of the declarations used by a type as referenced.
17088   // FIXME: Not fully implemented yet! We need to have a better understanding
17089   // of when we're entering a context we should not recurse into.
17090   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17091   // TreeTransforms rebuilding the type in a new context. Rather than
17092   // duplicating the TreeTransform logic, we should consider reusing it here.
17093   // Currently that causes problems when rebuilding LambdaExprs.
17094   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17095     Sema &S;
17096     SourceLocation Loc;
17097 
17098   public:
17099     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17100 
17101     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17102 
17103     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17104   };
17105 }
17106 
17107 bool MarkReferencedDecls::TraverseTemplateArgument(
17108     const TemplateArgument &Arg) {
17109   {
17110     // A non-type template argument is a constant-evaluated context.
17111     EnterExpressionEvaluationContext Evaluated(
17112         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17113     if (Arg.getKind() == TemplateArgument::Declaration) {
17114       if (Decl *D = Arg.getAsDecl())
17115         S.MarkAnyDeclReferenced(Loc, D, true);
17116     } else if (Arg.getKind() == TemplateArgument::Expression) {
17117       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17118     }
17119   }
17120 
17121   return Inherited::TraverseTemplateArgument(Arg);
17122 }
17123 
17124 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17125   MarkReferencedDecls Marker(*this, Loc);
17126   Marker.TraverseType(T);
17127 }
17128 
17129 namespace {
17130   /// Helper class that marks all of the declarations referenced by
17131   /// potentially-evaluated subexpressions as "referenced".
17132   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
17133     Sema &S;
17134     bool SkipLocalVariables;
17135 
17136   public:
17137     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
17138 
17139     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17140       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
17141 
17142     void VisitDeclRefExpr(DeclRefExpr *E) {
17143       // If we were asked not to visit local variables, don't.
17144       if (SkipLocalVariables) {
17145         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17146           if (VD->hasLocalStorage())
17147             return;
17148       }
17149 
17150       S.MarkDeclRefReferenced(E);
17151     }
17152 
17153     void VisitMemberExpr(MemberExpr *E) {
17154       S.MarkMemberReferenced(E);
17155       Inherited::VisitMemberExpr(E);
17156     }
17157 
17158     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17159       S.MarkFunctionReferenced(
17160           E->getBeginLoc(),
17161           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17162       Visit(E->getSubExpr());
17163     }
17164 
17165     void VisitCXXNewExpr(CXXNewExpr *E) {
17166       if (E->getOperatorNew())
17167         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
17168       if (E->getOperatorDelete())
17169         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17170       Inherited::VisitCXXNewExpr(E);
17171     }
17172 
17173     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17174       if (E->getOperatorDelete())
17175         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17176       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
17177       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17178         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17179         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
17180       }
17181 
17182       Inherited::VisitCXXDeleteExpr(E);
17183     }
17184 
17185     void VisitCXXConstructExpr(CXXConstructExpr *E) {
17186       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
17187       Inherited::VisitCXXConstructExpr(E);
17188     }
17189 
17190     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17191       Visit(E->getExpr());
17192     }
17193   };
17194 }
17195 
17196 /// Mark any declarations that appear within this expression or any
17197 /// potentially-evaluated subexpressions as "referenced".
17198 ///
17199 /// \param SkipLocalVariables If true, don't mark local variables as
17200 /// 'referenced'.
17201 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17202                                             bool SkipLocalVariables) {
17203   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17204 }
17205 
17206 /// Emit a diagnostic that describes an effect on the run-time behavior
17207 /// of the program being compiled.
17208 ///
17209 /// This routine emits the given diagnostic when the code currently being
17210 /// type-checked is "potentially evaluated", meaning that there is a
17211 /// possibility that the code will actually be executable. Code in sizeof()
17212 /// expressions, code used only during overload resolution, etc., are not
17213 /// potentially evaluated. This routine will suppress such diagnostics or,
17214 /// in the absolutely nutty case of potentially potentially evaluated
17215 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17216 /// later.
17217 ///
17218 /// This routine should be used for all diagnostics that describe the run-time
17219 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17220 /// Failure to do so will likely result in spurious diagnostics or failures
17221 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17222 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17223                                const PartialDiagnostic &PD) {
17224   switch (ExprEvalContexts.back().Context) {
17225   case ExpressionEvaluationContext::Unevaluated:
17226   case ExpressionEvaluationContext::UnevaluatedList:
17227   case ExpressionEvaluationContext::UnevaluatedAbstract:
17228   case ExpressionEvaluationContext::DiscardedStatement:
17229     // The argument will never be evaluated, so don't complain.
17230     break;
17231 
17232   case ExpressionEvaluationContext::ConstantEvaluated:
17233     // Relevant diagnostics should be produced by constant evaluation.
17234     break;
17235 
17236   case ExpressionEvaluationContext::PotentiallyEvaluated:
17237   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17238     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17239       FunctionScopes.back()->PossiblyUnreachableDiags.
17240         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17241       return true;
17242     }
17243 
17244     // The initializer of a constexpr variable or of the first declaration of a
17245     // static data member is not syntactically a constant evaluated constant,
17246     // but nonetheless is always required to be a constant expression, so we
17247     // can skip diagnosing.
17248     // FIXME: Using the mangling context here is a hack.
17249     if (auto *VD = dyn_cast_or_null<VarDecl>(
17250             ExprEvalContexts.back().ManglingContextDecl)) {
17251       if (VD->isConstexpr() ||
17252           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17253         break;
17254       // FIXME: For any other kind of variable, we should build a CFG for its
17255       // initializer and check whether the context in question is reachable.
17256     }
17257 
17258     Diag(Loc, PD);
17259     return true;
17260   }
17261 
17262   return false;
17263 }
17264 
17265 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17266                                const PartialDiagnostic &PD) {
17267   return DiagRuntimeBehavior(
17268       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17269 }
17270 
17271 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17272                                CallExpr *CE, FunctionDecl *FD) {
17273   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17274     return false;
17275 
17276   // If we're inside a decltype's expression, don't check for a valid return
17277   // type or construct temporaries until we know whether this is the last call.
17278   if (ExprEvalContexts.back().ExprContext ==
17279       ExpressionEvaluationContextRecord::EK_Decltype) {
17280     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17281     return false;
17282   }
17283 
17284   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17285     FunctionDecl *FD;
17286     CallExpr *CE;
17287 
17288   public:
17289     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17290       : FD(FD), CE(CE) { }
17291 
17292     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17293       if (!FD) {
17294         S.Diag(Loc, diag::err_call_incomplete_return)
17295           << T << CE->getSourceRange();
17296         return;
17297       }
17298 
17299       S.Diag(Loc, diag::err_call_function_incomplete_return)
17300         << CE->getSourceRange() << FD->getDeclName() << T;
17301       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17302           << FD->getDeclName();
17303     }
17304   } Diagnoser(FD, CE);
17305 
17306   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17307     return true;
17308 
17309   return false;
17310 }
17311 
17312 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17313 // will prevent this condition from triggering, which is what we want.
17314 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17315   SourceLocation Loc;
17316 
17317   unsigned diagnostic = diag::warn_condition_is_assignment;
17318   bool IsOrAssign = false;
17319 
17320   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17321     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17322       return;
17323 
17324     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17325 
17326     // Greylist some idioms by putting them into a warning subcategory.
17327     if (ObjCMessageExpr *ME
17328           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17329       Selector Sel = ME->getSelector();
17330 
17331       // self = [<foo> init...]
17332       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17333         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17334 
17335       // <foo> = [<bar> nextObject]
17336       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17337         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17338     }
17339 
17340     Loc = Op->getOperatorLoc();
17341   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17342     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17343       return;
17344 
17345     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17346     Loc = Op->getOperatorLoc();
17347   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17348     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17349   else {
17350     // Not an assignment.
17351     return;
17352   }
17353 
17354   Diag(Loc, diagnostic) << E->getSourceRange();
17355 
17356   SourceLocation Open = E->getBeginLoc();
17357   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17358   Diag(Loc, diag::note_condition_assign_silence)
17359         << FixItHint::CreateInsertion(Open, "(")
17360         << FixItHint::CreateInsertion(Close, ")");
17361 
17362   if (IsOrAssign)
17363     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17364       << FixItHint::CreateReplacement(Loc, "!=");
17365   else
17366     Diag(Loc, diag::note_condition_assign_to_comparison)
17367       << FixItHint::CreateReplacement(Loc, "==");
17368 }
17369 
17370 /// Redundant parentheses over an equality comparison can indicate
17371 /// that the user intended an assignment used as condition.
17372 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17373   // Don't warn if the parens came from a macro.
17374   SourceLocation parenLoc = ParenE->getBeginLoc();
17375   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17376     return;
17377   // Don't warn for dependent expressions.
17378   if (ParenE->isTypeDependent())
17379     return;
17380 
17381   Expr *E = ParenE->IgnoreParens();
17382 
17383   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17384     if (opE->getOpcode() == BO_EQ &&
17385         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17386                                                            == Expr::MLV_Valid) {
17387       SourceLocation Loc = opE->getOperatorLoc();
17388 
17389       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17390       SourceRange ParenERange = ParenE->getSourceRange();
17391       Diag(Loc, diag::note_equality_comparison_silence)
17392         << FixItHint::CreateRemoval(ParenERange.getBegin())
17393         << FixItHint::CreateRemoval(ParenERange.getEnd());
17394       Diag(Loc, diag::note_equality_comparison_to_assign)
17395         << FixItHint::CreateReplacement(Loc, "=");
17396     }
17397 }
17398 
17399 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17400                                        bool IsConstexpr) {
17401   DiagnoseAssignmentAsCondition(E);
17402   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17403     DiagnoseEqualityWithExtraParens(parenE);
17404 
17405   ExprResult result = CheckPlaceholderExpr(E);
17406   if (result.isInvalid()) return ExprError();
17407   E = result.get();
17408 
17409   if (!E->isTypeDependent()) {
17410     if (getLangOpts().CPlusPlus)
17411       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17412 
17413     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17414     if (ERes.isInvalid())
17415       return ExprError();
17416     E = ERes.get();
17417 
17418     QualType T = E->getType();
17419     if (!T->isScalarType()) { // C99 6.8.4.1p1
17420       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17421         << T << E->getSourceRange();
17422       return ExprError();
17423     }
17424     CheckBoolLikeConversion(E, Loc);
17425   }
17426 
17427   return E;
17428 }
17429 
17430 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17431                                            Expr *SubExpr, ConditionKind CK) {
17432   // Empty conditions are valid in for-statements.
17433   if (!SubExpr)
17434     return ConditionResult();
17435 
17436   ExprResult Cond;
17437   switch (CK) {
17438   case ConditionKind::Boolean:
17439     Cond = CheckBooleanCondition(Loc, SubExpr);
17440     break;
17441 
17442   case ConditionKind::ConstexprIf:
17443     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17444     break;
17445 
17446   case ConditionKind::Switch:
17447     Cond = CheckSwitchCondition(Loc, SubExpr);
17448     break;
17449   }
17450   if (Cond.isInvalid())
17451     return ConditionError();
17452 
17453   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17454   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17455   if (!FullExpr.get())
17456     return ConditionError();
17457 
17458   return ConditionResult(*this, nullptr, FullExpr,
17459                          CK == ConditionKind::ConstexprIf);
17460 }
17461 
17462 namespace {
17463   /// A visitor for rebuilding a call to an __unknown_any expression
17464   /// to have an appropriate type.
17465   struct RebuildUnknownAnyFunction
17466     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17467 
17468     Sema &S;
17469 
17470     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17471 
17472     ExprResult VisitStmt(Stmt *S) {
17473       llvm_unreachable("unexpected statement!");
17474     }
17475 
17476     ExprResult VisitExpr(Expr *E) {
17477       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17478         << E->getSourceRange();
17479       return ExprError();
17480     }
17481 
17482     /// Rebuild an expression which simply semantically wraps another
17483     /// expression which it shares the type and value kind of.
17484     template <class T> ExprResult rebuildSugarExpr(T *E) {
17485       ExprResult SubResult = Visit(E->getSubExpr());
17486       if (SubResult.isInvalid()) return ExprError();
17487 
17488       Expr *SubExpr = SubResult.get();
17489       E->setSubExpr(SubExpr);
17490       E->setType(SubExpr->getType());
17491       E->setValueKind(SubExpr->getValueKind());
17492       assert(E->getObjectKind() == OK_Ordinary);
17493       return E;
17494     }
17495 
17496     ExprResult VisitParenExpr(ParenExpr *E) {
17497       return rebuildSugarExpr(E);
17498     }
17499 
17500     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17501       return rebuildSugarExpr(E);
17502     }
17503 
17504     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17505       ExprResult SubResult = Visit(E->getSubExpr());
17506       if (SubResult.isInvalid()) return ExprError();
17507 
17508       Expr *SubExpr = SubResult.get();
17509       E->setSubExpr(SubExpr);
17510       E->setType(S.Context.getPointerType(SubExpr->getType()));
17511       assert(E->getValueKind() == VK_RValue);
17512       assert(E->getObjectKind() == OK_Ordinary);
17513       return E;
17514     }
17515 
17516     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17517       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17518 
17519       E->setType(VD->getType());
17520 
17521       assert(E->getValueKind() == VK_RValue);
17522       if (S.getLangOpts().CPlusPlus &&
17523           !(isa<CXXMethodDecl>(VD) &&
17524             cast<CXXMethodDecl>(VD)->isInstance()))
17525         E->setValueKind(VK_LValue);
17526 
17527       return E;
17528     }
17529 
17530     ExprResult VisitMemberExpr(MemberExpr *E) {
17531       return resolveDecl(E, E->getMemberDecl());
17532     }
17533 
17534     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17535       return resolveDecl(E, E->getDecl());
17536     }
17537   };
17538 }
17539 
17540 /// Given a function expression of unknown-any type, try to rebuild it
17541 /// to have a function type.
17542 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17543   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17544   if (Result.isInvalid()) return ExprError();
17545   return S.DefaultFunctionArrayConversion(Result.get());
17546 }
17547 
17548 namespace {
17549   /// A visitor for rebuilding an expression of type __unknown_anytype
17550   /// into one which resolves the type directly on the referring
17551   /// expression.  Strict preservation of the original source
17552   /// structure is not a goal.
17553   struct RebuildUnknownAnyExpr
17554     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17555 
17556     Sema &S;
17557 
17558     /// The current destination type.
17559     QualType DestType;
17560 
17561     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17562       : S(S), DestType(CastType) {}
17563 
17564     ExprResult VisitStmt(Stmt *S) {
17565       llvm_unreachable("unexpected statement!");
17566     }
17567 
17568     ExprResult VisitExpr(Expr *E) {
17569       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17570         << E->getSourceRange();
17571       return ExprError();
17572     }
17573 
17574     ExprResult VisitCallExpr(CallExpr *E);
17575     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17576 
17577     /// Rebuild an expression which simply semantically wraps another
17578     /// expression which it shares the type and value kind of.
17579     template <class T> ExprResult rebuildSugarExpr(T *E) {
17580       ExprResult SubResult = Visit(E->getSubExpr());
17581       if (SubResult.isInvalid()) return ExprError();
17582       Expr *SubExpr = SubResult.get();
17583       E->setSubExpr(SubExpr);
17584       E->setType(SubExpr->getType());
17585       E->setValueKind(SubExpr->getValueKind());
17586       assert(E->getObjectKind() == OK_Ordinary);
17587       return E;
17588     }
17589 
17590     ExprResult VisitParenExpr(ParenExpr *E) {
17591       return rebuildSugarExpr(E);
17592     }
17593 
17594     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17595       return rebuildSugarExpr(E);
17596     }
17597 
17598     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17599       const PointerType *Ptr = DestType->getAs<PointerType>();
17600       if (!Ptr) {
17601         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17602           << E->getSourceRange();
17603         return ExprError();
17604       }
17605 
17606       if (isa<CallExpr>(E->getSubExpr())) {
17607         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17608           << E->getSourceRange();
17609         return ExprError();
17610       }
17611 
17612       assert(E->getValueKind() == VK_RValue);
17613       assert(E->getObjectKind() == OK_Ordinary);
17614       E->setType(DestType);
17615 
17616       // Build the sub-expression as if it were an object of the pointee type.
17617       DestType = Ptr->getPointeeType();
17618       ExprResult SubResult = Visit(E->getSubExpr());
17619       if (SubResult.isInvalid()) return ExprError();
17620       E->setSubExpr(SubResult.get());
17621       return E;
17622     }
17623 
17624     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17625 
17626     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17627 
17628     ExprResult VisitMemberExpr(MemberExpr *E) {
17629       return resolveDecl(E, E->getMemberDecl());
17630     }
17631 
17632     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17633       return resolveDecl(E, E->getDecl());
17634     }
17635   };
17636 }
17637 
17638 /// Rebuilds a call expression which yielded __unknown_anytype.
17639 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17640   Expr *CalleeExpr = E->getCallee();
17641 
17642   enum FnKind {
17643     FK_MemberFunction,
17644     FK_FunctionPointer,
17645     FK_BlockPointer
17646   };
17647 
17648   FnKind Kind;
17649   QualType CalleeType = CalleeExpr->getType();
17650   if (CalleeType == S.Context.BoundMemberTy) {
17651     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17652     Kind = FK_MemberFunction;
17653     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17654   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17655     CalleeType = Ptr->getPointeeType();
17656     Kind = FK_FunctionPointer;
17657   } else {
17658     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17659     Kind = FK_BlockPointer;
17660   }
17661   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17662 
17663   // Verify that this is a legal result type of a function.
17664   if (DestType->isArrayType() || DestType->isFunctionType()) {
17665     unsigned diagID = diag::err_func_returning_array_function;
17666     if (Kind == FK_BlockPointer)
17667       diagID = diag::err_block_returning_array_function;
17668 
17669     S.Diag(E->getExprLoc(), diagID)
17670       << DestType->isFunctionType() << DestType;
17671     return ExprError();
17672   }
17673 
17674   // Otherwise, go ahead and set DestType as the call's result.
17675   E->setType(DestType.getNonLValueExprType(S.Context));
17676   E->setValueKind(Expr::getValueKindForType(DestType));
17677   assert(E->getObjectKind() == OK_Ordinary);
17678 
17679   // Rebuild the function type, replacing the result type with DestType.
17680   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17681   if (Proto) {
17682     // __unknown_anytype(...) is a special case used by the debugger when
17683     // it has no idea what a function's signature is.
17684     //
17685     // We want to build this call essentially under the K&R
17686     // unprototyped rules, but making a FunctionNoProtoType in C++
17687     // would foul up all sorts of assumptions.  However, we cannot
17688     // simply pass all arguments as variadic arguments, nor can we
17689     // portably just call the function under a non-variadic type; see
17690     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17691     // However, it turns out that in practice it is generally safe to
17692     // call a function declared as "A foo(B,C,D);" under the prototype
17693     // "A foo(B,C,D,...);".  The only known exception is with the
17694     // Windows ABI, where any variadic function is implicitly cdecl
17695     // regardless of its normal CC.  Therefore we change the parameter
17696     // types to match the types of the arguments.
17697     //
17698     // This is a hack, but it is far superior to moving the
17699     // corresponding target-specific code from IR-gen to Sema/AST.
17700 
17701     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17702     SmallVector<QualType, 8> ArgTypes;
17703     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17704       ArgTypes.reserve(E->getNumArgs());
17705       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17706         Expr *Arg = E->getArg(i);
17707         QualType ArgType = Arg->getType();
17708         if (E->isLValue()) {
17709           ArgType = S.Context.getLValueReferenceType(ArgType);
17710         } else if (E->isXValue()) {
17711           ArgType = S.Context.getRValueReferenceType(ArgType);
17712         }
17713         ArgTypes.push_back(ArgType);
17714       }
17715       ParamTypes = ArgTypes;
17716     }
17717     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17718                                          Proto->getExtProtoInfo());
17719   } else {
17720     DestType = S.Context.getFunctionNoProtoType(DestType,
17721                                                 FnType->getExtInfo());
17722   }
17723 
17724   // Rebuild the appropriate pointer-to-function type.
17725   switch (Kind) {
17726   case FK_MemberFunction:
17727     // Nothing to do.
17728     break;
17729 
17730   case FK_FunctionPointer:
17731     DestType = S.Context.getPointerType(DestType);
17732     break;
17733 
17734   case FK_BlockPointer:
17735     DestType = S.Context.getBlockPointerType(DestType);
17736     break;
17737   }
17738 
17739   // Finally, we can recurse.
17740   ExprResult CalleeResult = Visit(CalleeExpr);
17741   if (!CalleeResult.isUsable()) return ExprError();
17742   E->setCallee(CalleeResult.get());
17743 
17744   // Bind a temporary if necessary.
17745   return S.MaybeBindToTemporary(E);
17746 }
17747 
17748 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17749   // Verify that this is a legal result type of a call.
17750   if (DestType->isArrayType() || DestType->isFunctionType()) {
17751     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17752       << DestType->isFunctionType() << DestType;
17753     return ExprError();
17754   }
17755 
17756   // Rewrite the method result type if available.
17757   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17758     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17759     Method->setReturnType(DestType);
17760   }
17761 
17762   // Change the type of the message.
17763   E->setType(DestType.getNonReferenceType());
17764   E->setValueKind(Expr::getValueKindForType(DestType));
17765 
17766   return S.MaybeBindToTemporary(E);
17767 }
17768 
17769 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17770   // The only case we should ever see here is a function-to-pointer decay.
17771   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17772     assert(E->getValueKind() == VK_RValue);
17773     assert(E->getObjectKind() == OK_Ordinary);
17774 
17775     E->setType(DestType);
17776 
17777     // Rebuild the sub-expression as the pointee (function) type.
17778     DestType = DestType->castAs<PointerType>()->getPointeeType();
17779 
17780     ExprResult Result = Visit(E->getSubExpr());
17781     if (!Result.isUsable()) return ExprError();
17782 
17783     E->setSubExpr(Result.get());
17784     return E;
17785   } else if (E->getCastKind() == CK_LValueToRValue) {
17786     assert(E->getValueKind() == VK_RValue);
17787     assert(E->getObjectKind() == OK_Ordinary);
17788 
17789     assert(isa<BlockPointerType>(E->getType()));
17790 
17791     E->setType(DestType);
17792 
17793     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17794     DestType = S.Context.getLValueReferenceType(DestType);
17795 
17796     ExprResult Result = Visit(E->getSubExpr());
17797     if (!Result.isUsable()) return ExprError();
17798 
17799     E->setSubExpr(Result.get());
17800     return E;
17801   } else {
17802     llvm_unreachable("Unhandled cast type!");
17803   }
17804 }
17805 
17806 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17807   ExprValueKind ValueKind = VK_LValue;
17808   QualType Type = DestType;
17809 
17810   // We know how to make this work for certain kinds of decls:
17811 
17812   //  - functions
17813   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17814     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17815       DestType = Ptr->getPointeeType();
17816       ExprResult Result = resolveDecl(E, VD);
17817       if (Result.isInvalid()) return ExprError();
17818       return S.ImpCastExprToType(Result.get(), Type,
17819                                  CK_FunctionToPointerDecay, VK_RValue);
17820     }
17821 
17822     if (!Type->isFunctionType()) {
17823       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17824         << VD << E->getSourceRange();
17825       return ExprError();
17826     }
17827     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17828       // We must match the FunctionDecl's type to the hack introduced in
17829       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17830       // type. See the lengthy commentary in that routine.
17831       QualType FDT = FD->getType();
17832       const FunctionType *FnType = FDT->castAs<FunctionType>();
17833       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17834       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17835       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17836         SourceLocation Loc = FD->getLocation();
17837         FunctionDecl *NewFD = FunctionDecl::Create(
17838             S.Context, FD->getDeclContext(), Loc, Loc,
17839             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17840             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17841             /*ConstexprKind*/ CSK_unspecified);
17842 
17843         if (FD->getQualifier())
17844           NewFD->setQualifierInfo(FD->getQualifierLoc());
17845 
17846         SmallVector<ParmVarDecl*, 16> Params;
17847         for (const auto &AI : FT->param_types()) {
17848           ParmVarDecl *Param =
17849             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17850           Param->setScopeInfo(0, Params.size());
17851           Params.push_back(Param);
17852         }
17853         NewFD->setParams(Params);
17854         DRE->setDecl(NewFD);
17855         VD = DRE->getDecl();
17856       }
17857     }
17858 
17859     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17860       if (MD->isInstance()) {
17861         ValueKind = VK_RValue;
17862         Type = S.Context.BoundMemberTy;
17863       }
17864 
17865     // Function references aren't l-values in C.
17866     if (!S.getLangOpts().CPlusPlus)
17867       ValueKind = VK_RValue;
17868 
17869   //  - variables
17870   } else if (isa<VarDecl>(VD)) {
17871     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17872       Type = RefTy->getPointeeType();
17873     } else if (Type->isFunctionType()) {
17874       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17875         << VD << E->getSourceRange();
17876       return ExprError();
17877     }
17878 
17879   //  - nothing else
17880   } else {
17881     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17882       << VD << E->getSourceRange();
17883     return ExprError();
17884   }
17885 
17886   // Modifying the declaration like this is friendly to IR-gen but
17887   // also really dangerous.
17888   VD->setType(DestType);
17889   E->setType(Type);
17890   E->setValueKind(ValueKind);
17891   return E;
17892 }
17893 
17894 /// Check a cast of an unknown-any type.  We intentionally only
17895 /// trigger this for C-style casts.
17896 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17897                                      Expr *CastExpr, CastKind &CastKind,
17898                                      ExprValueKind &VK, CXXCastPath &Path) {
17899   // The type we're casting to must be either void or complete.
17900   if (!CastType->isVoidType() &&
17901       RequireCompleteType(TypeRange.getBegin(), CastType,
17902                           diag::err_typecheck_cast_to_incomplete))
17903     return ExprError();
17904 
17905   // Rewrite the casted expression from scratch.
17906   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17907   if (!result.isUsable()) return ExprError();
17908 
17909   CastExpr = result.get();
17910   VK = CastExpr->getValueKind();
17911   CastKind = CK_NoOp;
17912 
17913   return CastExpr;
17914 }
17915 
17916 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17917   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17918 }
17919 
17920 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17921                                     Expr *arg, QualType &paramType) {
17922   // If the syntactic form of the argument is not an explicit cast of
17923   // any sort, just do default argument promotion.
17924   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17925   if (!castArg) {
17926     ExprResult result = DefaultArgumentPromotion(arg);
17927     if (result.isInvalid()) return ExprError();
17928     paramType = result.get()->getType();
17929     return result;
17930   }
17931 
17932   // Otherwise, use the type that was written in the explicit cast.
17933   assert(!arg->hasPlaceholderType());
17934   paramType = castArg->getTypeAsWritten();
17935 
17936   // Copy-initialize a parameter of that type.
17937   InitializedEntity entity =
17938     InitializedEntity::InitializeParameter(Context, paramType,
17939                                            /*consumed*/ false);
17940   return PerformCopyInitialization(entity, callLoc, arg);
17941 }
17942 
17943 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17944   Expr *orig = E;
17945   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17946   while (true) {
17947     E = E->IgnoreParenImpCasts();
17948     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17949       E = call->getCallee();
17950       diagID = diag::err_uncasted_call_of_unknown_any;
17951     } else {
17952       break;
17953     }
17954   }
17955 
17956   SourceLocation loc;
17957   NamedDecl *d;
17958   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17959     loc = ref->getLocation();
17960     d = ref->getDecl();
17961   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17962     loc = mem->getMemberLoc();
17963     d = mem->getMemberDecl();
17964   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17965     diagID = diag::err_uncasted_call_of_unknown_any;
17966     loc = msg->getSelectorStartLoc();
17967     d = msg->getMethodDecl();
17968     if (!d) {
17969       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17970         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17971         << orig->getSourceRange();
17972       return ExprError();
17973     }
17974   } else {
17975     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17976       << E->getSourceRange();
17977     return ExprError();
17978   }
17979 
17980   S.Diag(loc, diagID) << d << orig->getSourceRange();
17981 
17982   // Never recoverable.
17983   return ExprError();
17984 }
17985 
17986 /// Check for operands with placeholder types and complain if found.
17987 /// Returns ExprError() if there was an error and no recovery was possible.
17988 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17989   if (!getLangOpts().CPlusPlus) {
17990     // C cannot handle TypoExpr nodes on either side of a binop because it
17991     // doesn't handle dependent types properly, so make sure any TypoExprs have
17992     // been dealt with before checking the operands.
17993     ExprResult Result = CorrectDelayedTyposInExpr(E);
17994     if (!Result.isUsable()) return ExprError();
17995     E = Result.get();
17996   }
17997 
17998   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17999   if (!placeholderType) return E;
18000 
18001   switch (placeholderType->getKind()) {
18002 
18003   // Overloaded expressions.
18004   case BuiltinType::Overload: {
18005     // Try to resolve a single function template specialization.
18006     // This is obligatory.
18007     ExprResult Result = E;
18008     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18009       return Result;
18010 
18011     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18012     // leaves Result unchanged on failure.
18013     Result = E;
18014     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18015       return Result;
18016 
18017     // If that failed, try to recover with a call.
18018     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18019                          /*complain*/ true);
18020     return Result;
18021   }
18022 
18023   // Bound member functions.
18024   case BuiltinType::BoundMember: {
18025     ExprResult result = E;
18026     const Expr *BME = E->IgnoreParens();
18027     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18028     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18029     if (isa<CXXPseudoDestructorExpr>(BME)) {
18030       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18031     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18032       if (ME->getMemberNameInfo().getName().getNameKind() ==
18033           DeclarationName::CXXDestructorName)
18034         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18035     }
18036     tryToRecoverWithCall(result, PD,
18037                          /*complain*/ true);
18038     return result;
18039   }
18040 
18041   // ARC unbridged casts.
18042   case BuiltinType::ARCUnbridgedCast: {
18043     Expr *realCast = stripARCUnbridgedCast(E);
18044     diagnoseARCUnbridgedCast(realCast);
18045     return realCast;
18046   }
18047 
18048   // Expressions of unknown type.
18049   case BuiltinType::UnknownAny:
18050     return diagnoseUnknownAnyExpr(*this, E);
18051 
18052   // Pseudo-objects.
18053   case BuiltinType::PseudoObject:
18054     return checkPseudoObjectRValue(E);
18055 
18056   case BuiltinType::BuiltinFn: {
18057     // Accept __noop without parens by implicitly converting it to a call expr.
18058     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18059     if (DRE) {
18060       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18061       if (FD->getBuiltinID() == Builtin::BI__noop) {
18062         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18063                               CK_BuiltinFnToFnPtr)
18064                 .get();
18065         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18066                                 VK_RValue, SourceLocation());
18067       }
18068     }
18069 
18070     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18071     return ExprError();
18072   }
18073 
18074   // Expressions of unknown type.
18075   case BuiltinType::OMPArraySection:
18076     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18077     return ExprError();
18078 
18079   // Everything else should be impossible.
18080 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18081   case BuiltinType::Id:
18082 #include "clang/Basic/OpenCLImageTypes.def"
18083 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18084   case BuiltinType::Id:
18085 #include "clang/Basic/OpenCLExtensionTypes.def"
18086 #define SVE_TYPE(Name, Id, SingletonId) \
18087   case BuiltinType::Id:
18088 #include "clang/Basic/AArch64SVEACLETypes.def"
18089 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18090 #define PLACEHOLDER_TYPE(Id, SingletonId)
18091 #include "clang/AST/BuiltinTypes.def"
18092     break;
18093   }
18094 
18095   llvm_unreachable("invalid placeholder type!");
18096 }
18097 
18098 bool Sema::CheckCaseExpression(Expr *E) {
18099   if (E->isTypeDependent())
18100     return true;
18101   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18102     return E->getType()->isIntegralOrEnumerationType();
18103   return false;
18104 }
18105 
18106 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18107 ExprResult
18108 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18109   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18110          "Unknown Objective-C Boolean value!");
18111   QualType BoolT = Context.ObjCBuiltinBoolTy;
18112   if (!Context.getBOOLDecl()) {
18113     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18114                         Sema::LookupOrdinaryName);
18115     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18116       NamedDecl *ND = Result.getFoundDecl();
18117       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18118         Context.setBOOLDecl(TD);
18119     }
18120   }
18121   if (Context.getBOOLDecl())
18122     BoolT = Context.getBOOLType();
18123   return new (Context)
18124       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18125 }
18126 
18127 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18128     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18129     SourceLocation RParen) {
18130 
18131   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18132 
18133   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18134     return Spec.getPlatform() == Platform;
18135   });
18136 
18137   VersionTuple Version;
18138   if (Spec != AvailSpecs.end())
18139     Version = Spec->getVersion();
18140 
18141   // The use of `@available` in the enclosing function should be analyzed to
18142   // warn when it's used inappropriately (i.e. not if(@available)).
18143   if (getCurFunctionOrMethodDecl())
18144     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18145   else if (getCurBlock() || getCurLambda())
18146     getCurFunction()->HasPotentialAvailabilityViolations = true;
18147 
18148   return new (Context)
18149       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18150 }
18151 
18152 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18153   assert(E->isTypeDependent());
18154   return isa<UnresolvedLookupExpr>(E);
18155 }
18156