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/FixedPoint.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
341                                  ArrayRef<Expr *> Args) {
342   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343   if (!attr)
344     return;
345 
346   // The number of formal parameters of the declaration.
347   unsigned numFormalParams;
348 
349   // The kind of declaration.  This is also an index into a %select in
350   // the diagnostic.
351   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354     numFormalParams = MD->param_size();
355     calleeType = CT_Method;
356   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357     numFormalParams = FD->param_size();
358     calleeType = CT_Function;
359   } else if (isa<VarDecl>(D)) {
360     QualType type = cast<ValueDecl>(D)->getType();
361     const FunctionType *fn = nullptr;
362     if (const PointerType *ptr = type->getAs<PointerType>()) {
363       fn = ptr->getPointeeType()->getAs<FunctionType>();
364       if (!fn) return;
365       calleeType = CT_Function;
366     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367       fn = ptr->getPointeeType()->castAs<FunctionType>();
368       calleeType = CT_Block;
369     } else {
370       return;
371     }
372 
373     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374       numFormalParams = proto->getNumParams();
375     } else {
376       numFormalParams = 0;
377     }
378   } else {
379     return;
380   }
381 
382   // "nullPos" is the number of formal parameters at the end which
383   // effectively count as part of the variadic arguments.  This is
384   // useful if you would prefer to not have *any* formal parameters,
385   // but the language forces you to have at least one.
386   unsigned nullPos = attr->getNullPos();
387   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390   // The number of arguments which should follow the sentinel.
391   unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393   // If there aren't enough arguments for all the formal parameters,
394   // the sentinel, and the args after the sentinel, complain.
395   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398     return;
399   }
400 
401   // Otherwise, find the sentinel expression.
402   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403   if (!sentinelExpr) return;
404   if (sentinelExpr->isValueDependent()) return;
405   if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
408   // or 'NULL' if those are actually defined in the context.  Only use
409   // 'nil' for ObjC methods, where it's much more likely that the
410   // variadic arguments form a list of object pointers.
411   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412   std::string NullValue;
413   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414     NullValue = "nil";
415   else if (getLangOpts().CPlusPlus11)
416     NullValue = "nullptr";
417   else if (PP.isMacroDefined("NULL"))
418     NullValue = "NULL";
419   else
420     NullValue = "(void*) 0";
421 
422   if (MissingNilLoc.isInvalid())
423     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424   else
425     Diag(MissingNilLoc, diag::warn_missing_sentinel)
426       << int(calleeType)
427       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
431 SourceRange Sema::getExprRange(Expr *E) const {
432   return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //  Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
441   // Handle any placeholder expressions which made it here.
442   if (E->getType()->isPlaceholderType()) {
443     ExprResult result = CheckPlaceholderExpr(E);
444     if (result.isInvalid()) return ExprError();
445     E = result.get();
446   }
447 
448   QualType Ty = E->getType();
449   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451   if (Ty->isFunctionType()) {
452     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455           return ExprError();
456 
457     E = ImpCastExprToType(E, Context.getPointerType(Ty),
458                           CK_FunctionToPointerDecay).get();
459   } else if (Ty->isArrayType()) {
460     // In C90 mode, arrays only promote to pointers if the array expression is
461     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462     // type 'array of type' is converted to an expression that has type 'pointer
463     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
464     // that has type 'array of type' ...".  The relevant change is "an lvalue"
465     // (C90) to "an expression" (C99).
466     //
467     // C++ 4.2p1:
468     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469     // T" can be converted to an rvalue of type "pointer to T".
470     //
471     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473                             CK_ArrayToPointerDecay).get();
474   }
475   return E;
476 }
477 
478 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
479   // Check to see if we are dereferencing a null pointer.  If so,
480   // and if not volatile-qualified, this is undefined behavior that the
481   // optimizer will delete, so warn about it.  People sometimes try to use this
482   // to get a deterministic trap and are surprised by clang's behavior.  This
483   // only handles the pattern "*null", which is a very syntactic check.
484   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485     if (UO->getOpcode() == UO_Deref &&
486         UO->getSubExpr()->IgnoreParenCasts()->
487           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488         !UO->getType().isVolatileQualified()) {
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                           S.PDiag(diag::warn_indirection_through_null)
491                             << UO->getSubExpr()->getSourceRange());
492     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493                         S.PDiag(diag::note_indirection_through_null));
494   }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498                                     SourceLocation AssignLoc,
499                                     const Expr* RHS) {
500   const ObjCIvarDecl *IV = OIRE->getDecl();
501   if (!IV)
502     return;
503 
504   DeclarationName MemberName = IV->getDeclName();
505   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506   if (!Member || !Member->isStr("isa"))
507     return;
508 
509   const Expr *Base = OIRE->getBase();
510   QualType BaseType = Base->getType();
511   if (OIRE->isArrow())
512     BaseType = BaseType->getPointeeType();
513   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515       ObjCInterfaceDecl *ClassDeclared = nullptr;
516       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517       if (!ClassDeclared->getSuperClass()
518           && (*ClassDeclared->ivar_begin()) == IV) {
519         if (RHS) {
520           NamedDecl *ObjectSetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_setClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectSetClass) {
525             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528                                               "object_setClass(")
529                 << FixItHint::CreateReplacement(
530                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
532           }
533           else
534             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535         } else {
536           NamedDecl *ObjectGetClass =
537             S.LookupSingleName(S.TUScope,
538                                &S.Context.Idents.get("object_getClass"),
539                                SourceLocation(), S.LookupOrdinaryName);
540           if (ObjectGetClass)
541             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543                                               "object_getClass(")
544                 << FixItHint::CreateReplacement(
545                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546           else
547             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548         }
549         S.Diag(IV->getLocation(), diag::note_ivar_decl);
550       }
551     }
552 }
553 
554 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
555   // Handle any placeholder expressions which made it here.
556   if (E->getType()->isPlaceholderType()) {
557     ExprResult result = CheckPlaceholderExpr(E);
558     if (result.isInvalid()) return ExprError();
559     E = result.get();
560   }
561 
562   // C++ [conv.lval]p1:
563   //   A glvalue of a non-function, non-array type T can be
564   //   converted to a prvalue.
565   if (!E->isGLValue()) return E;
566 
567   QualType T = E->getType();
568   assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570   // We don't want to throw lvalue-to-rvalue casts on top of
571   // expressions of certain types in C++.
572   if (getLangOpts().CPlusPlus &&
573       (E->getType() == Context.OverloadTy ||
574        T->isDependentType() ||
575        T->isRecordType()))
576     return E;
577 
578   // The C standard is actually really unclear on this point, and
579   // DR106 tells us what the result should be but not why.  It's
580   // generally best to say that void types just doesn't undergo
581   // lvalue-to-rvalue at all.  Note that expressions of unqualified
582   // 'void' type are never l-values, but qualified void can be.
583   if (T->isVoidType())
584     return E;
585 
586   // OpenCL usually rejects direct accesses to values of 'half' type.
587   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588       T->isHalfType()) {
589     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590       << 0 << T;
591     return ExprError();
592   }
593 
594   CheckForNullPointerDereference(*this, E);
595   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597                                      &Context.Idents.get("object_getClass"),
598                                      SourceLocation(), LookupOrdinaryName);
599     if (ObjectGetClass)
600       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602           << FixItHint::CreateReplacement(
603                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604     else
605       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606   }
607   else if (const ObjCIvarRefExpr *OIRE =
608             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611   // C++ [conv.lval]p1:
612   //   [...] If T is a non-class type, the type of the prvalue is the
613   //   cv-unqualified version of T. Otherwise, the type of the
614   //   rvalue is T.
615   //
616   // C99 6.3.2.1p2:
617   //   If the lvalue has qualified type, the value has the unqualified
618   //   version of the type of the lvalue; otherwise, the value has the
619   //   type of the lvalue.
620   if (T.hasQualifiers())
621     T = T.getUnqualifiedType();
622 
623   // Under the MS ABI, lock down the inheritance model now.
624   if (T->isMemberPointerType() &&
625       Context.getTargetInfo().getCXXABI().isMicrosoft())
626     (void)isCompleteType(E->getExprLoc(), T);
627 
628   ExprResult Res = CheckLValueToRValueConversionOperand(E);
629   if (Res.isInvalid())
630     return Res;
631   E = Res.get();
632 
633   // Loading a __weak object implicitly retains the value, so we need a cleanup to
634   // balance that.
635   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
636     Cleanup.setExprNeedsCleanups(true);
637 
638   // C++ [conv.lval]p3:
639   //   If T is cv std::nullptr_t, the result is a null pointer constant.
640   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
641   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
642 
643   // C11 6.3.2.1p2:
644   //   ... if the lvalue has atomic type, the value has the non-atomic version
645   //   of the type of the lvalue ...
646   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
647     T = Atomic->getValueType().getUnqualifiedType();
648     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649                                    nullptr, VK_RValue);
650   }
651 
652   return Res;
653 }
654 
655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
656   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
657   if (Res.isInvalid())
658     return ExprError();
659   Res = DefaultLvalueConversion(Res.get());
660   if (Res.isInvalid())
661     return ExprError();
662   return Res;
663 }
664 
665 /// CallExprUnaryConversions - a special case of an unary conversion
666 /// performed on a function designator of a call expression.
667 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
668   QualType Ty = E->getType();
669   ExprResult Res = E;
670   // Only do implicit cast for a function type, but not for a pointer
671   // to function type.
672   if (Ty->isFunctionType()) {
673     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
674                             CK_FunctionToPointerDecay).get();
675     if (Res.isInvalid())
676       return ExprError();
677   }
678   Res = DefaultLvalueConversion(Res.get());
679   if (Res.isInvalid())
680     return ExprError();
681   return Res.get();
682 }
683 
684 /// UsualUnaryConversions - Performs various conversions that are common to most
685 /// operators (C99 6.3). The conversions of array and function types are
686 /// sometimes suppressed. For example, the array->pointer conversion doesn't
687 /// apply if the array is an argument to the sizeof or address (&) operators.
688 /// In these instances, this routine should *not* be called.
689 ExprResult Sema::UsualUnaryConversions(Expr *E) {
690   // First, convert to an r-value.
691   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
692   if (Res.isInvalid())
693     return ExprError();
694   E = Res.get();
695 
696   QualType Ty = E->getType();
697   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
698 
699   // Half FP have to be promoted to float unless it is natively supported
700   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
701     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
702 
703   // Try to perform integral promotions if the object has a theoretically
704   // promotable type.
705   if (Ty->isIntegralOrUnscopedEnumerationType()) {
706     // C99 6.3.1.1p2:
707     //
708     //   The following may be used in an expression wherever an int or
709     //   unsigned int may be used:
710     //     - an object or expression with an integer type whose integer
711     //       conversion rank is less than or equal to the rank of int
712     //       and unsigned int.
713     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
714     //
715     //   If an int can represent all values of the original type, the
716     //   value is converted to an int; otherwise, it is converted to an
717     //   unsigned int. These are called the integer promotions. All
718     //   other types are unchanged by the integer promotions.
719 
720     QualType PTy = Context.isPromotableBitField(E);
721     if (!PTy.isNull()) {
722       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
723       return E;
724     }
725     if (Ty->isPromotableIntegerType()) {
726       QualType PT = Context.getPromotedIntegerType(Ty);
727       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728       return E;
729     }
730   }
731   return E;
732 }
733 
734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
735 /// do not have a prototype. Arguments that have type float or __fp16
736 /// are promoted to double. All other argument types are converted by
737 /// UsualUnaryConversions().
738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
739   QualType Ty = E->getType();
740   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
741 
742   ExprResult Res = UsualUnaryConversions(E);
743   if (Res.isInvalid())
744     return ExprError();
745   E = Res.get();
746 
747   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
748   // promote to double.
749   // Note that default argument promotion applies only to float (and
750   // half/fp16); it does not apply to _Float16.
751   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
752   if (BTy && (BTy->getKind() == BuiltinType::Half ||
753               BTy->getKind() == BuiltinType::Float)) {
754     if (getLangOpts().OpenCL &&
755         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
756         if (BTy->getKind() == BuiltinType::Half) {
757             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
758         }
759     } else {
760       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
761     }
762   }
763 
764   // C++ performs lvalue-to-rvalue conversion as a default argument
765   // promotion, even on class types, but note:
766   //   C++11 [conv.lval]p2:
767   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
768   //     operand or a subexpression thereof the value contained in the
769   //     referenced object is not accessed. Otherwise, if the glvalue
770   //     has a class type, the conversion copy-initializes a temporary
771   //     of type T from the glvalue and the result of the conversion
772   //     is a prvalue for the temporary.
773   // FIXME: add some way to gate this entire thing for correctness in
774   // potentially potentially evaluated contexts.
775   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
776     ExprResult Temp = PerformCopyInitialization(
777                        InitializedEntity::InitializeTemporary(E->getType()),
778                                                 E->getExprLoc(), E);
779     if (Temp.isInvalid())
780       return ExprError();
781     E = Temp.get();
782   }
783 
784   return E;
785 }
786 
787 /// Determine the degree of POD-ness for an expression.
788 /// Incomplete types are considered POD, since this check can be performed
789 /// when we're in an unevaluated context.
790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
791   if (Ty->isIncompleteType()) {
792     // C++11 [expr.call]p7:
793     //   After these conversions, if the argument does not have arithmetic,
794     //   enumeration, pointer, pointer to member, or class type, the program
795     //   is ill-formed.
796     //
797     // Since we've already performed array-to-pointer and function-to-pointer
798     // decay, the only such type in C++ is cv void. This also handles
799     // initializer lists as variadic arguments.
800     if (Ty->isVoidType())
801       return VAK_Invalid;
802 
803     if (Ty->isObjCObjectType())
804       return VAK_Invalid;
805     return VAK_Valid;
806   }
807 
808   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
809     return VAK_Invalid;
810 
811   if (Ty.isCXX98PODType(Context))
812     return VAK_Valid;
813 
814   // C++11 [expr.call]p7:
815   //   Passing a potentially-evaluated argument of class type (Clause 9)
816   //   having a non-trivial copy constructor, a non-trivial move constructor,
817   //   or a non-trivial destructor, with no corresponding parameter,
818   //   is conditionally-supported with implementation-defined semantics.
819   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
820     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
821       if (!Record->hasNonTrivialCopyConstructor() &&
822           !Record->hasNonTrivialMoveConstructor() &&
823           !Record->hasNonTrivialDestructor())
824         return VAK_ValidInCXX11;
825 
826   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
827     return VAK_Valid;
828 
829   if (Ty->isObjCObjectType())
830     return VAK_Invalid;
831 
832   if (getLangOpts().MSVCCompat)
833     return VAK_MSVCUndefined;
834 
835   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
836   // permitted to reject them. We should consider doing so.
837   return VAK_Undefined;
838 }
839 
840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
841   // Don't allow one to pass an Objective-C interface to a vararg.
842   const QualType &Ty = E->getType();
843   VarArgKind VAK = isValidVarArgType(Ty);
844 
845   // Complain about passing non-POD types through varargs.
846   switch (VAK) {
847   case VAK_ValidInCXX11:
848     DiagRuntimeBehavior(
849         E->getBeginLoc(), nullptr,
850         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
851     LLVM_FALLTHROUGH;
852   case VAK_Valid:
853     if (Ty->isRecordType()) {
854       // This is unlikely to be what the user intended. If the class has a
855       // 'c_str' member function, the user probably meant to call that.
856       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
857                           PDiag(diag::warn_pass_class_arg_to_vararg)
858                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
859     }
860     break;
861 
862   case VAK_Undefined:
863   case VAK_MSVCUndefined:
864     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
865                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
866                             << getLangOpts().CPlusPlus11 << Ty << CT);
867     break;
868 
869   case VAK_Invalid:
870     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
871       Diag(E->getBeginLoc(),
872            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
873           << Ty << CT;
874     else if (Ty->isObjCObjectType())
875       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
876                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
877                               << Ty << CT);
878     else
879       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
880           << isa<InitListExpr>(E) << Ty << CT;
881     break;
882   }
883 }
884 
885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
886 /// will create a trap if the resulting type is not a POD type.
887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
888                                                   FunctionDecl *FDecl) {
889   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
890     // Strip the unbridged-cast placeholder expression off, if applicable.
891     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
892         (CT == VariadicMethod ||
893          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
894       E = stripARCUnbridgedCast(E);
895 
896     // Otherwise, do normal placeholder checking.
897     } else {
898       ExprResult ExprRes = CheckPlaceholderExpr(E);
899       if (ExprRes.isInvalid())
900         return ExprError();
901       E = ExprRes.get();
902     }
903   }
904 
905   ExprResult ExprRes = DefaultArgumentPromotion(E);
906   if (ExprRes.isInvalid())
907     return ExprError();
908   E = ExprRes.get();
909 
910   // Diagnostics regarding non-POD argument types are
911   // emitted along with format string checking in Sema::CheckFunctionCall().
912   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
913     // Turn this into a trap.
914     CXXScopeSpec SS;
915     SourceLocation TemplateKWLoc;
916     UnqualifiedId Name;
917     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
918                        E->getBeginLoc());
919     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
920                                           /*HasTrailingLParen=*/true,
921                                           /*IsAddressOfOperand=*/false);
922     if (TrapFn.isInvalid())
923       return ExprError();
924 
925     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
926                                     None, E->getEndLoc());
927     if (Call.isInvalid())
928       return ExprError();
929 
930     ExprResult Comma =
931         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
932     if (Comma.isInvalid())
933       return ExprError();
934     return Comma.get();
935   }
936 
937   if (!getLangOpts().CPlusPlus &&
938       RequireCompleteType(E->getExprLoc(), E->getType(),
939                           diag::err_call_incomplete_argument))
940     return ExprError();
941 
942   return E;
943 }
944 
945 /// Converts an integer to complex float type.  Helper function of
946 /// UsualArithmeticConversions()
947 ///
948 /// \return false if the integer expression is an integer type and is
949 /// successfully converted to the complex type.
950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
951                                                   ExprResult &ComplexExpr,
952                                                   QualType IntTy,
953                                                   QualType ComplexTy,
954                                                   bool SkipCast) {
955   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
956   if (SkipCast) return false;
957   if (IntTy->isIntegerType()) {
958     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
960     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
961                                   CK_FloatingRealToComplex);
962   } else {
963     assert(IntTy->isComplexIntegerType());
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
965                                   CK_IntegralComplexToFloatingComplex);
966   }
967   return false;
968 }
969 
970 /// Handle arithmetic conversion with complex types.  Helper function of
971 /// UsualArithmeticConversions()
972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
973                                              ExprResult &RHS, QualType LHSType,
974                                              QualType RHSType,
975                                              bool IsCompAssign) {
976   // if we have an integer operand, the result is the complex type.
977   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
978                                              /*skipCast*/false))
979     return LHSType;
980   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
981                                              /*skipCast*/IsCompAssign))
982     return RHSType;
983 
984   // This handles complex/complex, complex/float, or float/complex.
985   // When both operands are complex, the shorter operand is converted to the
986   // type of the longer, and that is the type of the result. This corresponds
987   // to what is done when combining two real floating-point operands.
988   // The fun begins when size promotion occur across type domains.
989   // From H&S 6.3.4: When one operand is complex and the other is a real
990   // floating-point type, the less precise type is converted, within it's
991   // real or complex domain, to the precision of the other type. For example,
992   // when combining a "long double" with a "double _Complex", the
993   // "double _Complex" is promoted to "long double _Complex".
994 
995   // Compute the rank of the two types, regardless of whether they are complex.
996   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
997 
998   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
999   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1000   QualType LHSElementType =
1001       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1002   QualType RHSElementType =
1003       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1004 
1005   QualType ResultType = S.Context.getComplexType(LHSElementType);
1006   if (Order < 0) {
1007     // Promote the precision of the LHS if not an assignment.
1008     ResultType = S.Context.getComplexType(RHSElementType);
1009     if (!IsCompAssign) {
1010       if (LHSComplexType)
1011         LHS =
1012             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1013       else
1014         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1015     }
1016   } else if (Order > 0) {
1017     // Promote the precision of the RHS.
1018     if (RHSComplexType)
1019       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1020     else
1021       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1022   }
1023   return ResultType;
1024 }
1025 
1026 /// Handle arithmetic conversion from integer to float.  Helper function
1027 /// of UsualArithmeticConversions()
1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1029                                            ExprResult &IntExpr,
1030                                            QualType FloatTy, QualType IntTy,
1031                                            bool ConvertFloat, bool ConvertInt) {
1032   if (IntTy->isIntegerType()) {
1033     if (ConvertInt)
1034       // Convert intExpr to the lhs floating point type.
1035       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1036                                     CK_IntegralToFloating);
1037     return FloatTy;
1038   }
1039 
1040   // Convert both sides to the appropriate complex float.
1041   assert(IntTy->isComplexIntegerType());
1042   QualType result = S.Context.getComplexType(FloatTy);
1043 
1044   // _Complex int -> _Complex float
1045   if (ConvertInt)
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1047                                   CK_IntegralComplexToFloatingComplex);
1048 
1049   // float -> _Complex float
1050   if (ConvertFloat)
1051     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1052                                     CK_FloatingRealToComplex);
1053 
1054   return result;
1055 }
1056 
1057 /// Handle arithmethic conversion with floating point types.  Helper
1058 /// function of UsualArithmeticConversions()
1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1060                                       ExprResult &RHS, QualType LHSType,
1061                                       QualType RHSType, bool IsCompAssign) {
1062   bool LHSFloat = LHSType->isRealFloatingType();
1063   bool RHSFloat = RHSType->isRealFloatingType();
1064 
1065   // If we have two real floating types, convert the smaller operand
1066   // to the bigger result.
1067   if (LHSFloat && RHSFloat) {
1068     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1069     if (order > 0) {
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1071       return LHSType;
1072     }
1073 
1074     assert(order < 0 && "illegal float comparison");
1075     if (!IsCompAssign)
1076       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1077     return RHSType;
1078   }
1079 
1080   if (LHSFloat) {
1081     // Half FP has to be promoted to float unless it is natively supported
1082     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1083       LHSType = S.Context.FloatTy;
1084 
1085     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1086                                       /*ConvertFloat=*/!IsCompAssign,
1087                                       /*ConvertInt=*/ true);
1088   }
1089   assert(RHSFloat);
1090   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1091                                     /*convertInt=*/ true,
1092                                     /*convertFloat=*/!IsCompAssign);
1093 }
1094 
1095 /// Diagnose attempts to convert between __float128 and long double if
1096 /// there is no support for such conversion. Helper function of
1097 /// UsualArithmeticConversions().
1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1099                                       QualType RHSType) {
1100   /*  No issue converting if at least one of the types is not a floating point
1101       type or the two types have the same rank.
1102   */
1103   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1104       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1105     return false;
1106 
1107   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1108          "The remaining types must be floating point types.");
1109 
1110   auto *LHSComplex = LHSType->getAs<ComplexType>();
1111   auto *RHSComplex = RHSType->getAs<ComplexType>();
1112 
1113   QualType LHSElemType = LHSComplex ?
1114     LHSComplex->getElementType() : LHSType;
1115   QualType RHSElemType = RHSComplex ?
1116     RHSComplex->getElementType() : RHSType;
1117 
1118   // No issue if the two types have the same representation
1119   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1120       &S.Context.getFloatTypeSemantics(RHSElemType))
1121     return false;
1122 
1123   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1124                                 RHSElemType == S.Context.LongDoubleTy);
1125   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1126                             RHSElemType == S.Context.Float128Ty);
1127 
1128   // We've handled the situation where __float128 and long double have the same
1129   // representation. We allow all conversions for all possible long double types
1130   // except PPC's double double.
1131   return Float128AndLongDouble &&
1132     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1133      &llvm::APFloat::PPCDoubleDouble());
1134 }
1135 
1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1137 
1138 namespace {
1139 /// These helper callbacks are placed in an anonymous namespace to
1140 /// permit their use as function template parameters.
1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1142   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1143 }
1144 
1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1146   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1147                              CK_IntegralComplexCast);
1148 }
1149 }
1150 
1151 /// Handle integer arithmetic conversions.  Helper function of
1152 /// UsualArithmeticConversions()
1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1155                                         ExprResult &RHS, QualType LHSType,
1156                                         QualType RHSType, bool IsCompAssign) {
1157   // The rules for this case are in C99 6.3.1.8
1158   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1159   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1160   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1161   if (LHSSigned == RHSSigned) {
1162     // Same signedness; use the higher-ranked type
1163     if (order >= 0) {
1164       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1165       return LHSType;
1166     } else if (!IsCompAssign)
1167       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1168     return RHSType;
1169   } else if (order != (LHSSigned ? 1 : -1)) {
1170     // The unsigned type has greater than or equal rank to the
1171     // signed type, so use the unsigned type
1172     if (RHSSigned) {
1173       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1174       return LHSType;
1175     } else if (!IsCompAssign)
1176       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1177     return RHSType;
1178   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1179     // The two types are different widths; if we are here, that
1180     // means the signed type is larger than the unsigned type, so
1181     // use the signed type.
1182     if (LHSSigned) {
1183       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1184       return LHSType;
1185     } else if (!IsCompAssign)
1186       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1187     return RHSType;
1188   } else {
1189     // The signed type is higher-ranked than the unsigned type,
1190     // but isn't actually any bigger (like unsigned int and long
1191     // on most 32-bit systems).  Use the unsigned type corresponding
1192     // to the signed type.
1193     QualType result =
1194       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1195     RHS = (*doRHSCast)(S, RHS.get(), result);
1196     if (!IsCompAssign)
1197       LHS = (*doLHSCast)(S, LHS.get(), result);
1198     return result;
1199   }
1200 }
1201 
1202 /// Handle conversions with GCC complex int extension.  Helper function
1203 /// of UsualArithmeticConversions()
1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1205                                            ExprResult &RHS, QualType LHSType,
1206                                            QualType RHSType,
1207                                            bool IsCompAssign) {
1208   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1209   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1210 
1211   if (LHSComplexInt && RHSComplexInt) {
1212     QualType LHSEltType = LHSComplexInt->getElementType();
1213     QualType RHSEltType = RHSComplexInt->getElementType();
1214     QualType ScalarType =
1215       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1216         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1217 
1218     return S.Context.getComplexType(ScalarType);
1219   }
1220 
1221   if (LHSComplexInt) {
1222     QualType LHSEltType = LHSComplexInt->getElementType();
1223     QualType ScalarType =
1224       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1225         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1226     QualType ComplexType = S.Context.getComplexType(ScalarType);
1227     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229 
1230     return ComplexType;
1231   }
1232 
1233   assert(RHSComplexInt);
1234 
1235   QualType RHSEltType = RHSComplexInt->getElementType();
1236   QualType ScalarType =
1237     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1238       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1239   QualType ComplexType = S.Context.getComplexType(ScalarType);
1240 
1241   if (!IsCompAssign)
1242     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1243                               CK_IntegralRealToComplex);
1244   return ComplexType;
1245 }
1246 
1247 /// Return the rank of a given fixed point or integer type. The value itself
1248 /// doesn't matter, but the values must be increasing with proper increasing
1249 /// rank as described in N1169 4.1.1.
1250 static unsigned GetFixedPointRank(QualType Ty) {
1251   const auto *BTy = Ty->getAs<BuiltinType>();
1252   assert(BTy && "Expected a builtin type.");
1253 
1254   switch (BTy->getKind()) {
1255   case BuiltinType::ShortFract:
1256   case BuiltinType::UShortFract:
1257   case BuiltinType::SatShortFract:
1258   case BuiltinType::SatUShortFract:
1259     return 1;
1260   case BuiltinType::Fract:
1261   case BuiltinType::UFract:
1262   case BuiltinType::SatFract:
1263   case BuiltinType::SatUFract:
1264     return 2;
1265   case BuiltinType::LongFract:
1266   case BuiltinType::ULongFract:
1267   case BuiltinType::SatLongFract:
1268   case BuiltinType::SatULongFract:
1269     return 3;
1270   case BuiltinType::ShortAccum:
1271   case BuiltinType::UShortAccum:
1272   case BuiltinType::SatShortAccum:
1273   case BuiltinType::SatUShortAccum:
1274     return 4;
1275   case BuiltinType::Accum:
1276   case BuiltinType::UAccum:
1277   case BuiltinType::SatAccum:
1278   case BuiltinType::SatUAccum:
1279     return 5;
1280   case BuiltinType::LongAccum:
1281   case BuiltinType::ULongAccum:
1282   case BuiltinType::SatLongAccum:
1283   case BuiltinType::SatULongAccum:
1284     return 6;
1285   default:
1286     if (BTy->isInteger())
1287       return 0;
1288     llvm_unreachable("Unexpected fixed point or integer type");
1289   }
1290 }
1291 
1292 /// handleFixedPointConversion - Fixed point operations between fixed
1293 /// point types and integers or other fixed point types do not fall under
1294 /// usual arithmetic conversion since these conversions could result in loss
1295 /// of precsision (N1169 4.1.4). These operations should be calculated with
1296 /// the full precision of their result type (N1169 4.1.6.2.1).
1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1298                                            QualType RHSTy) {
1299   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1300          "Expected at least one of the operands to be a fixed point type");
1301   assert((LHSTy->isFixedPointOrIntegerType() ||
1302           RHSTy->isFixedPointOrIntegerType()) &&
1303          "Special fixed point arithmetic operation conversions are only "
1304          "applied to ints or other fixed point types");
1305 
1306   // If one operand has signed fixed-point type and the other operand has
1307   // unsigned fixed-point type, then the unsigned fixed-point operand is
1308   // converted to its corresponding signed fixed-point type and the resulting
1309   // type is the type of the converted operand.
1310   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1311     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1312   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1313     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1314 
1315   // The result type is the type with the highest rank, whereby a fixed-point
1316   // conversion rank is always greater than an integer conversion rank; if the
1317   // type of either of the operands is a saturating fixedpoint type, the result
1318   // type shall be the saturating fixed-point type corresponding to the type
1319   // with the highest rank; the resulting value is converted (taking into
1320   // account rounding and overflow) to the precision of the resulting type.
1321   // Same ranks between signed and unsigned types are resolved earlier, so both
1322   // types are either signed or both unsigned at this point.
1323   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1324   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1325 
1326   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1327 
1328   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1329     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1330 
1331   return ResultTy;
1332 }
1333 
1334 /// UsualArithmeticConversions - Performs various conversions that are common to
1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1336 /// routine returns the first non-arithmetic type found. The client is
1337 /// responsible for emitting appropriate error diagnostics.
1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1339                                           bool IsCompAssign) {
1340   if (!IsCompAssign) {
1341     LHS = UsualUnaryConversions(LHS.get());
1342     if (LHS.isInvalid())
1343       return QualType();
1344   }
1345 
1346   RHS = UsualUnaryConversions(RHS.get());
1347   if (RHS.isInvalid())
1348     return QualType();
1349 
1350   // For conversion purposes, we ignore any qualifiers.
1351   // For example, "const float" and "float" are equivalent.
1352   QualType LHSType =
1353     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1354   QualType RHSType =
1355     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1356 
1357   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1358   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1359     LHSType = AtomicLHS->getValueType();
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1366   // The caller can deal with this (e.g. pointer + int).
1367   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1368     return QualType();
1369 
1370   // Apply unary and bitfield promotions to the LHS's type.
1371   QualType LHSUnpromotedType = LHSType;
1372   if (LHSType->isPromotableIntegerType())
1373     LHSType = Context.getPromotedIntegerType(LHSType);
1374   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1375   if (!LHSBitfieldPromoteTy.isNull())
1376     LHSType = LHSBitfieldPromoteTy;
1377   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1378     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1379 
1380   // If both types are identical, no conversion is needed.
1381   if (LHSType == RHSType)
1382     return LHSType;
1383 
1384   // At this point, we have two different arithmetic types.
1385 
1386   // Diagnose attempts to convert between __float128 and long double where
1387   // such conversions currently can't be handled.
1388   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1389     return QualType();
1390 
1391   // Handle complex types first (C99 6.3.1.8p1).
1392   if (LHSType->isComplexType() || RHSType->isComplexType())
1393     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                         IsCompAssign);
1395 
1396   // Now handle "real" floating types (i.e. float, double, long double).
1397   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1398     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                  IsCompAssign);
1400 
1401   // Handle GCC complex int extension.
1402   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1403     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                       IsCompAssign);
1405 
1406   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1407     return handleFixedPointConversion(*this, LHSType, RHSType);
1408 
1409   // Finally, we have two differing integer types.
1410   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1411            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //  Semantic Analysis for various Expression Types
1416 //===----------------------------------------------------------------------===//
1417 
1418 
1419 ExprResult
1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1421                                 SourceLocation DefaultLoc,
1422                                 SourceLocation RParenLoc,
1423                                 Expr *ControllingExpr,
1424                                 ArrayRef<ParsedType> ArgTypes,
1425                                 ArrayRef<Expr *> ArgExprs) {
1426   unsigned NumAssocs = ArgTypes.size();
1427   assert(NumAssocs == ArgExprs.size());
1428 
1429   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (ArgTypes[i])
1432       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1433     else
1434       Types[i] = nullptr;
1435   }
1436 
1437   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1438                                              ControllingExpr,
1439                                              llvm::makeArrayRef(Types, NumAssocs),
1440                                              ArgExprs);
1441   delete [] Types;
1442   return ER;
1443 }
1444 
1445 ExprResult
1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1447                                  SourceLocation DefaultLoc,
1448                                  SourceLocation RParenLoc,
1449                                  Expr *ControllingExpr,
1450                                  ArrayRef<TypeSourceInfo *> Types,
1451                                  ArrayRef<Expr *> Exprs) {
1452   unsigned NumAssocs = Types.size();
1453   assert(NumAssocs == Exprs.size());
1454 
1455   // Decay and strip qualifiers for the controlling expression type, and handle
1456   // placeholder type replacement. See committee discussion from WG14 DR423.
1457   {
1458     EnterExpressionEvaluationContext Unevaluated(
1459         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1460     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1461     if (R.isInvalid())
1462       return ExprError();
1463     ControllingExpr = R.get();
1464   }
1465 
1466   // The controlling expression is an unevaluated operand, so side effects are
1467   // likely unintended.
1468   if (!inTemplateInstantiation() &&
1469       ControllingExpr->HasSideEffects(Context, false))
1470     Diag(ControllingExpr->getExprLoc(),
1471          diag::warn_side_effects_unevaluated_context);
1472 
1473   bool TypeErrorFound = false,
1474        IsResultDependent = ControllingExpr->isTypeDependent(),
1475        ContainsUnexpandedParameterPack
1476          = ControllingExpr->containsUnexpandedParameterPack();
1477 
1478   for (unsigned i = 0; i < NumAssocs; ++i) {
1479     if (Exprs[i]->containsUnexpandedParameterPack())
1480       ContainsUnexpandedParameterPack = true;
1481 
1482     if (Types[i]) {
1483       if (Types[i]->getType()->containsUnexpandedParameterPack())
1484         ContainsUnexpandedParameterPack = true;
1485 
1486       if (Types[i]->getType()->isDependentType()) {
1487         IsResultDependent = true;
1488       } else {
1489         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1490         // complete object type other than a variably modified type."
1491         unsigned D = 0;
1492         if (Types[i]->getType()->isIncompleteType())
1493           D = diag::err_assoc_type_incomplete;
1494         else if (!Types[i]->getType()->isObjectType())
1495           D = diag::err_assoc_type_nonobject;
1496         else if (Types[i]->getType()->isVariablyModifiedType())
1497           D = diag::err_assoc_type_variably_modified;
1498 
1499         if (D != 0) {
1500           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1501             << Types[i]->getTypeLoc().getSourceRange()
1502             << Types[i]->getType();
1503           TypeErrorFound = true;
1504         }
1505 
1506         // C11 6.5.1.1p2 "No two generic associations in the same generic
1507         // selection shall specify compatible types."
1508         for (unsigned j = i+1; j < NumAssocs; ++j)
1509           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1510               Context.typesAreCompatible(Types[i]->getType(),
1511                                          Types[j]->getType())) {
1512             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1513                  diag::err_assoc_compatible_types)
1514               << Types[j]->getTypeLoc().getSourceRange()
1515               << Types[j]->getType()
1516               << Types[i]->getType();
1517             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1518                  diag::note_compat_assoc)
1519               << Types[i]->getTypeLoc().getSourceRange()
1520               << Types[i]->getType();
1521             TypeErrorFound = true;
1522           }
1523       }
1524     }
1525   }
1526   if (TypeErrorFound)
1527     return ExprError();
1528 
1529   // If we determined that the generic selection is result-dependent, don't
1530   // try to compute the result expression.
1531   if (IsResultDependent)
1532     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1533                                         Exprs, DefaultLoc, RParenLoc,
1534                                         ContainsUnexpandedParameterPack);
1535 
1536   SmallVector<unsigned, 1> CompatIndices;
1537   unsigned DefaultIndex = -1U;
1538   for (unsigned i = 0; i < NumAssocs; ++i) {
1539     if (!Types[i])
1540       DefaultIndex = i;
1541     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1542                                         Types[i]->getType()))
1543       CompatIndices.push_back(i);
1544   }
1545 
1546   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1547   // type compatible with at most one of the types named in its generic
1548   // association list."
1549   if (CompatIndices.size() > 1) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1554         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1555         << (unsigned)CompatIndices.size();
1556     for (unsigned I : CompatIndices) {
1557       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1558            diag::note_compat_assoc)
1559         << Types[I]->getTypeLoc().getSourceRange()
1560         << Types[I]->getType();
1561     }
1562     return ExprError();
1563   }
1564 
1565   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1566   // its controlling expression shall have type compatible with exactly one of
1567   // the types named in its generic association list."
1568   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1569     // We strip parens here because the controlling expression is typically
1570     // parenthesized in macro definitions.
1571     ControllingExpr = ControllingExpr->IgnoreParens();
1572     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1573         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1574     return ExprError();
1575   }
1576 
1577   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1578   // type name that is compatible with the type of the controlling expression,
1579   // then the result expression of the generic selection is the expression
1580   // in that generic association. Otherwise, the result expression of the
1581   // generic selection is the expression in the default generic association."
1582   unsigned ResultIndex =
1583     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1584 
1585   return GenericSelectionExpr::Create(
1586       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1587       ContainsUnexpandedParameterPack, ResultIndex);
1588 }
1589 
1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1591 /// location of the token and the offset of the ud-suffix within it.
1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1593                                      unsigned Offset) {
1594   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1595                                         S.getLangOpts());
1596 }
1597 
1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1601                                                  IdentifierInfo *UDSuffix,
1602                                                  SourceLocation UDSuffixLoc,
1603                                                  ArrayRef<Expr*> Args,
1604                                                  SourceLocation LitEndLoc) {
1605   assert(Args.size() <= 2 && "too many arguments for literal operator");
1606 
1607   QualType ArgTy[2];
1608   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1609     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1610     if (ArgTy[ArgIdx]->isArrayType())
1611       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1612   }
1613 
1614   DeclarationName OpName =
1615     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1616   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1617   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1618 
1619   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1620   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1621                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1622                               /*AllowStringTemplate*/ false,
1623                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1624     return ExprError();
1625 
1626   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1627 }
1628 
1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1630 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1632 /// multiple tokens.  However, the common case is that StringToks points to one
1633 /// string.
1634 ///
1635 ExprResult
1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1637   assert(!StringToks.empty() && "Must have at least one string!");
1638 
1639   StringLiteralParser Literal(StringToks, PP);
1640   if (Literal.hadError)
1641     return ExprError();
1642 
1643   SmallVector<SourceLocation, 4> StringTokLocs;
1644   for (const Token &Tok : StringToks)
1645     StringTokLocs.push_back(Tok.getLocation());
1646 
1647   QualType CharTy = Context.CharTy;
1648   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1649   if (Literal.isWide()) {
1650     CharTy = Context.getWideCharType();
1651     Kind = StringLiteral::Wide;
1652   } else if (Literal.isUTF8()) {
1653     if (getLangOpts().Char8)
1654       CharTy = Context.Char8Ty;
1655     Kind = StringLiteral::UTF8;
1656   } else if (Literal.isUTF16()) {
1657     CharTy = Context.Char16Ty;
1658     Kind = StringLiteral::UTF16;
1659   } else if (Literal.isUTF32()) {
1660     CharTy = Context.Char32Ty;
1661     Kind = StringLiteral::UTF32;
1662   } else if (Literal.isPascal()) {
1663     CharTy = Context.UnsignedCharTy;
1664   }
1665 
1666   // Warn on initializing an array of char from a u8 string literal; this
1667   // becomes ill-formed in C++2a.
1668   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1669       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1670     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1671 
1672     // Create removals for all 'u8' prefixes in the string literal(s). This
1673     // ensures C++2a compatibility (but may change the program behavior when
1674     // built by non-Clang compilers for which the execution character set is
1675     // not always UTF-8).
1676     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1677     SourceLocation RemovalDiagLoc;
1678     for (const Token &Tok : StringToks) {
1679       if (Tok.getKind() == tok::utf8_string_literal) {
1680         if (RemovalDiagLoc.isInvalid())
1681           RemovalDiagLoc = Tok.getLocation();
1682         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1683             Tok.getLocation(),
1684             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1685                                            getSourceManager(), getLangOpts())));
1686       }
1687     }
1688     Diag(RemovalDiagLoc, RemovalDiag);
1689   }
1690 
1691   QualType StrTy =
1692       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1693 
1694   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1695   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1696                                              Kind, Literal.Pascal, StrTy,
1697                                              &StringTokLocs[0],
1698                                              StringTokLocs.size());
1699   if (Literal.getUDSuffix().empty())
1700     return Lit;
1701 
1702   // We're building a user-defined literal.
1703   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1704   SourceLocation UDSuffixLoc =
1705     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1706                    Literal.getUDSuffixOffset());
1707 
1708   // Make sure we're allowed user-defined literals here.
1709   if (!UDLScope)
1710     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1711 
1712   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1713   //   operator "" X (str, len)
1714   QualType SizeType = Context.getSizeType();
1715 
1716   DeclarationName OpName =
1717     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1718   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1719   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1720 
1721   QualType ArgTy[] = {
1722     Context.getArrayDecayedType(StrTy), SizeType
1723   };
1724 
1725   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1726   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1727                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                                 /*AllowStringTemplate*/ true,
1729                                 /*DiagnoseMissing*/ true)) {
1730 
1731   case LOLR_Cooked: {
1732     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1733     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1734                                                     StringTokLocs[0]);
1735     Expr *Args[] = { Lit, LenArg };
1736 
1737     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1738   }
1739 
1740   case LOLR_StringTemplate: {
1741     TemplateArgumentListInfo ExplicitArgs;
1742 
1743     unsigned CharBits = Context.getIntWidth(CharTy);
1744     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1745     llvm::APSInt Value(CharBits, CharIsUnsigned);
1746 
1747     TemplateArgument TypeArg(CharTy);
1748     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1749     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1750 
1751     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1752       Value = Lit->getCodeUnit(I);
1753       TemplateArgument Arg(Context, Value, CharTy);
1754       TemplateArgumentLocInfo ArgInfo;
1755       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1756     }
1757     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1758                                     &ExplicitArgs);
1759   }
1760   case LOLR_Raw:
1761   case LOLR_Template:
1762   case LOLR_ErrorNoDiagnostic:
1763     llvm_unreachable("unexpected literal operator lookup result");
1764   case LOLR_Error:
1765     return ExprError();
1766   }
1767   llvm_unreachable("unexpected literal operator lookup result");
1768 }
1769 
1770 DeclRefExpr *
1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1772                        SourceLocation Loc,
1773                        const CXXScopeSpec *SS) {
1774   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1775   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1776 }
1777 
1778 DeclRefExpr *
1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1780                        const DeclarationNameInfo &NameInfo,
1781                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1782                        SourceLocation TemplateKWLoc,
1783                        const TemplateArgumentListInfo *TemplateArgs) {
1784   NestedNameSpecifierLoc NNS =
1785       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1786   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1787                           TemplateArgs);
1788 }
1789 
1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1791   // A declaration named in an unevaluated operand never constitutes an odr-use.
1792   if (isUnevaluatedContext())
1793     return NOUR_Unevaluated;
1794 
1795   // C++2a [basic.def.odr]p4:
1796   //   A variable x whose name appears as a potentially-evaluated expression e
1797   //   is odr-used by e unless [...] x is a reference that is usable in
1798   //   constant expressions.
1799   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     if (VD->getType()->isReferenceType() &&
1801         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1802         VD->isUsableInConstantExpressions(Context))
1803       return NOUR_Constant;
1804   }
1805 
1806   // All remaining non-variable cases constitute an odr-use. For variables, we
1807   // need to wait and see how the expression is used.
1808   return NOUR_None;
1809 }
1810 
1811 /// BuildDeclRefExpr - Build an expression that references a
1812 /// declaration that does not require a closure capture.
1813 DeclRefExpr *
1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1815                        const DeclarationNameInfo &NameInfo,
1816                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1817                        SourceLocation TemplateKWLoc,
1818                        const TemplateArgumentListInfo *TemplateArgs) {
1819   bool RefersToCapturedVariable =
1820       isa<VarDecl>(D) &&
1821       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1822 
1823   DeclRefExpr *E = DeclRefExpr::Create(
1824       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1825       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1826   MarkDeclRefReferenced(E);
1827 
1828   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1829       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1830       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1831     getCurFunction()->recordUseOfWeak(E);
1832 
1833   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1834   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1835     FD = IFD->getAnonField();
1836   if (FD) {
1837     UnusedPrivateFields.remove(FD);
1838     // Just in case we're building an illegal pointer-to-member.
1839     if (FD->isBitField())
1840       E->setObjectKind(OK_BitField);
1841   }
1842 
1843   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1844   // designates a bit-field.
1845   if (auto *BD = dyn_cast<BindingDecl>(D))
1846     if (auto *BE = BD->getBinding())
1847       E->setObjectKind(BE->getObjectKind());
1848 
1849   return E;
1850 }
1851 
1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1853 /// possibly a list of template arguments.
1854 ///
1855 /// If this produces template arguments, it is permitted to call
1856 /// DecomposeTemplateName.
1857 ///
1858 /// This actually loses a lot of source location information for
1859 /// non-standard name kinds; we should consider preserving that in
1860 /// some way.
1861 void
1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1863                              TemplateArgumentListInfo &Buffer,
1864                              DeclarationNameInfo &NameInfo,
1865                              const TemplateArgumentListInfo *&TemplateArgs) {
1866   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1867     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1868     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1869 
1870     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1871                                        Id.TemplateId->NumArgs);
1872     translateTemplateArguments(TemplateArgsPtr, Buffer);
1873 
1874     TemplateName TName = Id.TemplateId->Template.get();
1875     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1876     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1877     TemplateArgs = &Buffer;
1878   } else {
1879     NameInfo = GetNameFromUnqualifiedId(Id);
1880     TemplateArgs = nullptr;
1881   }
1882 }
1883 
1884 static void emitEmptyLookupTypoDiagnostic(
1885     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1886     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1887     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1888   DeclContext *Ctx =
1889       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1890   if (!TC) {
1891     // Emit a special diagnostic for failed member lookups.
1892     // FIXME: computing the declaration context might fail here (?)
1893     if (Ctx)
1894       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1895                                                  << SS.getRange();
1896     else
1897       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1898     return;
1899   }
1900 
1901   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1902   bool DroppedSpecifier =
1903       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1904   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1905                         ? diag::note_implicit_param_decl
1906                         : diag::note_previous_decl;
1907   if (!Ctx)
1908     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1909                          SemaRef.PDiag(NoteID));
1910   else
1911     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1912                                  << Typo << Ctx << DroppedSpecifier
1913                                  << SS.getRange(),
1914                          SemaRef.PDiag(NoteID));
1915 }
1916 
1917 /// Diagnose an empty lookup.
1918 ///
1919 /// \return false if new lookup candidates were found
1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                                CorrectionCandidateCallback &CCC,
1922                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     DC = DC->getLookupParent();
1994   }
1995 
1996   // We didn't find anything, so try to correct for a typo.
1997   TypoCorrection Corrected;
1998   if (S && Out) {
1999     SourceLocation TypoLoc = R.getNameLoc();
2000     assert(!ExplicitTemplateArgs &&
2001            "Diagnosing an empty lookup with explicit template args!");
2002     *Out = CorrectTypoDelayed(
2003         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2004         [=](const TypoCorrection &TC) {
2005           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2006                                         diagnostic, diagnostic_suggest);
2007         },
2008         nullptr, CTK_ErrorRecovery);
2009     if (*Out)
2010       return true;
2011   } else if (S &&
2012              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2013                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2014     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2015     bool DroppedSpecifier =
2016         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2017     R.setLookupName(Corrected.getCorrection());
2018 
2019     bool AcceptableWithRecovery = false;
2020     bool AcceptableWithoutRecovery = false;
2021     NamedDecl *ND = Corrected.getFoundDecl();
2022     if (ND) {
2023       if (Corrected.isOverloaded()) {
2024         OverloadCandidateSet OCS(R.getNameLoc(),
2025                                  OverloadCandidateSet::CSK_Normal);
2026         OverloadCandidateSet::iterator Best;
2027         for (NamedDecl *CD : Corrected) {
2028           if (FunctionTemplateDecl *FTD =
2029                    dyn_cast<FunctionTemplateDecl>(CD))
2030             AddTemplateOverloadCandidate(
2031                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2032                 Args, OCS);
2033           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2034             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2035               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2036                                    Args, OCS);
2037         }
2038         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2039         case OR_Success:
2040           ND = Best->FoundDecl;
2041           Corrected.setCorrectionDecl(ND);
2042           break;
2043         default:
2044           // FIXME: Arbitrarily pick the first declaration for the note.
2045           Corrected.setCorrectionDecl(ND);
2046           break;
2047         }
2048       }
2049       R.addDecl(ND);
2050       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2051         CXXRecordDecl *Record = nullptr;
2052         if (Corrected.getCorrectionSpecifier()) {
2053           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2054           Record = Ty->getAsCXXRecordDecl();
2055         }
2056         if (!Record)
2057           Record = cast<CXXRecordDecl>(
2058               ND->getDeclContext()->getRedeclContext());
2059         R.setNamingClass(Record);
2060       }
2061 
2062       auto *UnderlyingND = ND->getUnderlyingDecl();
2063       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2064                                isa<FunctionTemplateDecl>(UnderlyingND);
2065       // FIXME: If we ended up with a typo for a type name or
2066       // Objective-C class name, we're in trouble because the parser
2067       // is in the wrong place to recover. Suggest the typo
2068       // correction, but don't make it a fix-it since we're not going
2069       // to recover well anyway.
2070       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2071                                   getAsTypeTemplateDecl(UnderlyingND) ||
2072                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2073     } else {
2074       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2075       // because we aren't able to recover.
2076       AcceptableWithoutRecovery = true;
2077     }
2078 
2079     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2080       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2081                             ? diag::note_implicit_param_decl
2082                             : diag::note_previous_decl;
2083       if (SS.isEmpty())
2084         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2085                      PDiag(NoteID), AcceptableWithRecovery);
2086       else
2087         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2088                                   << Name << computeDeclContext(SS, false)
2089                                   << DroppedSpecifier << SS.getRange(),
2090                      PDiag(NoteID), AcceptableWithRecovery);
2091 
2092       // Tell the callee whether to try to recover.
2093       return !AcceptableWithRecovery;
2094     }
2095   }
2096   R.clear();
2097 
2098   // Emit a special diagnostic for failed member lookups.
2099   // FIXME: computing the declaration context might fail here (?)
2100   if (!SS.isEmpty()) {
2101     Diag(R.getNameLoc(), diag::err_no_member)
2102       << Name << computeDeclContext(SS, false)
2103       << SS.getRange();
2104     return true;
2105   }
2106 
2107   // Give up, we can't recover.
2108   Diag(R.getNameLoc(), diagnostic) << Name;
2109   return true;
2110 }
2111 
2112 /// In Microsoft mode, if we are inside a template class whose parent class has
2113 /// dependent base classes, and we can't resolve an unqualified identifier, then
2114 /// assume the identifier is a member of a dependent base class.  We can only
2115 /// recover successfully in static methods, instance methods, and other contexts
2116 /// where 'this' is available.  This doesn't precisely match MSVC's
2117 /// instantiation model, but it's close enough.
2118 static Expr *
2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2120                                DeclarationNameInfo &NameInfo,
2121                                SourceLocation TemplateKWLoc,
2122                                const TemplateArgumentListInfo *TemplateArgs) {
2123   // Only try to recover from lookup into dependent bases in static methods or
2124   // contexts where 'this' is available.
2125   QualType ThisType = S.getCurrentThisType();
2126   const CXXRecordDecl *RD = nullptr;
2127   if (!ThisType.isNull())
2128     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2129   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2130     RD = MD->getParent();
2131   if (!RD || !RD->hasAnyDependentBases())
2132     return nullptr;
2133 
2134   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2135   // is available, suggest inserting 'this->' as a fixit.
2136   SourceLocation Loc = NameInfo.getLoc();
2137   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2138   DB << NameInfo.getName() << RD;
2139 
2140   if (!ThisType.isNull()) {
2141     DB << FixItHint::CreateInsertion(Loc, "this->");
2142     return CXXDependentScopeMemberExpr::Create(
2143         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2144         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2145         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2146   }
2147 
2148   // Synthesize a fake NNS that points to the derived class.  This will
2149   // perform name lookup during template instantiation.
2150   CXXScopeSpec SS;
2151   auto *NNS =
2152       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2153   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2154   return DependentScopeDeclRefExpr::Create(
2155       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2156       TemplateArgs);
2157 }
2158 
2159 ExprResult
2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2161                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2162                         bool HasTrailingLParen, bool IsAddressOfOperand,
2163                         CorrectionCandidateCallback *CCC,
2164                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2165   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2166          "cannot be direct & operand and have a trailing lparen");
2167   if (SS.isInvalid())
2168     return ExprError();
2169 
2170   TemplateArgumentListInfo TemplateArgsBuffer;
2171 
2172   // Decompose the UnqualifiedId into the following data.
2173   DeclarationNameInfo NameInfo;
2174   const TemplateArgumentListInfo *TemplateArgs;
2175   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2176 
2177   DeclarationName Name = NameInfo.getName();
2178   IdentifierInfo *II = Name.getAsIdentifierInfo();
2179   SourceLocation NameLoc = NameInfo.getLoc();
2180 
2181   if (II && II->isEditorPlaceholder()) {
2182     // FIXME: When typed placeholders are supported we can create a typed
2183     // placeholder expression node.
2184     return ExprError();
2185   }
2186 
2187   // C++ [temp.dep.expr]p3:
2188   //   An id-expression is type-dependent if it contains:
2189   //     -- an identifier that was declared with a dependent type,
2190   //        (note: handled after lookup)
2191   //     -- a template-id that is dependent,
2192   //        (note: handled in BuildTemplateIdExpr)
2193   //     -- a conversion-function-id that specifies a dependent type,
2194   //     -- a nested-name-specifier that contains a class-name that
2195   //        names a dependent type.
2196   // Determine whether this is a member of an unknown specialization;
2197   // we need to handle these differently.
2198   bool DependentID = false;
2199   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2200       Name.getCXXNameType()->isDependentType()) {
2201     DependentID = true;
2202   } else if (SS.isSet()) {
2203     if (DeclContext *DC = computeDeclContext(SS, false)) {
2204       if (RequireCompleteDeclContext(SS, DC))
2205         return ExprError();
2206     } else {
2207       DependentID = true;
2208     }
2209   }
2210 
2211   if (DependentID)
2212     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2213                                       IsAddressOfOperand, TemplateArgs);
2214 
2215   // Perform the required lookup.
2216   LookupResult R(*this, NameInfo,
2217                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2218                      ? LookupObjCImplicitSelfParam
2219                      : LookupOrdinaryName);
2220   if (TemplateKWLoc.isValid() || TemplateArgs) {
2221     // Lookup the template name again to correctly establish the context in
2222     // which it was found. This is really unfortunate as we already did the
2223     // lookup to determine that it was a template name in the first place. If
2224     // this becomes a performance hit, we can work harder to preserve those
2225     // results until we get here but it's likely not worth it.
2226     bool MemberOfUnknownSpecialization;
2227     AssumedTemplateKind AssumedTemplate;
2228     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2229                            MemberOfUnknownSpecialization, TemplateKWLoc,
2230                            &AssumedTemplate))
2231       return ExprError();
2232 
2233     if (MemberOfUnknownSpecialization ||
2234         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2235       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2236                                         IsAddressOfOperand, TemplateArgs);
2237   } else {
2238     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2239     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2240 
2241     // If the result might be in a dependent base class, this is a dependent
2242     // id-expression.
2243     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246 
2247     // If this reference is in an Objective-C method, then we need to do
2248     // some special Objective-C lookup, too.
2249     if (IvarLookupFollowUp) {
2250       ExprResult E(LookupInObjCMethod(R, S, II, true));
2251       if (E.isInvalid())
2252         return ExprError();
2253 
2254       if (Expr *Ex = E.getAs<Expr>())
2255         return Ex;
2256     }
2257   }
2258 
2259   if (R.isAmbiguous())
2260     return ExprError();
2261 
2262   // This could be an implicitly declared function reference (legal in C90,
2263   // extension in C99, forbidden in C++).
2264   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2265     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2266     if (D) R.addDecl(D);
2267   }
2268 
2269   // Determine whether this name might be a candidate for
2270   // argument-dependent lookup.
2271   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2272 
2273   if (R.empty() && !ADL) {
2274     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2275       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2276                                                    TemplateKWLoc, TemplateArgs))
2277         return E;
2278     }
2279 
2280     // Don't diagnose an empty lookup for inline assembly.
2281     if (IsInlineAsmIdentifier)
2282       return ExprError();
2283 
2284     // If this name wasn't predeclared and if this is not a function
2285     // call, diagnose the problem.
2286     TypoExpr *TE = nullptr;
2287     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2288                                                        : nullptr);
2289     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2290     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2291            "Typo correction callback misconfigured");
2292     if (CCC) {
2293       // Make sure the callback knows what the typo being diagnosed is.
2294       CCC->setTypoName(II);
2295       if (SS.isValid())
2296         CCC->setTypoNNS(SS.getScopeRep());
2297     }
2298     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2299     // a template name, but we happen to have always already looked up the name
2300     // before we get here if it must be a template name.
2301     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2302                             None, &TE)) {
2303       if (TE && KeywordReplacement) {
2304         auto &State = getTypoExprState(TE);
2305         auto BestTC = State.Consumer->getNextCorrection();
2306         if (BestTC.isKeyword()) {
2307           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2308           if (State.DiagHandler)
2309             State.DiagHandler(BestTC);
2310           KeywordReplacement->startToken();
2311           KeywordReplacement->setKind(II->getTokenID());
2312           KeywordReplacement->setIdentifierInfo(II);
2313           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2314           // Clean up the state associated with the TypoExpr, since it has
2315           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2316           clearDelayedTypo(TE);
2317           // Signal that a correction to a keyword was performed by returning a
2318           // valid-but-null ExprResult.
2319           return (Expr*)nullptr;
2320         }
2321         State.Consumer->resetCorrectionStream();
2322       }
2323       return TE ? TE : ExprError();
2324     }
2325 
2326     assert(!R.empty() &&
2327            "DiagnoseEmptyLookup returned false but added no results");
2328 
2329     // If we found an Objective-C instance variable, let
2330     // LookupInObjCMethod build the appropriate expression to
2331     // reference the ivar.
2332     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2333       R.clear();
2334       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2335       // In a hopelessly buggy code, Objective-C instance variable
2336       // lookup fails and no expression will be built to reference it.
2337       if (!E.isInvalid() && !E.get())
2338         return ExprError();
2339       return E;
2340     }
2341   }
2342 
2343   // This is guaranteed from this point on.
2344   assert(!R.empty() || ADL);
2345 
2346   // Check whether this might be a C++ implicit instance member access.
2347   // C++ [class.mfct.non-static]p3:
2348   //   When an id-expression that is not part of a class member access
2349   //   syntax and not used to form a pointer to member is used in the
2350   //   body of a non-static member function of class X, if name lookup
2351   //   resolves the name in the id-expression to a non-static non-type
2352   //   member of some class C, the id-expression is transformed into a
2353   //   class member access expression using (*this) as the
2354   //   postfix-expression to the left of the . operator.
2355   //
2356   // But we don't actually need to do this for '&' operands if R
2357   // resolved to a function or overloaded function set, because the
2358   // expression is ill-formed if it actually works out to be a
2359   // non-static member function:
2360   //
2361   // C++ [expr.ref]p4:
2362   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2363   //   [t]he expression can be used only as the left-hand operand of a
2364   //   member function call.
2365   //
2366   // There are other safeguards against such uses, but it's important
2367   // to get this right here so that we don't end up making a
2368   // spuriously dependent expression if we're inside a dependent
2369   // instance method.
2370   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2371     bool MightBeImplicitMember;
2372     if (!IsAddressOfOperand)
2373       MightBeImplicitMember = true;
2374     else if (!SS.isEmpty())
2375       MightBeImplicitMember = false;
2376     else if (R.isOverloadedResult())
2377       MightBeImplicitMember = false;
2378     else if (R.isUnresolvableResult())
2379       MightBeImplicitMember = true;
2380     else
2381       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2382                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2383                               isa<MSPropertyDecl>(R.getFoundDecl());
2384 
2385     if (MightBeImplicitMember)
2386       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2387                                              R, TemplateArgs, S);
2388   }
2389 
2390   if (TemplateArgs || TemplateKWLoc.isValid()) {
2391 
2392     // In C++1y, if this is a variable template id, then check it
2393     // in BuildTemplateIdExpr().
2394     // The single lookup result must be a variable template declaration.
2395     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2396         Id.TemplateId->Kind == TNK_Var_template) {
2397       assert(R.getAsSingle<VarTemplateDecl>() &&
2398              "There should only be one declaration found.");
2399     }
2400 
2401     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2402   }
2403 
2404   return BuildDeclarationNameExpr(SS, R, ADL);
2405 }
2406 
2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2408 /// declaration name, generally during template instantiation.
2409 /// There's a large number of things which don't need to be done along
2410 /// this path.
2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2412     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2413     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2414   DeclContext *DC = computeDeclContext(SS, false);
2415   if (!DC)
2416     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2417                                      NameInfo, /*TemplateArgs=*/nullptr);
2418 
2419   if (RequireCompleteDeclContext(SS, DC))
2420     return ExprError();
2421 
2422   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2423   LookupQualifiedName(R, DC);
2424 
2425   if (R.isAmbiguous())
2426     return ExprError();
2427 
2428   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2429     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2430                                      NameInfo, /*TemplateArgs=*/nullptr);
2431 
2432   if (R.empty()) {
2433     Diag(NameInfo.getLoc(), diag::err_no_member)
2434       << NameInfo.getName() << DC << SS.getRange();
2435     return ExprError();
2436   }
2437 
2438   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2439     // Diagnose a missing typename if this resolved unambiguously to a type in
2440     // a dependent context.  If we can recover with a type, downgrade this to
2441     // a warning in Microsoft compatibility mode.
2442     unsigned DiagID = diag::err_typename_missing;
2443     if (RecoveryTSI && getLangOpts().MSVCCompat)
2444       DiagID = diag::ext_typename_missing;
2445     SourceLocation Loc = SS.getBeginLoc();
2446     auto D = Diag(Loc, DiagID);
2447     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2448       << SourceRange(Loc, NameInfo.getEndLoc());
2449 
2450     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2451     // context.
2452     if (!RecoveryTSI)
2453       return ExprError();
2454 
2455     // Only issue the fixit if we're prepared to recover.
2456     D << FixItHint::CreateInsertion(Loc, "typename ");
2457 
2458     // Recover by pretending this was an elaborated type.
2459     QualType Ty = Context.getTypeDeclType(TD);
2460     TypeLocBuilder TLB;
2461     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2462 
2463     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2464     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2465     QTL.setElaboratedKeywordLoc(SourceLocation());
2466     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2467 
2468     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2469 
2470     return ExprEmpty();
2471   }
2472 
2473   // Defend against this resolving to an implicit member access. We usually
2474   // won't get here if this might be a legitimate a class member (we end up in
2475   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2476   // a pointer-to-member or in an unevaluated context in C++11.
2477   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2478     return BuildPossibleImplicitMemberExpr(SS,
2479                                            /*TemplateKWLoc=*/SourceLocation(),
2480                                            R, /*TemplateArgs=*/nullptr, S);
2481 
2482   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2483 }
2484 
2485 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2486 /// detected that we're currently inside an ObjC method.  Perform some
2487 /// additional lookup.
2488 ///
2489 /// Ideally, most of this would be done by lookup, but there's
2490 /// actually quite a lot of extra work involved.
2491 ///
2492 /// Returns a null sentinel to indicate trivial success.
2493 ExprResult
2494 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2495                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2496   SourceLocation Loc = Lookup.getNameLoc();
2497   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2498 
2499   // Check for error condition which is already reported.
2500   if (!CurMethod)
2501     return ExprError();
2502 
2503   // There are two cases to handle here.  1) scoped lookup could have failed,
2504   // in which case we should look for an ivar.  2) scoped lookup could have
2505   // found a decl, but that decl is outside the current instance method (i.e.
2506   // a global variable).  In these two cases, we do a lookup for an ivar with
2507   // this name, if the lookup sucedes, we replace it our current decl.
2508 
2509   // If we're in a class method, we don't normally want to look for
2510   // ivars.  But if we don't find anything else, and there's an
2511   // ivar, that's an error.
2512   bool IsClassMethod = CurMethod->isClassMethod();
2513 
2514   bool LookForIvars;
2515   if (Lookup.empty())
2516     LookForIvars = true;
2517   else if (IsClassMethod)
2518     LookForIvars = false;
2519   else
2520     LookForIvars = (Lookup.isSingleResult() &&
2521                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2522   ObjCInterfaceDecl *IFace = nullptr;
2523   if (LookForIvars) {
2524     IFace = CurMethod->getClassInterface();
2525     ObjCInterfaceDecl *ClassDeclared;
2526     ObjCIvarDecl *IV = nullptr;
2527     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2528       // Diagnose using an ivar in a class method.
2529       if (IsClassMethod)
2530         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2531                          << IV->getDeclName());
2532 
2533       // If we're referencing an invalid decl, just return this as a silent
2534       // error node.  The error diagnostic was already emitted on the decl.
2535       if (IV->isInvalidDecl())
2536         return ExprError();
2537 
2538       // Check if referencing a field with __attribute__((deprecated)).
2539       if (DiagnoseUseOfDecl(IV, Loc))
2540         return ExprError();
2541 
2542       // Diagnose the use of an ivar outside of the declaring class.
2543       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2544           !declaresSameEntity(ClassDeclared, IFace) &&
2545           !getLangOpts().DebuggerSupport)
2546         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2547 
2548       // FIXME: This should use a new expr for a direct reference, don't
2549       // turn this into Self->ivar, just return a BareIVarExpr or something.
2550       IdentifierInfo &II = Context.Idents.get("self");
2551       UnqualifiedId SelfName;
2552       SelfName.setIdentifier(&II, SourceLocation());
2553       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2554       CXXScopeSpec SelfScopeSpec;
2555       SourceLocation TemplateKWLoc;
2556       ExprResult SelfExpr =
2557           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2558                             /*HasTrailingLParen=*/false,
2559                             /*IsAddressOfOperand=*/false);
2560       if (SelfExpr.isInvalid())
2561         return ExprError();
2562 
2563       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2564       if (SelfExpr.isInvalid())
2565         return ExprError();
2566 
2567       MarkAnyDeclReferenced(Loc, IV, true);
2568 
2569       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2570       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2571           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2572         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2573 
2574       ObjCIvarRefExpr *Result = new (Context)
2575           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2576                           IV->getLocation(), SelfExpr.get(), true, true);
2577 
2578       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2579         if (!isUnevaluatedContext() &&
2580             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2581           getCurFunction()->recordUseOfWeak(Result);
2582       }
2583       if (getLangOpts().ObjCAutoRefCount)
2584         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2585           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2586 
2587       return Result;
2588     }
2589   } else if (CurMethod->isInstanceMethod()) {
2590     // We should warn if a local variable hides an ivar.
2591     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2592       ObjCInterfaceDecl *ClassDeclared;
2593       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2594         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2595             declaresSameEntity(IFace, ClassDeclared))
2596           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2597       }
2598     }
2599   } else if (Lookup.isSingleResult() &&
2600              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2601     // If accessing a stand-alone ivar in a class method, this is an error.
2602     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2603       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2604                        << IV->getDeclName());
2605   }
2606 
2607   if (Lookup.empty() && II && AllowBuiltinCreation) {
2608     // FIXME. Consolidate this with similar code in LookupName.
2609     if (unsigned BuiltinID = II->getBuiltinID()) {
2610       if (!(getLangOpts().CPlusPlus &&
2611             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2612         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2613                                            S, Lookup.isForRedeclaration(),
2614                                            Lookup.getNameLoc());
2615         if (D) Lookup.addDecl(D);
2616       }
2617     }
2618   }
2619   // Sentinel value saying that we didn't do anything special.
2620   return ExprResult((Expr *)nullptr);
2621 }
2622 
2623 /// Cast a base object to a member's actual type.
2624 ///
2625 /// Logically this happens in three phases:
2626 ///
2627 /// * First we cast from the base type to the naming class.
2628 ///   The naming class is the class into which we were looking
2629 ///   when we found the member;  it's the qualifier type if a
2630 ///   qualifier was provided, and otherwise it's the base type.
2631 ///
2632 /// * Next we cast from the naming class to the declaring class.
2633 ///   If the member we found was brought into a class's scope by
2634 ///   a using declaration, this is that class;  otherwise it's
2635 ///   the class declaring the member.
2636 ///
2637 /// * Finally we cast from the declaring class to the "true"
2638 ///   declaring class of the member.  This conversion does not
2639 ///   obey access control.
2640 ExprResult
2641 Sema::PerformObjectMemberConversion(Expr *From,
2642                                     NestedNameSpecifier *Qualifier,
2643                                     NamedDecl *FoundDecl,
2644                                     NamedDecl *Member) {
2645   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2646   if (!RD)
2647     return From;
2648 
2649   QualType DestRecordType;
2650   QualType DestType;
2651   QualType FromRecordType;
2652   QualType FromType = From->getType();
2653   bool PointerConversions = false;
2654   if (isa<FieldDecl>(Member)) {
2655     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2656     auto FromPtrType = FromType->getAs<PointerType>();
2657     DestRecordType = Context.getAddrSpaceQualType(
2658         DestRecordType, FromPtrType
2659                             ? FromType->getPointeeType().getAddressSpace()
2660                             : FromType.getAddressSpace());
2661 
2662     if (FromPtrType) {
2663       DestType = Context.getPointerType(DestRecordType);
2664       FromRecordType = FromPtrType->getPointeeType();
2665       PointerConversions = true;
2666     } else {
2667       DestType = DestRecordType;
2668       FromRecordType = FromType;
2669     }
2670   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2671     if (Method->isStatic())
2672       return From;
2673 
2674     DestType = Method->getThisType();
2675     DestRecordType = DestType->getPointeeType();
2676 
2677     if (FromType->getAs<PointerType>()) {
2678       FromRecordType = FromType->getPointeeType();
2679       PointerConversions = true;
2680     } else {
2681       FromRecordType = FromType;
2682       DestType = DestRecordType;
2683     }
2684   } else {
2685     // No conversion necessary.
2686     return From;
2687   }
2688 
2689   if (DestType->isDependentType() || FromType->isDependentType())
2690     return From;
2691 
2692   // If the unqualified types are the same, no conversion is necessary.
2693   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2694     return From;
2695 
2696   SourceRange FromRange = From->getSourceRange();
2697   SourceLocation FromLoc = FromRange.getBegin();
2698 
2699   ExprValueKind VK = From->getValueKind();
2700 
2701   // C++ [class.member.lookup]p8:
2702   //   [...] Ambiguities can often be resolved by qualifying a name with its
2703   //   class name.
2704   //
2705   // If the member was a qualified name and the qualified referred to a
2706   // specific base subobject type, we'll cast to that intermediate type
2707   // first and then to the object in which the member is declared. That allows
2708   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2709   //
2710   //   class Base { public: int x; };
2711   //   class Derived1 : public Base { };
2712   //   class Derived2 : public Base { };
2713   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2714   //
2715   //   void VeryDerived::f() {
2716   //     x = 17; // error: ambiguous base subobjects
2717   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2718   //   }
2719   if (Qualifier && Qualifier->getAsType()) {
2720     QualType QType = QualType(Qualifier->getAsType(), 0);
2721     assert(QType->isRecordType() && "lookup done with non-record type");
2722 
2723     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2724 
2725     // In C++98, the qualifier type doesn't actually have to be a base
2726     // type of the object type, in which case we just ignore it.
2727     // Otherwise build the appropriate casts.
2728     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2729       CXXCastPath BasePath;
2730       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2731                                        FromLoc, FromRange, &BasePath))
2732         return ExprError();
2733 
2734       if (PointerConversions)
2735         QType = Context.getPointerType(QType);
2736       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2737                                VK, &BasePath).get();
2738 
2739       FromType = QType;
2740       FromRecordType = QRecordType;
2741 
2742       // If the qualifier type was the same as the destination type,
2743       // we're done.
2744       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2745         return From;
2746     }
2747   }
2748 
2749   bool IgnoreAccess = false;
2750 
2751   // If we actually found the member through a using declaration, cast
2752   // down to the using declaration's type.
2753   //
2754   // Pointer equality is fine here because only one declaration of a
2755   // class ever has member declarations.
2756   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2757     assert(isa<UsingShadowDecl>(FoundDecl));
2758     QualType URecordType = Context.getTypeDeclType(
2759                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2760 
2761     // We only need to do this if the naming-class to declaring-class
2762     // conversion is non-trivial.
2763     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2764       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2765       CXXCastPath BasePath;
2766       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2767                                        FromLoc, FromRange, &BasePath))
2768         return ExprError();
2769 
2770       QualType UType = URecordType;
2771       if (PointerConversions)
2772         UType = Context.getPointerType(UType);
2773       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2774                                VK, &BasePath).get();
2775       FromType = UType;
2776       FromRecordType = URecordType;
2777     }
2778 
2779     // We don't do access control for the conversion from the
2780     // declaring class to the true declaring class.
2781     IgnoreAccess = true;
2782   }
2783 
2784   CXXCastPath BasePath;
2785   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2786                                    FromLoc, FromRange, &BasePath,
2787                                    IgnoreAccess))
2788     return ExprError();
2789 
2790   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2791                            VK, &BasePath);
2792 }
2793 
2794 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2795                                       const LookupResult &R,
2796                                       bool HasTrailingLParen) {
2797   // Only when used directly as the postfix-expression of a call.
2798   if (!HasTrailingLParen)
2799     return false;
2800 
2801   // Never if a scope specifier was provided.
2802   if (SS.isSet())
2803     return false;
2804 
2805   // Only in C++ or ObjC++.
2806   if (!getLangOpts().CPlusPlus)
2807     return false;
2808 
2809   // Turn off ADL when we find certain kinds of declarations during
2810   // normal lookup:
2811   for (NamedDecl *D : R) {
2812     // C++0x [basic.lookup.argdep]p3:
2813     //     -- a declaration of a class member
2814     // Since using decls preserve this property, we check this on the
2815     // original decl.
2816     if (D->isCXXClassMember())
2817       return false;
2818 
2819     // C++0x [basic.lookup.argdep]p3:
2820     //     -- a block-scope function declaration that is not a
2821     //        using-declaration
2822     // NOTE: we also trigger this for function templates (in fact, we
2823     // don't check the decl type at all, since all other decl types
2824     // turn off ADL anyway).
2825     if (isa<UsingShadowDecl>(D))
2826       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2827     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2828       return false;
2829 
2830     // C++0x [basic.lookup.argdep]p3:
2831     //     -- a declaration that is neither a function or a function
2832     //        template
2833     // And also for builtin functions.
2834     if (isa<FunctionDecl>(D)) {
2835       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2836 
2837       // But also builtin functions.
2838       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2839         return false;
2840     } else if (!isa<FunctionTemplateDecl>(D))
2841       return false;
2842   }
2843 
2844   return true;
2845 }
2846 
2847 
2848 /// Diagnoses obvious problems with the use of the given declaration
2849 /// as an expression.  This is only actually called for lookups that
2850 /// were not overloaded, and it doesn't promise that the declaration
2851 /// will in fact be used.
2852 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2853   if (D->isInvalidDecl())
2854     return true;
2855 
2856   if (isa<TypedefNameDecl>(D)) {
2857     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2858     return true;
2859   }
2860 
2861   if (isa<ObjCInterfaceDecl>(D)) {
2862     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2863     return true;
2864   }
2865 
2866   if (isa<NamespaceDecl>(D)) {
2867     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2868     return true;
2869   }
2870 
2871   return false;
2872 }
2873 
2874 // Certain multiversion types should be treated as overloaded even when there is
2875 // only one result.
2876 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2877   assert(R.isSingleResult() && "Expected only a single result");
2878   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2879   return FD &&
2880          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2881 }
2882 
2883 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2884                                           LookupResult &R, bool NeedsADL,
2885                                           bool AcceptInvalidDecl) {
2886   // If this is a single, fully-resolved result and we don't need ADL,
2887   // just build an ordinary singleton decl ref.
2888   if (!NeedsADL && R.isSingleResult() &&
2889       !R.getAsSingle<FunctionTemplateDecl>() &&
2890       !ShouldLookupResultBeMultiVersionOverload(R))
2891     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2892                                     R.getRepresentativeDecl(), nullptr,
2893                                     AcceptInvalidDecl);
2894 
2895   // We only need to check the declaration if there's exactly one
2896   // result, because in the overloaded case the results can only be
2897   // functions and function templates.
2898   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2899       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2900     return ExprError();
2901 
2902   // Otherwise, just build an unresolved lookup expression.  Suppress
2903   // any lookup-related diagnostics; we'll hash these out later, when
2904   // we've picked a target.
2905   R.suppressDiagnostics();
2906 
2907   UnresolvedLookupExpr *ULE
2908     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2909                                    SS.getWithLocInContext(Context),
2910                                    R.getLookupNameInfo(),
2911                                    NeedsADL, R.isOverloadedResult(),
2912                                    R.begin(), R.end());
2913 
2914   return ULE;
2915 }
2916 
2917 static void
2918 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2919                                    ValueDecl *var, DeclContext *DC);
2920 
2921 /// Complete semantic analysis for a reference to the given declaration.
2922 ExprResult Sema::BuildDeclarationNameExpr(
2923     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2924     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2925     bool AcceptInvalidDecl) {
2926   assert(D && "Cannot refer to a NULL declaration");
2927   assert(!isa<FunctionTemplateDecl>(D) &&
2928          "Cannot refer unambiguously to a function template");
2929 
2930   SourceLocation Loc = NameInfo.getLoc();
2931   if (CheckDeclInExpr(*this, Loc, D))
2932     return ExprError();
2933 
2934   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2935     // Specifically diagnose references to class templates that are missing
2936     // a template argument list.
2937     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2938     return ExprError();
2939   }
2940 
2941   // Make sure that we're referring to a value.
2942   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2943   if (!VD) {
2944     Diag(Loc, diag::err_ref_non_value)
2945       << D << SS.getRange();
2946     Diag(D->getLocation(), diag::note_declared_at);
2947     return ExprError();
2948   }
2949 
2950   // Check whether this declaration can be used. Note that we suppress
2951   // this check when we're going to perform argument-dependent lookup
2952   // on this function name, because this might not be the function
2953   // that overload resolution actually selects.
2954   if (DiagnoseUseOfDecl(VD, Loc))
2955     return ExprError();
2956 
2957   // Only create DeclRefExpr's for valid Decl's.
2958   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2959     return ExprError();
2960 
2961   // Handle members of anonymous structs and unions.  If we got here,
2962   // and the reference is to a class member indirect field, then this
2963   // must be the subject of a pointer-to-member expression.
2964   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2965     if (!indirectField->isCXXClassMember())
2966       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2967                                                       indirectField);
2968 
2969   {
2970     QualType type = VD->getType();
2971     if (type.isNull())
2972       return ExprError();
2973     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2974       // C++ [except.spec]p17:
2975       //   An exception-specification is considered to be needed when:
2976       //   - in an expression, the function is the unique lookup result or
2977       //     the selected member of a set of overloaded functions.
2978       ResolveExceptionSpec(Loc, FPT);
2979       type = VD->getType();
2980     }
2981     ExprValueKind valueKind = VK_RValue;
2982 
2983     switch (D->getKind()) {
2984     // Ignore all the non-ValueDecl kinds.
2985 #define ABSTRACT_DECL(kind)
2986 #define VALUE(type, base)
2987 #define DECL(type, base) \
2988     case Decl::type:
2989 #include "clang/AST/DeclNodes.inc"
2990       llvm_unreachable("invalid value decl kind");
2991 
2992     // These shouldn't make it here.
2993     case Decl::ObjCAtDefsField:
2994       llvm_unreachable("forming non-member reference to ivar?");
2995 
2996     // Enum constants are always r-values and never references.
2997     // Unresolved using declarations are dependent.
2998     case Decl::EnumConstant:
2999     case Decl::UnresolvedUsingValue:
3000     case Decl::OMPDeclareReduction:
3001     case Decl::OMPDeclareMapper:
3002       valueKind = VK_RValue;
3003       break;
3004 
3005     // Fields and indirect fields that got here must be for
3006     // pointer-to-member expressions; we just call them l-values for
3007     // internal consistency, because this subexpression doesn't really
3008     // exist in the high-level semantics.
3009     case Decl::Field:
3010     case Decl::IndirectField:
3011     case Decl::ObjCIvar:
3012       assert(getLangOpts().CPlusPlus &&
3013              "building reference to field in C?");
3014 
3015       // These can't have reference type in well-formed programs, but
3016       // for internal consistency we do this anyway.
3017       type = type.getNonReferenceType();
3018       valueKind = VK_LValue;
3019       break;
3020 
3021     // Non-type template parameters are either l-values or r-values
3022     // depending on the type.
3023     case Decl::NonTypeTemplateParm: {
3024       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3025         type = reftype->getPointeeType();
3026         valueKind = VK_LValue; // even if the parameter is an r-value reference
3027         break;
3028       }
3029 
3030       // For non-references, we need to strip qualifiers just in case
3031       // the template parameter was declared as 'const int' or whatever.
3032       valueKind = VK_RValue;
3033       type = type.getUnqualifiedType();
3034       break;
3035     }
3036 
3037     case Decl::Var:
3038     case Decl::VarTemplateSpecialization:
3039     case Decl::VarTemplatePartialSpecialization:
3040     case Decl::Decomposition:
3041     case Decl::OMPCapturedExpr:
3042       // In C, "extern void blah;" is valid and is an r-value.
3043       if (!getLangOpts().CPlusPlus &&
3044           !type.hasQualifiers() &&
3045           type->isVoidType()) {
3046         valueKind = VK_RValue;
3047         break;
3048       }
3049       LLVM_FALLTHROUGH;
3050 
3051     case Decl::ImplicitParam:
3052     case Decl::ParmVar: {
3053       // These are always l-values.
3054       valueKind = VK_LValue;
3055       type = type.getNonReferenceType();
3056 
3057       // FIXME: Does the addition of const really only apply in
3058       // potentially-evaluated contexts? Since the variable isn't actually
3059       // captured in an unevaluated context, it seems that the answer is no.
3060       if (!isUnevaluatedContext()) {
3061         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3062         if (!CapturedType.isNull())
3063           type = CapturedType;
3064       }
3065 
3066       break;
3067     }
3068 
3069     case Decl::Binding: {
3070       // These are always lvalues.
3071       valueKind = VK_LValue;
3072       type = type.getNonReferenceType();
3073       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3074       // decides how that's supposed to work.
3075       auto *BD = cast<BindingDecl>(VD);
3076       if (BD->getDeclContext() != CurContext) {
3077         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3078         if (DD && DD->hasLocalStorage())
3079           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3080       }
3081       break;
3082     }
3083 
3084     case Decl::Function: {
3085       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3086         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3087           type = Context.BuiltinFnTy;
3088           valueKind = VK_RValue;
3089           break;
3090         }
3091       }
3092 
3093       const FunctionType *fty = type->castAs<FunctionType>();
3094 
3095       // If we're referring to a function with an __unknown_anytype
3096       // result type, make the entire expression __unknown_anytype.
3097       if (fty->getReturnType() == Context.UnknownAnyTy) {
3098         type = Context.UnknownAnyTy;
3099         valueKind = VK_RValue;
3100         break;
3101       }
3102 
3103       // Functions are l-values in C++.
3104       if (getLangOpts().CPlusPlus) {
3105         valueKind = VK_LValue;
3106         break;
3107       }
3108 
3109       // C99 DR 316 says that, if a function type comes from a
3110       // function definition (without a prototype), that type is only
3111       // used for checking compatibility. Therefore, when referencing
3112       // the function, we pretend that we don't have the full function
3113       // type.
3114       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3115           isa<FunctionProtoType>(fty))
3116         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3117                                               fty->getExtInfo());
3118 
3119       // Functions are r-values in C.
3120       valueKind = VK_RValue;
3121       break;
3122     }
3123 
3124     case Decl::CXXDeductionGuide:
3125       llvm_unreachable("building reference to deduction guide");
3126 
3127     case Decl::MSProperty:
3128       valueKind = VK_LValue;
3129       break;
3130 
3131     case Decl::CXXMethod:
3132       // If we're referring to a method with an __unknown_anytype
3133       // result type, make the entire expression __unknown_anytype.
3134       // This should only be possible with a type written directly.
3135       if (const FunctionProtoType *proto
3136             = dyn_cast<FunctionProtoType>(VD->getType()))
3137         if (proto->getReturnType() == Context.UnknownAnyTy) {
3138           type = Context.UnknownAnyTy;
3139           valueKind = VK_RValue;
3140           break;
3141         }
3142 
3143       // C++ methods are l-values if static, r-values if non-static.
3144       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3145         valueKind = VK_LValue;
3146         break;
3147       }
3148       LLVM_FALLTHROUGH;
3149 
3150     case Decl::CXXConversion:
3151     case Decl::CXXDestructor:
3152     case Decl::CXXConstructor:
3153       valueKind = VK_RValue;
3154       break;
3155     }
3156 
3157     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3158                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3159                             TemplateArgs);
3160   }
3161 }
3162 
3163 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3164                                     SmallString<32> &Target) {
3165   Target.resize(CharByteWidth * (Source.size() + 1));
3166   char *ResultPtr = &Target[0];
3167   const llvm::UTF8 *ErrorPtr;
3168   bool success =
3169       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3170   (void)success;
3171   assert(success);
3172   Target.resize(ResultPtr - &Target[0]);
3173 }
3174 
3175 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3176                                      PredefinedExpr::IdentKind IK) {
3177   // Pick the current block, lambda, captured statement or function.
3178   Decl *currentDecl = nullptr;
3179   if (const BlockScopeInfo *BSI = getCurBlock())
3180     currentDecl = BSI->TheDecl;
3181   else if (const LambdaScopeInfo *LSI = getCurLambda())
3182     currentDecl = LSI->CallOperator;
3183   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3184     currentDecl = CSI->TheCapturedDecl;
3185   else
3186     currentDecl = getCurFunctionOrMethodDecl();
3187 
3188   if (!currentDecl) {
3189     Diag(Loc, diag::ext_predef_outside_function);
3190     currentDecl = Context.getTranslationUnitDecl();
3191   }
3192 
3193   QualType ResTy;
3194   StringLiteral *SL = nullptr;
3195   if (cast<DeclContext>(currentDecl)->isDependentContext())
3196     ResTy = Context.DependentTy;
3197   else {
3198     // Pre-defined identifiers are of type char[x], where x is the length of
3199     // the string.
3200     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3201     unsigned Length = Str.length();
3202 
3203     llvm::APInt LengthI(32, Length + 1);
3204     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3205       ResTy =
3206           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3207       SmallString<32> RawChars;
3208       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3209                               Str, RawChars);
3210       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3211                                            ArrayType::Normal,
3212                                            /*IndexTypeQuals*/ 0);
3213       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3214                                  /*Pascal*/ false, ResTy, Loc);
3215     } else {
3216       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3217       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3218                                            ArrayType::Normal,
3219                                            /*IndexTypeQuals*/ 0);
3220       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3221                                  /*Pascal*/ false, ResTy, Loc);
3222     }
3223   }
3224 
3225   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3226 }
3227 
3228 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3229   PredefinedExpr::IdentKind IK;
3230 
3231   switch (Kind) {
3232   default: llvm_unreachable("Unknown simple primary expr!");
3233   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3234   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3235   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3236   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3237   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3238   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3239   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3240   }
3241 
3242   return BuildPredefinedExpr(Loc, IK);
3243 }
3244 
3245 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3246   SmallString<16> CharBuffer;
3247   bool Invalid = false;
3248   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3249   if (Invalid)
3250     return ExprError();
3251 
3252   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3253                             PP, Tok.getKind());
3254   if (Literal.hadError())
3255     return ExprError();
3256 
3257   QualType Ty;
3258   if (Literal.isWide())
3259     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3260   else if (Literal.isUTF8() && getLangOpts().Char8)
3261     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3262   else if (Literal.isUTF16())
3263     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3264   else if (Literal.isUTF32())
3265     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3266   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3267     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3268   else
3269     Ty = Context.CharTy;  // 'x' -> char in C++
3270 
3271   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3272   if (Literal.isWide())
3273     Kind = CharacterLiteral::Wide;
3274   else if (Literal.isUTF16())
3275     Kind = CharacterLiteral::UTF16;
3276   else if (Literal.isUTF32())
3277     Kind = CharacterLiteral::UTF32;
3278   else if (Literal.isUTF8())
3279     Kind = CharacterLiteral::UTF8;
3280 
3281   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3282                                              Tok.getLocation());
3283 
3284   if (Literal.getUDSuffix().empty())
3285     return Lit;
3286 
3287   // We're building a user-defined literal.
3288   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3289   SourceLocation UDSuffixLoc =
3290     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3291 
3292   // Make sure we're allowed user-defined literals here.
3293   if (!UDLScope)
3294     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3295 
3296   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3297   //   operator "" X (ch)
3298   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3299                                         Lit, Tok.getLocation());
3300 }
3301 
3302 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3303   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3304   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3305                                 Context.IntTy, Loc);
3306 }
3307 
3308 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3309                                   QualType Ty, SourceLocation Loc) {
3310   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3311 
3312   using llvm::APFloat;
3313   APFloat Val(Format);
3314 
3315   APFloat::opStatus result = Literal.GetFloatValue(Val);
3316 
3317   // Overflow is always an error, but underflow is only an error if
3318   // we underflowed to zero (APFloat reports denormals as underflow).
3319   if ((result & APFloat::opOverflow) ||
3320       ((result & APFloat::opUnderflow) && Val.isZero())) {
3321     unsigned diagnostic;
3322     SmallString<20> buffer;
3323     if (result & APFloat::opOverflow) {
3324       diagnostic = diag::warn_float_overflow;
3325       APFloat::getLargest(Format).toString(buffer);
3326     } else {
3327       diagnostic = diag::warn_float_underflow;
3328       APFloat::getSmallest(Format).toString(buffer);
3329     }
3330 
3331     S.Diag(Loc, diagnostic)
3332       << Ty
3333       << StringRef(buffer.data(), buffer.size());
3334   }
3335 
3336   bool isExact = (result == APFloat::opOK);
3337   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3338 }
3339 
3340 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3341   assert(E && "Invalid expression");
3342 
3343   if (E->isValueDependent())
3344     return false;
3345 
3346   QualType QT = E->getType();
3347   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3348     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3349     return true;
3350   }
3351 
3352   llvm::APSInt ValueAPS;
3353   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3354 
3355   if (R.isInvalid())
3356     return true;
3357 
3358   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3359   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3360     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3361         << ValueAPS.toString(10) << ValueIsPositive;
3362     return true;
3363   }
3364 
3365   return false;
3366 }
3367 
3368 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3369   // Fast path for a single digit (which is quite common).  A single digit
3370   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3371   if (Tok.getLength() == 1) {
3372     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3373     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3374   }
3375 
3376   SmallString<128> SpellingBuffer;
3377   // NumericLiteralParser wants to overread by one character.  Add padding to
3378   // the buffer in case the token is copied to the buffer.  If getSpelling()
3379   // returns a StringRef to the memory buffer, it should have a null char at
3380   // the EOF, so it is also safe.
3381   SpellingBuffer.resize(Tok.getLength() + 1);
3382 
3383   // Get the spelling of the token, which eliminates trigraphs, etc.
3384   bool Invalid = false;
3385   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3386   if (Invalid)
3387     return ExprError();
3388 
3389   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3390   if (Literal.hadError)
3391     return ExprError();
3392 
3393   if (Literal.hasUDSuffix()) {
3394     // We're building a user-defined literal.
3395     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3396     SourceLocation UDSuffixLoc =
3397       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3398 
3399     // Make sure we're allowed user-defined literals here.
3400     if (!UDLScope)
3401       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3402 
3403     QualType CookedTy;
3404     if (Literal.isFloatingLiteral()) {
3405       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3406       // long double, the literal is treated as a call of the form
3407       //   operator "" X (f L)
3408       CookedTy = Context.LongDoubleTy;
3409     } else {
3410       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3411       // unsigned long long, the literal is treated as a call of the form
3412       //   operator "" X (n ULL)
3413       CookedTy = Context.UnsignedLongLongTy;
3414     }
3415 
3416     DeclarationName OpName =
3417       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3418     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3419     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3420 
3421     SourceLocation TokLoc = Tok.getLocation();
3422 
3423     // Perform literal operator lookup to determine if we're building a raw
3424     // literal or a cooked one.
3425     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3426     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3427                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3428                                   /*AllowStringTemplate*/ false,
3429                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3430     case LOLR_ErrorNoDiagnostic:
3431       // Lookup failure for imaginary constants isn't fatal, there's still the
3432       // GNU extension producing _Complex types.
3433       break;
3434     case LOLR_Error:
3435       return ExprError();
3436     case LOLR_Cooked: {
3437       Expr *Lit;
3438       if (Literal.isFloatingLiteral()) {
3439         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3440       } else {
3441         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3442         if (Literal.GetIntegerValue(ResultVal))
3443           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3444               << /* Unsigned */ 1;
3445         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3446                                      Tok.getLocation());
3447       }
3448       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3449     }
3450 
3451     case LOLR_Raw: {
3452       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3453       // literal is treated as a call of the form
3454       //   operator "" X ("n")
3455       unsigned Length = Literal.getUDSuffixOffset();
3456       QualType StrTy = Context.getConstantArrayType(
3457           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3458           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3459       Expr *Lit = StringLiteral::Create(
3460           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3461           /*Pascal*/false, StrTy, &TokLoc, 1);
3462       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3463     }
3464 
3465     case LOLR_Template: {
3466       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3467       // template), L is treated as a call fo the form
3468       //   operator "" X <'c1', 'c2', ... 'ck'>()
3469       // where n is the source character sequence c1 c2 ... ck.
3470       TemplateArgumentListInfo ExplicitArgs;
3471       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3472       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3473       llvm::APSInt Value(CharBits, CharIsUnsigned);
3474       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3475         Value = TokSpelling[I];
3476         TemplateArgument Arg(Context, Value, Context.CharTy);
3477         TemplateArgumentLocInfo ArgInfo;
3478         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3479       }
3480       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3481                                       &ExplicitArgs);
3482     }
3483     case LOLR_StringTemplate:
3484       llvm_unreachable("unexpected literal operator lookup result");
3485     }
3486   }
3487 
3488   Expr *Res;
3489 
3490   if (Literal.isFixedPointLiteral()) {
3491     QualType Ty;
3492 
3493     if (Literal.isAccum) {
3494       if (Literal.isHalf) {
3495         Ty = Context.ShortAccumTy;
3496       } else if (Literal.isLong) {
3497         Ty = Context.LongAccumTy;
3498       } else {
3499         Ty = Context.AccumTy;
3500       }
3501     } else if (Literal.isFract) {
3502       if (Literal.isHalf) {
3503         Ty = Context.ShortFractTy;
3504       } else if (Literal.isLong) {
3505         Ty = Context.LongFractTy;
3506       } else {
3507         Ty = Context.FractTy;
3508       }
3509     }
3510 
3511     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3512 
3513     bool isSigned = !Literal.isUnsigned;
3514     unsigned scale = Context.getFixedPointScale(Ty);
3515     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3516 
3517     llvm::APInt Val(bit_width, 0, isSigned);
3518     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3519     bool ValIsZero = Val.isNullValue() && !Overflowed;
3520 
3521     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3522     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3523       // Clause 6.4.4 - The value of a constant shall be in the range of
3524       // representable values for its type, with exception for constants of a
3525       // fract type with a value of exactly 1; such a constant shall denote
3526       // the maximal value for the type.
3527       --Val;
3528     else if (Val.ugt(MaxVal) || Overflowed)
3529       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3530 
3531     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3532                                               Tok.getLocation(), scale);
3533   } else if (Literal.isFloatingLiteral()) {
3534     QualType Ty;
3535     if (Literal.isHalf){
3536       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3537         Ty = Context.HalfTy;
3538       else {
3539         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3540         return ExprError();
3541       }
3542     } else if (Literal.isFloat)
3543       Ty = Context.FloatTy;
3544     else if (Literal.isLong)
3545       Ty = Context.LongDoubleTy;
3546     else if (Literal.isFloat16)
3547       Ty = Context.Float16Ty;
3548     else if (Literal.isFloat128)
3549       Ty = Context.Float128Ty;
3550     else
3551       Ty = Context.DoubleTy;
3552 
3553     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3554 
3555     if (Ty == Context.DoubleTy) {
3556       if (getLangOpts().SinglePrecisionConstants) {
3557         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3558         if (BTy->getKind() != BuiltinType::Float) {
3559           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3560         }
3561       } else if (getLangOpts().OpenCL &&
3562                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3563         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3564         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3565         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3566       }
3567     }
3568   } else if (!Literal.isIntegerLiteral()) {
3569     return ExprError();
3570   } else {
3571     QualType Ty;
3572 
3573     // 'long long' is a C99 or C++11 feature.
3574     if (!getLangOpts().C99 && Literal.isLongLong) {
3575       if (getLangOpts().CPlusPlus)
3576         Diag(Tok.getLocation(),
3577              getLangOpts().CPlusPlus11 ?
3578              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3579       else
3580         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3581     }
3582 
3583     // Get the value in the widest-possible width.
3584     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3585     llvm::APInt ResultVal(MaxWidth, 0);
3586 
3587     if (Literal.GetIntegerValue(ResultVal)) {
3588       // If this value didn't fit into uintmax_t, error and force to ull.
3589       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3590           << /* Unsigned */ 1;
3591       Ty = Context.UnsignedLongLongTy;
3592       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3593              "long long is not intmax_t?");
3594     } else {
3595       // If this value fits into a ULL, try to figure out what else it fits into
3596       // according to the rules of C99 6.4.4.1p5.
3597 
3598       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3599       // be an unsigned int.
3600       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3601 
3602       // Check from smallest to largest, picking the smallest type we can.
3603       unsigned Width = 0;
3604 
3605       // Microsoft specific integer suffixes are explicitly sized.
3606       if (Literal.MicrosoftInteger) {
3607         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3608           Width = 8;
3609           Ty = Context.CharTy;
3610         } else {
3611           Width = Literal.MicrosoftInteger;
3612           Ty = Context.getIntTypeForBitwidth(Width,
3613                                              /*Signed=*/!Literal.isUnsigned);
3614         }
3615       }
3616 
3617       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3618         // Are int/unsigned possibilities?
3619         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3620 
3621         // Does it fit in a unsigned int?
3622         if (ResultVal.isIntN(IntSize)) {
3623           // Does it fit in a signed int?
3624           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3625             Ty = Context.IntTy;
3626           else if (AllowUnsigned)
3627             Ty = Context.UnsignedIntTy;
3628           Width = IntSize;
3629         }
3630       }
3631 
3632       // Are long/unsigned long possibilities?
3633       if (Ty.isNull() && !Literal.isLongLong) {
3634         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3635 
3636         // Does it fit in a unsigned long?
3637         if (ResultVal.isIntN(LongSize)) {
3638           // Does it fit in a signed long?
3639           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3640             Ty = Context.LongTy;
3641           else if (AllowUnsigned)
3642             Ty = Context.UnsignedLongTy;
3643           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3644           // is compatible.
3645           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3646             const unsigned LongLongSize =
3647                 Context.getTargetInfo().getLongLongWidth();
3648             Diag(Tok.getLocation(),
3649                  getLangOpts().CPlusPlus
3650                      ? Literal.isLong
3651                            ? diag::warn_old_implicitly_unsigned_long_cxx
3652                            : /*C++98 UB*/ diag::
3653                                  ext_old_implicitly_unsigned_long_cxx
3654                      : diag::warn_old_implicitly_unsigned_long)
3655                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3656                                             : /*will be ill-formed*/ 1);
3657             Ty = Context.UnsignedLongTy;
3658           }
3659           Width = LongSize;
3660         }
3661       }
3662 
3663       // Check long long if needed.
3664       if (Ty.isNull()) {
3665         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3666 
3667         // Does it fit in a unsigned long long?
3668         if (ResultVal.isIntN(LongLongSize)) {
3669           // Does it fit in a signed long long?
3670           // To be compatible with MSVC, hex integer literals ending with the
3671           // LL or i64 suffix are always signed in Microsoft mode.
3672           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3673               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3674             Ty = Context.LongLongTy;
3675           else if (AllowUnsigned)
3676             Ty = Context.UnsignedLongLongTy;
3677           Width = LongLongSize;
3678         }
3679       }
3680 
3681       // If we still couldn't decide a type, we probably have something that
3682       // does not fit in a signed long long, but has no U suffix.
3683       if (Ty.isNull()) {
3684         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3685         Ty = Context.UnsignedLongLongTy;
3686         Width = Context.getTargetInfo().getLongLongWidth();
3687       }
3688 
3689       if (ResultVal.getBitWidth() != Width)
3690         ResultVal = ResultVal.trunc(Width);
3691     }
3692     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3693   }
3694 
3695   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3696   if (Literal.isImaginary) {
3697     Res = new (Context) ImaginaryLiteral(Res,
3698                                         Context.getComplexType(Res->getType()));
3699 
3700     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3701   }
3702   return Res;
3703 }
3704 
3705 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3706   assert(E && "ActOnParenExpr() missing expr");
3707   return new (Context) ParenExpr(L, R, E);
3708 }
3709 
3710 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3711                                          SourceLocation Loc,
3712                                          SourceRange ArgRange) {
3713   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3714   // scalar or vector data type argument..."
3715   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3716   // type (C99 6.2.5p18) or void.
3717   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3718     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3719       << T << ArgRange;
3720     return true;
3721   }
3722 
3723   assert((T->isVoidType() || !T->isIncompleteType()) &&
3724          "Scalar types should always be complete");
3725   return false;
3726 }
3727 
3728 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3729                                            SourceLocation Loc,
3730                                            SourceRange ArgRange,
3731                                            UnaryExprOrTypeTrait TraitKind) {
3732   // Invalid types must be hard errors for SFINAE in C++.
3733   if (S.LangOpts.CPlusPlus)
3734     return true;
3735 
3736   // C99 6.5.3.4p1:
3737   if (T->isFunctionType() &&
3738       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3739        TraitKind == UETT_PreferredAlignOf)) {
3740     // sizeof(function)/alignof(function) is allowed as an extension.
3741     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3742       << TraitKind << ArgRange;
3743     return false;
3744   }
3745 
3746   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3747   // this is an error (OpenCL v1.1 s6.3.k)
3748   if (T->isVoidType()) {
3749     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3750                                         : diag::ext_sizeof_alignof_void_type;
3751     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3752     return false;
3753   }
3754 
3755   return true;
3756 }
3757 
3758 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3759                                              SourceLocation Loc,
3760                                              SourceRange ArgRange,
3761                                              UnaryExprOrTypeTrait TraitKind) {
3762   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3763   // runtime doesn't allow it.
3764   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3765     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3766       << T << (TraitKind == UETT_SizeOf)
3767       << ArgRange;
3768     return true;
3769   }
3770 
3771   return false;
3772 }
3773 
3774 /// Check whether E is a pointer from a decayed array type (the decayed
3775 /// pointer type is equal to T) and emit a warning if it is.
3776 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3777                                      Expr *E) {
3778   // Don't warn if the operation changed the type.
3779   if (T != E->getType())
3780     return;
3781 
3782   // Now look for array decays.
3783   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3784   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3785     return;
3786 
3787   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3788                                              << ICE->getType()
3789                                              << ICE->getSubExpr()->getType();
3790 }
3791 
3792 /// Check the constraints on expression operands to unary type expression
3793 /// and type traits.
3794 ///
3795 /// Completes any types necessary and validates the constraints on the operand
3796 /// expression. The logic mostly mirrors the type-based overload, but may modify
3797 /// the expression as it completes the type for that expression through template
3798 /// instantiation, etc.
3799 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3800                                             UnaryExprOrTypeTrait ExprKind) {
3801   QualType ExprTy = E->getType();
3802   assert(!ExprTy->isReferenceType());
3803 
3804   bool IsUnevaluatedOperand =
3805       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3806        ExprKind == UETT_PreferredAlignOf);
3807   if (IsUnevaluatedOperand) {
3808     ExprResult Result = CheckUnevaluatedOperand(E);
3809     if (Result.isInvalid())
3810       return true;
3811     E = Result.get();
3812   }
3813 
3814   if (ExprKind == UETT_VecStep)
3815     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3816                                         E->getSourceRange());
3817 
3818   // Whitelist some types as extensions
3819   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3820                                       E->getSourceRange(), ExprKind))
3821     return false;
3822 
3823   // 'alignof' applied to an expression only requires the base element type of
3824   // the expression to be complete. 'sizeof' requires the expression's type to
3825   // be complete (and will attempt to complete it if it's an array of unknown
3826   // bound).
3827   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3828     if (RequireCompleteType(E->getExprLoc(),
3829                             Context.getBaseElementType(E->getType()),
3830                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3831                             E->getSourceRange()))
3832       return true;
3833   } else {
3834     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3835                                 ExprKind, E->getSourceRange()))
3836       return true;
3837   }
3838 
3839   // Completing the expression's type may have changed it.
3840   ExprTy = E->getType();
3841   assert(!ExprTy->isReferenceType());
3842 
3843   if (ExprTy->isFunctionType()) {
3844     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3845       << ExprKind << E->getSourceRange();
3846     return true;
3847   }
3848 
3849   // The operand for sizeof and alignof is in an unevaluated expression context,
3850   // so side effects could result in unintended consequences.
3851   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3852       E->HasSideEffects(Context, false))
3853     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3854 
3855   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3856                                        E->getSourceRange(), ExprKind))
3857     return true;
3858 
3859   if (ExprKind == UETT_SizeOf) {
3860     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3861       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3862         QualType OType = PVD->getOriginalType();
3863         QualType Type = PVD->getType();
3864         if (Type->isPointerType() && OType->isArrayType()) {
3865           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3866             << Type << OType;
3867           Diag(PVD->getLocation(), diag::note_declared_at);
3868         }
3869       }
3870     }
3871 
3872     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3873     // decays into a pointer and returns an unintended result. This is most
3874     // likely a typo for "sizeof(array) op x".
3875     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3876       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3877                                BO->getLHS());
3878       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3879                                BO->getRHS());
3880     }
3881   }
3882 
3883   return false;
3884 }
3885 
3886 /// Check the constraints on operands to unary expression and type
3887 /// traits.
3888 ///
3889 /// This will complete any types necessary, and validate the various constraints
3890 /// on those operands.
3891 ///
3892 /// The UsualUnaryConversions() function is *not* called by this routine.
3893 /// C99 6.3.2.1p[2-4] all state:
3894 ///   Except when it is the operand of the sizeof operator ...
3895 ///
3896 /// C++ [expr.sizeof]p4
3897 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3898 ///   standard conversions are not applied to the operand of sizeof.
3899 ///
3900 /// This policy is followed for all of the unary trait expressions.
3901 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3902                                             SourceLocation OpLoc,
3903                                             SourceRange ExprRange,
3904                                             UnaryExprOrTypeTrait ExprKind) {
3905   if (ExprType->isDependentType())
3906     return false;
3907 
3908   // C++ [expr.sizeof]p2:
3909   //     When applied to a reference or a reference type, the result
3910   //     is the size of the referenced type.
3911   // C++11 [expr.alignof]p3:
3912   //     When alignof is applied to a reference type, the result
3913   //     shall be the alignment of the referenced type.
3914   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3915     ExprType = Ref->getPointeeType();
3916 
3917   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3918   //   When alignof or _Alignof is applied to an array type, the result
3919   //   is the alignment of the element type.
3920   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3921       ExprKind == UETT_OpenMPRequiredSimdAlign)
3922     ExprType = Context.getBaseElementType(ExprType);
3923 
3924   if (ExprKind == UETT_VecStep)
3925     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3926 
3927   // Whitelist some types as extensions
3928   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3929                                       ExprKind))
3930     return false;
3931 
3932   if (RequireCompleteType(OpLoc, ExprType,
3933                           diag::err_sizeof_alignof_incomplete_type,
3934                           ExprKind, ExprRange))
3935     return true;
3936 
3937   if (ExprType->isFunctionType()) {
3938     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3939       << ExprKind << ExprRange;
3940     return true;
3941   }
3942 
3943   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3944                                        ExprKind))
3945     return true;
3946 
3947   return false;
3948 }
3949 
3950 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3951   // Cannot know anything else if the expression is dependent.
3952   if (E->isTypeDependent())
3953     return false;
3954 
3955   if (E->getObjectKind() == OK_BitField) {
3956     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3957        << 1 << E->getSourceRange();
3958     return true;
3959   }
3960 
3961   ValueDecl *D = nullptr;
3962   Expr *Inner = E->IgnoreParens();
3963   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
3964     D = DRE->getDecl();
3965   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
3966     D = ME->getMemberDecl();
3967   }
3968 
3969   // If it's a field, require the containing struct to have a
3970   // complete definition so that we can compute the layout.
3971   //
3972   // This can happen in C++11 onwards, either by naming the member
3973   // in a way that is not transformed into a member access expression
3974   // (in an unevaluated operand, for instance), or by naming the member
3975   // in a trailing-return-type.
3976   //
3977   // For the record, since __alignof__ on expressions is a GCC
3978   // extension, GCC seems to permit this but always gives the
3979   // nonsensical answer 0.
3980   //
3981   // We don't really need the layout here --- we could instead just
3982   // directly check for all the appropriate alignment-lowing
3983   // attributes --- but that would require duplicating a lot of
3984   // logic that just isn't worth duplicating for such a marginal
3985   // use-case.
3986   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3987     // Fast path this check, since we at least know the record has a
3988     // definition if we can find a member of it.
3989     if (!FD->getParent()->isCompleteDefinition()) {
3990       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3991         << E->getSourceRange();
3992       return true;
3993     }
3994 
3995     // Otherwise, if it's a field, and the field doesn't have
3996     // reference type, then it must have a complete type (or be a
3997     // flexible array member, which we explicitly want to
3998     // white-list anyway), which makes the following checks trivial.
3999     if (!FD->getType()->isReferenceType())
4000       return false;
4001   }
4002 
4003   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4004 }
4005 
4006 bool Sema::CheckVecStepExpr(Expr *E) {
4007   E = E->IgnoreParens();
4008 
4009   // Cannot know anything else if the expression is dependent.
4010   if (E->isTypeDependent())
4011     return false;
4012 
4013   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4014 }
4015 
4016 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4017                                         CapturingScopeInfo *CSI) {
4018   assert(T->isVariablyModifiedType());
4019   assert(CSI != nullptr);
4020 
4021   // We're going to walk down into the type and look for VLA expressions.
4022   do {
4023     const Type *Ty = T.getTypePtr();
4024     switch (Ty->getTypeClass()) {
4025 #define TYPE(Class, Base)
4026 #define ABSTRACT_TYPE(Class, Base)
4027 #define NON_CANONICAL_TYPE(Class, Base)
4028 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4029 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4030 #include "clang/AST/TypeNodes.inc"
4031       T = QualType();
4032       break;
4033     // These types are never variably-modified.
4034     case Type::Builtin:
4035     case Type::Complex:
4036     case Type::Vector:
4037     case Type::ExtVector:
4038     case Type::Record:
4039     case Type::Enum:
4040     case Type::Elaborated:
4041     case Type::TemplateSpecialization:
4042     case Type::ObjCObject:
4043     case Type::ObjCInterface:
4044     case Type::ObjCObjectPointer:
4045     case Type::ObjCTypeParam:
4046     case Type::Pipe:
4047       llvm_unreachable("type class is never variably-modified!");
4048     case Type::Adjusted:
4049       T = cast<AdjustedType>(Ty)->getOriginalType();
4050       break;
4051     case Type::Decayed:
4052       T = cast<DecayedType>(Ty)->getPointeeType();
4053       break;
4054     case Type::Pointer:
4055       T = cast<PointerType>(Ty)->getPointeeType();
4056       break;
4057     case Type::BlockPointer:
4058       T = cast<BlockPointerType>(Ty)->getPointeeType();
4059       break;
4060     case Type::LValueReference:
4061     case Type::RValueReference:
4062       T = cast<ReferenceType>(Ty)->getPointeeType();
4063       break;
4064     case Type::MemberPointer:
4065       T = cast<MemberPointerType>(Ty)->getPointeeType();
4066       break;
4067     case Type::ConstantArray:
4068     case Type::IncompleteArray:
4069       // Losing element qualification here is fine.
4070       T = cast<ArrayType>(Ty)->getElementType();
4071       break;
4072     case Type::VariableArray: {
4073       // Losing element qualification here is fine.
4074       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4075 
4076       // Unknown size indication requires no size computation.
4077       // Otherwise, evaluate and record it.
4078       auto Size = VAT->getSizeExpr();
4079       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4080           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4081         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4082 
4083       T = VAT->getElementType();
4084       break;
4085     }
4086     case Type::FunctionProto:
4087     case Type::FunctionNoProto:
4088       T = cast<FunctionType>(Ty)->getReturnType();
4089       break;
4090     case Type::Paren:
4091     case Type::TypeOf:
4092     case Type::UnaryTransform:
4093     case Type::Attributed:
4094     case Type::SubstTemplateTypeParm:
4095     case Type::PackExpansion:
4096     case Type::MacroQualified:
4097       // Keep walking after single level desugaring.
4098       T = T.getSingleStepDesugaredType(Context);
4099       break;
4100     case Type::Typedef:
4101       T = cast<TypedefType>(Ty)->desugar();
4102       break;
4103     case Type::Decltype:
4104       T = cast<DecltypeType>(Ty)->desugar();
4105       break;
4106     case Type::Auto:
4107     case Type::DeducedTemplateSpecialization:
4108       T = cast<DeducedType>(Ty)->getDeducedType();
4109       break;
4110     case Type::TypeOfExpr:
4111       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4112       break;
4113     case Type::Atomic:
4114       T = cast<AtomicType>(Ty)->getValueType();
4115       break;
4116     }
4117   } while (!T.isNull() && T->isVariablyModifiedType());
4118 }
4119 
4120 /// Build a sizeof or alignof expression given a type operand.
4121 ExprResult
4122 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4123                                      SourceLocation OpLoc,
4124                                      UnaryExprOrTypeTrait ExprKind,
4125                                      SourceRange R) {
4126   if (!TInfo)
4127     return ExprError();
4128 
4129   QualType T = TInfo->getType();
4130 
4131   if (!T->isDependentType() &&
4132       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4133     return ExprError();
4134 
4135   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4136     if (auto *TT = T->getAs<TypedefType>()) {
4137       for (auto I = FunctionScopes.rbegin(),
4138                 E = std::prev(FunctionScopes.rend());
4139            I != E; ++I) {
4140         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4141         if (CSI == nullptr)
4142           break;
4143         DeclContext *DC = nullptr;
4144         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4145           DC = LSI->CallOperator;
4146         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4147           DC = CRSI->TheCapturedDecl;
4148         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4149           DC = BSI->TheDecl;
4150         if (DC) {
4151           if (DC->containsDecl(TT->getDecl()))
4152             break;
4153           captureVariablyModifiedType(Context, T, CSI);
4154         }
4155       }
4156     }
4157   }
4158 
4159   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4160   return new (Context) UnaryExprOrTypeTraitExpr(
4161       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4162 }
4163 
4164 /// Build a sizeof or alignof expression given an expression
4165 /// operand.
4166 ExprResult
4167 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4168                                      UnaryExprOrTypeTrait ExprKind) {
4169   ExprResult PE = CheckPlaceholderExpr(E);
4170   if (PE.isInvalid())
4171     return ExprError();
4172 
4173   E = PE.get();
4174 
4175   // Verify that the operand is valid.
4176   bool isInvalid = false;
4177   if (E->isTypeDependent()) {
4178     // Delay type-checking for type-dependent expressions.
4179   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4180     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4181   } else if (ExprKind == UETT_VecStep) {
4182     isInvalid = CheckVecStepExpr(E);
4183   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4184       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4185       isInvalid = true;
4186   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4187     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4188     isInvalid = true;
4189   } else {
4190     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4191   }
4192 
4193   if (isInvalid)
4194     return ExprError();
4195 
4196   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4197     PE = TransformToPotentiallyEvaluated(E);
4198     if (PE.isInvalid()) return ExprError();
4199     E = PE.get();
4200   }
4201 
4202   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4203   return new (Context) UnaryExprOrTypeTraitExpr(
4204       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4205 }
4206 
4207 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4208 /// expr and the same for @c alignof and @c __alignof
4209 /// Note that the ArgRange is invalid if isType is false.
4210 ExprResult
4211 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4212                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4213                                     void *TyOrEx, SourceRange ArgRange) {
4214   // If error parsing type, ignore.
4215   if (!TyOrEx) return ExprError();
4216 
4217   if (IsType) {
4218     TypeSourceInfo *TInfo;
4219     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4220     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4221   }
4222 
4223   Expr *ArgEx = (Expr *)TyOrEx;
4224   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4225   return Result;
4226 }
4227 
4228 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4229                                      bool IsReal) {
4230   if (V.get()->isTypeDependent())
4231     return S.Context.DependentTy;
4232 
4233   // _Real and _Imag are only l-values for normal l-values.
4234   if (V.get()->getObjectKind() != OK_Ordinary) {
4235     V = S.DefaultLvalueConversion(V.get());
4236     if (V.isInvalid())
4237       return QualType();
4238   }
4239 
4240   // These operators return the element type of a complex type.
4241   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4242     return CT->getElementType();
4243 
4244   // Otherwise they pass through real integer and floating point types here.
4245   if (V.get()->getType()->isArithmeticType())
4246     return V.get()->getType();
4247 
4248   // Test for placeholders.
4249   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4250   if (PR.isInvalid()) return QualType();
4251   if (PR.get() != V.get()) {
4252     V = PR;
4253     return CheckRealImagOperand(S, V, Loc, IsReal);
4254   }
4255 
4256   // Reject anything else.
4257   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4258     << (IsReal ? "__real" : "__imag");
4259   return QualType();
4260 }
4261 
4262 
4263 
4264 ExprResult
4265 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4266                           tok::TokenKind Kind, Expr *Input) {
4267   UnaryOperatorKind Opc;
4268   switch (Kind) {
4269   default: llvm_unreachable("Unknown unary op!");
4270   case tok::plusplus:   Opc = UO_PostInc; break;
4271   case tok::minusminus: Opc = UO_PostDec; break;
4272   }
4273 
4274   // Since this might is a postfix expression, get rid of ParenListExprs.
4275   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4276   if (Result.isInvalid()) return ExprError();
4277   Input = Result.get();
4278 
4279   return BuildUnaryOp(S, OpLoc, Opc, Input);
4280 }
4281 
4282 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4283 ///
4284 /// \return true on error
4285 static bool checkArithmeticOnObjCPointer(Sema &S,
4286                                          SourceLocation opLoc,
4287                                          Expr *op) {
4288   assert(op->getType()->isObjCObjectPointerType());
4289   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4290       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4291     return false;
4292 
4293   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4294     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4295     << op->getSourceRange();
4296   return true;
4297 }
4298 
4299 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4300   auto *BaseNoParens = Base->IgnoreParens();
4301   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4302     return MSProp->getPropertyDecl()->getType()->isArrayType();
4303   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4304 }
4305 
4306 ExprResult
4307 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4308                               Expr *idx, SourceLocation rbLoc) {
4309   if (base && !base->getType().isNull() &&
4310       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4311     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4312                                     /*Length=*/nullptr, rbLoc);
4313 
4314   // Since this might be a postfix expression, get rid of ParenListExprs.
4315   if (isa<ParenListExpr>(base)) {
4316     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4317     if (result.isInvalid()) return ExprError();
4318     base = result.get();
4319   }
4320 
4321   // A comma-expression as the index is deprecated in C++2a onwards.
4322   if (getLangOpts().CPlusPlus2a &&
4323       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4324        (isa<CXXOperatorCallExpr>(idx) &&
4325         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4326     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4327       << SourceRange(base->getBeginLoc(), rbLoc);
4328   }
4329 
4330   // Handle any non-overload placeholder types in the base and index
4331   // expressions.  We can't handle overloads here because the other
4332   // operand might be an overloadable type, in which case the overload
4333   // resolution for the operator overload should get the first crack
4334   // at the overload.
4335   bool IsMSPropertySubscript = false;
4336   if (base->getType()->isNonOverloadPlaceholderType()) {
4337     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4338     if (!IsMSPropertySubscript) {
4339       ExprResult result = CheckPlaceholderExpr(base);
4340       if (result.isInvalid())
4341         return ExprError();
4342       base = result.get();
4343     }
4344   }
4345   if (idx->getType()->isNonOverloadPlaceholderType()) {
4346     ExprResult result = CheckPlaceholderExpr(idx);
4347     if (result.isInvalid()) return ExprError();
4348     idx = result.get();
4349   }
4350 
4351   // Build an unanalyzed expression if either operand is type-dependent.
4352   if (getLangOpts().CPlusPlus &&
4353       (base->isTypeDependent() || idx->isTypeDependent())) {
4354     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4355                                             VK_LValue, OK_Ordinary, rbLoc);
4356   }
4357 
4358   // MSDN, property (C++)
4359   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4360   // This attribute can also be used in the declaration of an empty array in a
4361   // class or structure definition. For example:
4362   // __declspec(property(get=GetX, put=PutX)) int x[];
4363   // The above statement indicates that x[] can be used with one or more array
4364   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4365   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4366   if (IsMSPropertySubscript) {
4367     // Build MS property subscript expression if base is MS property reference
4368     // or MS property subscript.
4369     return new (Context) MSPropertySubscriptExpr(
4370         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4371   }
4372 
4373   // Use C++ overloaded-operator rules if either operand has record
4374   // type.  The spec says to do this if either type is *overloadable*,
4375   // but enum types can't declare subscript operators or conversion
4376   // operators, so there's nothing interesting for overload resolution
4377   // to do if there aren't any record types involved.
4378   //
4379   // ObjC pointers have their own subscripting logic that is not tied
4380   // to overload resolution and so should not take this path.
4381   if (getLangOpts().CPlusPlus &&
4382       (base->getType()->isRecordType() ||
4383        (!base->getType()->isObjCObjectPointerType() &&
4384         idx->getType()->isRecordType()))) {
4385     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4386   }
4387 
4388   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4389 
4390   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4391     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4392 
4393   return Res;
4394 }
4395 
4396 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4397   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4398   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4399 
4400   // For expressions like `&(*s).b`, the base is recorded and what should be
4401   // checked.
4402   const MemberExpr *Member = nullptr;
4403   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4404     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4405 
4406   LastRecord.PossibleDerefs.erase(StrippedExpr);
4407 }
4408 
4409 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4410   QualType ResultTy = E->getType();
4411   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4412 
4413   // Bail if the element is an array since it is not memory access.
4414   if (isa<ArrayType>(ResultTy))
4415     return;
4416 
4417   if (ResultTy->hasAttr(attr::NoDeref)) {
4418     LastRecord.PossibleDerefs.insert(E);
4419     return;
4420   }
4421 
4422   // Check if the base type is a pointer to a member access of a struct
4423   // marked with noderef.
4424   const Expr *Base = E->getBase();
4425   QualType BaseTy = Base->getType();
4426   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4427     // Not a pointer access
4428     return;
4429 
4430   const MemberExpr *Member = nullptr;
4431   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4432          Member->isArrow())
4433     Base = Member->getBase();
4434 
4435   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4436     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4437       LastRecord.PossibleDerefs.insert(E);
4438   }
4439 }
4440 
4441 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4442                                           Expr *LowerBound,
4443                                           SourceLocation ColonLoc, Expr *Length,
4444                                           SourceLocation RBLoc) {
4445   if (Base->getType()->isPlaceholderType() &&
4446       !Base->getType()->isSpecificPlaceholderType(
4447           BuiltinType::OMPArraySection)) {
4448     ExprResult Result = CheckPlaceholderExpr(Base);
4449     if (Result.isInvalid())
4450       return ExprError();
4451     Base = Result.get();
4452   }
4453   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4454     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4455     if (Result.isInvalid())
4456       return ExprError();
4457     Result = DefaultLvalueConversion(Result.get());
4458     if (Result.isInvalid())
4459       return ExprError();
4460     LowerBound = Result.get();
4461   }
4462   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4463     ExprResult Result = CheckPlaceholderExpr(Length);
4464     if (Result.isInvalid())
4465       return ExprError();
4466     Result = DefaultLvalueConversion(Result.get());
4467     if (Result.isInvalid())
4468       return ExprError();
4469     Length = Result.get();
4470   }
4471 
4472   // Build an unanalyzed expression if either operand is type-dependent.
4473   if (Base->isTypeDependent() ||
4474       (LowerBound &&
4475        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4476       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4477     return new (Context)
4478         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4479                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4480   }
4481 
4482   // Perform default conversions.
4483   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4484   QualType ResultTy;
4485   if (OriginalTy->isAnyPointerType()) {
4486     ResultTy = OriginalTy->getPointeeType();
4487   } else if (OriginalTy->isArrayType()) {
4488     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4489   } else {
4490     return ExprError(
4491         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4492         << Base->getSourceRange());
4493   }
4494   // C99 6.5.2.1p1
4495   if (LowerBound) {
4496     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4497                                                       LowerBound);
4498     if (Res.isInvalid())
4499       return ExprError(Diag(LowerBound->getExprLoc(),
4500                             diag::err_omp_typecheck_section_not_integer)
4501                        << 0 << LowerBound->getSourceRange());
4502     LowerBound = Res.get();
4503 
4504     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4505         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4506       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4507           << 0 << LowerBound->getSourceRange();
4508   }
4509   if (Length) {
4510     auto Res =
4511         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4512     if (Res.isInvalid())
4513       return ExprError(Diag(Length->getExprLoc(),
4514                             diag::err_omp_typecheck_section_not_integer)
4515                        << 1 << Length->getSourceRange());
4516     Length = Res.get();
4517 
4518     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4519         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4520       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4521           << 1 << Length->getSourceRange();
4522   }
4523 
4524   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4525   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4526   // type. Note that functions are not objects, and that (in C99 parlance)
4527   // incomplete types are not object types.
4528   if (ResultTy->isFunctionType()) {
4529     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4530         << ResultTy << Base->getSourceRange();
4531     return ExprError();
4532   }
4533 
4534   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4535                           diag::err_omp_section_incomplete_type, Base))
4536     return ExprError();
4537 
4538   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4539     Expr::EvalResult Result;
4540     if (LowerBound->EvaluateAsInt(Result, Context)) {
4541       // OpenMP 4.5, [2.4 Array Sections]
4542       // The array section must be a subset of the original array.
4543       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4544       if (LowerBoundValue.isNegative()) {
4545         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4546             << LowerBound->getSourceRange();
4547         return ExprError();
4548       }
4549     }
4550   }
4551 
4552   if (Length) {
4553     Expr::EvalResult Result;
4554     if (Length->EvaluateAsInt(Result, Context)) {
4555       // OpenMP 4.5, [2.4 Array Sections]
4556       // The length must evaluate to non-negative integers.
4557       llvm::APSInt LengthValue = Result.Val.getInt();
4558       if (LengthValue.isNegative()) {
4559         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4560             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4561             << Length->getSourceRange();
4562         return ExprError();
4563       }
4564     }
4565   } else if (ColonLoc.isValid() &&
4566              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4567                                       !OriginalTy->isVariableArrayType()))) {
4568     // OpenMP 4.5, [2.4 Array Sections]
4569     // When the size of the array dimension is not known, the length must be
4570     // specified explicitly.
4571     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4572         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4573     return ExprError();
4574   }
4575 
4576   if (!Base->getType()->isSpecificPlaceholderType(
4577           BuiltinType::OMPArraySection)) {
4578     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4579     if (Result.isInvalid())
4580       return ExprError();
4581     Base = Result.get();
4582   }
4583   return new (Context)
4584       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4585                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4586 }
4587 
4588 ExprResult
4589 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4590                                       Expr *Idx, SourceLocation RLoc) {
4591   Expr *LHSExp = Base;
4592   Expr *RHSExp = Idx;
4593 
4594   ExprValueKind VK = VK_LValue;
4595   ExprObjectKind OK = OK_Ordinary;
4596 
4597   // Per C++ core issue 1213, the result is an xvalue if either operand is
4598   // a non-lvalue array, and an lvalue otherwise.
4599   if (getLangOpts().CPlusPlus11) {
4600     for (auto *Op : {LHSExp, RHSExp}) {
4601       Op = Op->IgnoreImplicit();
4602       if (Op->getType()->isArrayType() && !Op->isLValue())
4603         VK = VK_XValue;
4604     }
4605   }
4606 
4607   // Perform default conversions.
4608   if (!LHSExp->getType()->getAs<VectorType>()) {
4609     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4610     if (Result.isInvalid())
4611       return ExprError();
4612     LHSExp = Result.get();
4613   }
4614   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4615   if (Result.isInvalid())
4616     return ExprError();
4617   RHSExp = Result.get();
4618 
4619   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4620 
4621   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4622   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4623   // in the subscript position. As a result, we need to derive the array base
4624   // and index from the expression types.
4625   Expr *BaseExpr, *IndexExpr;
4626   QualType ResultType;
4627   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4628     BaseExpr = LHSExp;
4629     IndexExpr = RHSExp;
4630     ResultType = Context.DependentTy;
4631   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4632     BaseExpr = LHSExp;
4633     IndexExpr = RHSExp;
4634     ResultType = PTy->getPointeeType();
4635   } else if (const ObjCObjectPointerType *PTy =
4636                LHSTy->getAs<ObjCObjectPointerType>()) {
4637     BaseExpr = LHSExp;
4638     IndexExpr = RHSExp;
4639 
4640     // Use custom logic if this should be the pseudo-object subscript
4641     // expression.
4642     if (!LangOpts.isSubscriptPointerArithmetic())
4643       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4644                                           nullptr);
4645 
4646     ResultType = PTy->getPointeeType();
4647   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4648      // Handle the uncommon case of "123[Ptr]".
4649     BaseExpr = RHSExp;
4650     IndexExpr = LHSExp;
4651     ResultType = PTy->getPointeeType();
4652   } else if (const ObjCObjectPointerType *PTy =
4653                RHSTy->getAs<ObjCObjectPointerType>()) {
4654      // Handle the uncommon case of "123[Ptr]".
4655     BaseExpr = RHSExp;
4656     IndexExpr = LHSExp;
4657     ResultType = PTy->getPointeeType();
4658     if (!LangOpts.isSubscriptPointerArithmetic()) {
4659       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4660         << ResultType << BaseExpr->getSourceRange();
4661       return ExprError();
4662     }
4663   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4664     BaseExpr = LHSExp;    // vectors: V[123]
4665     IndexExpr = RHSExp;
4666     // We apply C++ DR1213 to vector subscripting too.
4667     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4668       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4669       if (Materialized.isInvalid())
4670         return ExprError();
4671       LHSExp = Materialized.get();
4672     }
4673     VK = LHSExp->getValueKind();
4674     if (VK != VK_RValue)
4675       OK = OK_VectorComponent;
4676 
4677     ResultType = VTy->getElementType();
4678     QualType BaseType = BaseExpr->getType();
4679     Qualifiers BaseQuals = BaseType.getQualifiers();
4680     Qualifiers MemberQuals = ResultType.getQualifiers();
4681     Qualifiers Combined = BaseQuals + MemberQuals;
4682     if (Combined != MemberQuals)
4683       ResultType = Context.getQualifiedType(ResultType, Combined);
4684   } else if (LHSTy->isArrayType()) {
4685     // If we see an array that wasn't promoted by
4686     // DefaultFunctionArrayLvalueConversion, it must be an array that
4687     // wasn't promoted because of the C90 rule that doesn't
4688     // allow promoting non-lvalue arrays.  Warn, then
4689     // force the promotion here.
4690     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4691         << LHSExp->getSourceRange();
4692     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4693                                CK_ArrayToPointerDecay).get();
4694     LHSTy = LHSExp->getType();
4695 
4696     BaseExpr = LHSExp;
4697     IndexExpr = RHSExp;
4698     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4699   } else if (RHSTy->isArrayType()) {
4700     // Same as previous, except for 123[f().a] case
4701     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4702         << RHSExp->getSourceRange();
4703     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4704                                CK_ArrayToPointerDecay).get();
4705     RHSTy = RHSExp->getType();
4706 
4707     BaseExpr = RHSExp;
4708     IndexExpr = LHSExp;
4709     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4710   } else {
4711     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4712        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4713   }
4714   // C99 6.5.2.1p1
4715   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4716     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4717                      << IndexExpr->getSourceRange());
4718 
4719   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4720        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4721          && !IndexExpr->isTypeDependent())
4722     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4723 
4724   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4725   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4726   // type. Note that Functions are not objects, and that (in C99 parlance)
4727   // incomplete types are not object types.
4728   if (ResultType->isFunctionType()) {
4729     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4730         << ResultType << BaseExpr->getSourceRange();
4731     return ExprError();
4732   }
4733 
4734   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4735     // GNU extension: subscripting on pointer to void
4736     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4737       << BaseExpr->getSourceRange();
4738 
4739     // C forbids expressions of unqualified void type from being l-values.
4740     // See IsCForbiddenLValueType.
4741     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4742   } else if (!ResultType->isDependentType() &&
4743       RequireCompleteType(LLoc, ResultType,
4744                           diag::err_subscript_incomplete_type, BaseExpr))
4745     return ExprError();
4746 
4747   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4748          !ResultType.isCForbiddenLValueType());
4749 
4750   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4751       FunctionScopes.size() > 1) {
4752     if (auto *TT =
4753             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4754       for (auto I = FunctionScopes.rbegin(),
4755                 E = std::prev(FunctionScopes.rend());
4756            I != E; ++I) {
4757         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4758         if (CSI == nullptr)
4759           break;
4760         DeclContext *DC = nullptr;
4761         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4762           DC = LSI->CallOperator;
4763         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4764           DC = CRSI->TheCapturedDecl;
4765         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4766           DC = BSI->TheDecl;
4767         if (DC) {
4768           if (DC->containsDecl(TT->getDecl()))
4769             break;
4770           captureVariablyModifiedType(
4771               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4772         }
4773       }
4774     }
4775   }
4776 
4777   return new (Context)
4778       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4779 }
4780 
4781 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4782                                   ParmVarDecl *Param) {
4783   if (Param->hasUnparsedDefaultArg()) {
4784     Diag(CallLoc,
4785          diag::err_use_of_default_argument_to_function_declared_later) <<
4786       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4787     Diag(UnparsedDefaultArgLocs[Param],
4788          diag::note_default_argument_declared_here);
4789     return true;
4790   }
4791 
4792   if (Param->hasUninstantiatedDefaultArg()) {
4793     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4794 
4795     EnterExpressionEvaluationContext EvalContext(
4796         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4797 
4798     // Instantiate the expression.
4799     //
4800     // FIXME: Pass in a correct Pattern argument, otherwise
4801     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4802     //
4803     // template<typename T>
4804     // struct A {
4805     //   static int FooImpl();
4806     //
4807     //   template<typename Tp>
4808     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4809     //   // template argument list [[T], [Tp]], should be [[Tp]].
4810     //   friend A<Tp> Foo(int a);
4811     // };
4812     //
4813     // template<typename T>
4814     // A<T> Foo(int a = A<T>::FooImpl());
4815     MultiLevelTemplateArgumentList MutiLevelArgList
4816       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4817 
4818     InstantiatingTemplate Inst(*this, CallLoc, Param,
4819                                MutiLevelArgList.getInnermost());
4820     if (Inst.isInvalid())
4821       return true;
4822     if (Inst.isAlreadyInstantiating()) {
4823       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4824       Param->setInvalidDecl();
4825       return true;
4826     }
4827 
4828     ExprResult Result;
4829     {
4830       // C++ [dcl.fct.default]p5:
4831       //   The names in the [default argument] expression are bound, and
4832       //   the semantic constraints are checked, at the point where the
4833       //   default argument expression appears.
4834       ContextRAII SavedContext(*this, FD);
4835       LocalInstantiationScope Local(*this);
4836       runWithSufficientStackSpace(CallLoc, [&] {
4837         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4838                                   /*DirectInit*/false);
4839       });
4840     }
4841     if (Result.isInvalid())
4842       return true;
4843 
4844     // Check the expression as an initializer for the parameter.
4845     InitializedEntity Entity
4846       = InitializedEntity::InitializeParameter(Context, Param);
4847     InitializationKind Kind = InitializationKind::CreateCopy(
4848         Param->getLocation(),
4849         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4850     Expr *ResultE = Result.getAs<Expr>();
4851 
4852     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4853     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4854     if (Result.isInvalid())
4855       return true;
4856 
4857     Result =
4858         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4859                             /*DiscardedValue*/ false);
4860     if (Result.isInvalid())
4861       return true;
4862 
4863     // Remember the instantiated default argument.
4864     Param->setDefaultArg(Result.getAs<Expr>());
4865     if (ASTMutationListener *L = getASTMutationListener()) {
4866       L->DefaultArgumentInstantiated(Param);
4867     }
4868   }
4869 
4870   // If the default argument expression is not set yet, we are building it now.
4871   if (!Param->hasInit()) {
4872     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4873     Param->setInvalidDecl();
4874     return true;
4875   }
4876 
4877   // If the default expression creates temporaries, we need to
4878   // push them to the current stack of expression temporaries so they'll
4879   // be properly destroyed.
4880   // FIXME: We should really be rebuilding the default argument with new
4881   // bound temporaries; see the comment in PR5810.
4882   // We don't need to do that with block decls, though, because
4883   // blocks in default argument expression can never capture anything.
4884   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4885     // Set the "needs cleanups" bit regardless of whether there are
4886     // any explicit objects.
4887     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4888 
4889     // Append all the objects to the cleanup list.  Right now, this
4890     // should always be a no-op, because blocks in default argument
4891     // expressions should never be able to capture anything.
4892     assert(!Init->getNumObjects() &&
4893            "default argument expression has capturing blocks?");
4894   }
4895 
4896   // We already type-checked the argument, so we know it works.
4897   // Just mark all of the declarations in this potentially-evaluated expression
4898   // as being "referenced".
4899   EnterExpressionEvaluationContext EvalContext(
4900       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4901   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4902                                    /*SkipLocalVariables=*/true);
4903   return false;
4904 }
4905 
4906 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4907                                         FunctionDecl *FD, ParmVarDecl *Param) {
4908   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4909     return ExprError();
4910   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4911 }
4912 
4913 Sema::VariadicCallType
4914 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4915                           Expr *Fn) {
4916   if (Proto && Proto->isVariadic()) {
4917     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4918       return VariadicConstructor;
4919     else if (Fn && Fn->getType()->isBlockPointerType())
4920       return VariadicBlock;
4921     else if (FDecl) {
4922       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4923         if (Method->isInstance())
4924           return VariadicMethod;
4925     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4926       return VariadicMethod;
4927     return VariadicFunction;
4928   }
4929   return VariadicDoesNotApply;
4930 }
4931 
4932 namespace {
4933 class FunctionCallCCC final : public FunctionCallFilterCCC {
4934 public:
4935   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4936                   unsigned NumArgs, MemberExpr *ME)
4937       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4938         FunctionName(FuncName) {}
4939 
4940   bool ValidateCandidate(const TypoCorrection &candidate) override {
4941     if (!candidate.getCorrectionSpecifier() ||
4942         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4943       return false;
4944     }
4945 
4946     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4947   }
4948 
4949   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4950     return std::make_unique<FunctionCallCCC>(*this);
4951   }
4952 
4953 private:
4954   const IdentifierInfo *const FunctionName;
4955 };
4956 }
4957 
4958 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4959                                                FunctionDecl *FDecl,
4960                                                ArrayRef<Expr *> Args) {
4961   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4962   DeclarationName FuncName = FDecl->getDeclName();
4963   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4964 
4965   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4966   if (TypoCorrection Corrected = S.CorrectTypo(
4967           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4968           S.getScopeForContext(S.CurContext), nullptr, CCC,
4969           Sema::CTK_ErrorRecovery)) {
4970     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4971       if (Corrected.isOverloaded()) {
4972         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4973         OverloadCandidateSet::iterator Best;
4974         for (NamedDecl *CD : Corrected) {
4975           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4976             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4977                                    OCS);
4978         }
4979         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4980         case OR_Success:
4981           ND = Best->FoundDecl;
4982           Corrected.setCorrectionDecl(ND);
4983           break;
4984         default:
4985           break;
4986         }
4987       }
4988       ND = ND->getUnderlyingDecl();
4989       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4990         return Corrected;
4991     }
4992   }
4993   return TypoCorrection();
4994 }
4995 
4996 /// ConvertArgumentsForCall - Converts the arguments specified in
4997 /// Args/NumArgs to the parameter types of the function FDecl with
4998 /// function prototype Proto. Call is the call expression itself, and
4999 /// Fn is the function expression. For a C++ member function, this
5000 /// routine does not attempt to convert the object argument. Returns
5001 /// true if the call is ill-formed.
5002 bool
5003 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5004                               FunctionDecl *FDecl,
5005                               const FunctionProtoType *Proto,
5006                               ArrayRef<Expr *> Args,
5007                               SourceLocation RParenLoc,
5008                               bool IsExecConfig) {
5009   // Bail out early if calling a builtin with custom typechecking.
5010   if (FDecl)
5011     if (unsigned ID = FDecl->getBuiltinID())
5012       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5013         return false;
5014 
5015   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5016   // assignment, to the types of the corresponding parameter, ...
5017   unsigned NumParams = Proto->getNumParams();
5018   bool Invalid = false;
5019   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5020   unsigned FnKind = Fn->getType()->isBlockPointerType()
5021                        ? 1 /* block */
5022                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5023                                        : 0 /* function */);
5024 
5025   // If too few arguments are available (and we don't have default
5026   // arguments for the remaining parameters), don't make the call.
5027   if (Args.size() < NumParams) {
5028     if (Args.size() < MinArgs) {
5029       TypoCorrection TC;
5030       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5031         unsigned diag_id =
5032             MinArgs == NumParams && !Proto->isVariadic()
5033                 ? diag::err_typecheck_call_too_few_args_suggest
5034                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5035         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5036                                         << static_cast<unsigned>(Args.size())
5037                                         << TC.getCorrectionRange());
5038       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5039         Diag(RParenLoc,
5040              MinArgs == NumParams && !Proto->isVariadic()
5041                  ? diag::err_typecheck_call_too_few_args_one
5042                  : diag::err_typecheck_call_too_few_args_at_least_one)
5043             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5044       else
5045         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5046                             ? diag::err_typecheck_call_too_few_args
5047                             : diag::err_typecheck_call_too_few_args_at_least)
5048             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5049             << Fn->getSourceRange();
5050 
5051       // Emit the location of the prototype.
5052       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5053         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5054 
5055       return true;
5056     }
5057     // We reserve space for the default arguments when we create
5058     // the call expression, before calling ConvertArgumentsForCall.
5059     assert((Call->getNumArgs() == NumParams) &&
5060            "We should have reserved space for the default arguments before!");
5061   }
5062 
5063   // If too many are passed and not variadic, error on the extras and drop
5064   // them.
5065   if (Args.size() > NumParams) {
5066     if (!Proto->isVariadic()) {
5067       TypoCorrection TC;
5068       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5069         unsigned diag_id =
5070             MinArgs == NumParams && !Proto->isVariadic()
5071                 ? diag::err_typecheck_call_too_many_args_suggest
5072                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5073         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5074                                         << static_cast<unsigned>(Args.size())
5075                                         << TC.getCorrectionRange());
5076       } else if (NumParams == 1 && FDecl &&
5077                  FDecl->getParamDecl(0)->getDeclName())
5078         Diag(Args[NumParams]->getBeginLoc(),
5079              MinArgs == NumParams
5080                  ? diag::err_typecheck_call_too_many_args_one
5081                  : diag::err_typecheck_call_too_many_args_at_most_one)
5082             << FnKind << FDecl->getParamDecl(0)
5083             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5084             << SourceRange(Args[NumParams]->getBeginLoc(),
5085                            Args.back()->getEndLoc());
5086       else
5087         Diag(Args[NumParams]->getBeginLoc(),
5088              MinArgs == NumParams
5089                  ? diag::err_typecheck_call_too_many_args
5090                  : diag::err_typecheck_call_too_many_args_at_most)
5091             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5092             << Fn->getSourceRange()
5093             << SourceRange(Args[NumParams]->getBeginLoc(),
5094                            Args.back()->getEndLoc());
5095 
5096       // Emit the location of the prototype.
5097       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5098         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5099 
5100       // This deletes the extra arguments.
5101       Call->shrinkNumArgs(NumParams);
5102       return true;
5103     }
5104   }
5105   SmallVector<Expr *, 8> AllArgs;
5106   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5107 
5108   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5109                                    AllArgs, CallType);
5110   if (Invalid)
5111     return true;
5112   unsigned TotalNumArgs = AllArgs.size();
5113   for (unsigned i = 0; i < TotalNumArgs; ++i)
5114     Call->setArg(i, AllArgs[i]);
5115 
5116   return false;
5117 }
5118 
5119 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5120                                   const FunctionProtoType *Proto,
5121                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5122                                   SmallVectorImpl<Expr *> &AllArgs,
5123                                   VariadicCallType CallType, bool AllowExplicit,
5124                                   bool IsListInitialization) {
5125   unsigned NumParams = Proto->getNumParams();
5126   bool Invalid = false;
5127   size_t ArgIx = 0;
5128   // Continue to check argument types (even if we have too few/many args).
5129   for (unsigned i = FirstParam; i < NumParams; i++) {
5130     QualType ProtoArgType = Proto->getParamType(i);
5131 
5132     Expr *Arg;
5133     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5134     if (ArgIx < Args.size()) {
5135       Arg = Args[ArgIx++];
5136 
5137       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5138                               diag::err_call_incomplete_argument, Arg))
5139         return true;
5140 
5141       // Strip the unbridged-cast placeholder expression off, if applicable.
5142       bool CFAudited = false;
5143       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5144           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5145           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5146         Arg = stripARCUnbridgedCast(Arg);
5147       else if (getLangOpts().ObjCAutoRefCount &&
5148                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5149                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5150         CFAudited = true;
5151 
5152       if (Proto->getExtParameterInfo(i).isNoEscape())
5153         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5154           BE->getBlockDecl()->setDoesNotEscape();
5155 
5156       InitializedEntity Entity =
5157           Param ? InitializedEntity::InitializeParameter(Context, Param,
5158                                                          ProtoArgType)
5159                 : InitializedEntity::InitializeParameter(
5160                       Context, ProtoArgType, Proto->isParamConsumed(i));
5161 
5162       // Remember that parameter belongs to a CF audited API.
5163       if (CFAudited)
5164         Entity.setParameterCFAudited();
5165 
5166       ExprResult ArgE = PerformCopyInitialization(
5167           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5168       if (ArgE.isInvalid())
5169         return true;
5170 
5171       Arg = ArgE.getAs<Expr>();
5172     } else {
5173       assert(Param && "can't use default arguments without a known callee");
5174 
5175       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5176       if (ArgExpr.isInvalid())
5177         return true;
5178 
5179       Arg = ArgExpr.getAs<Expr>();
5180     }
5181 
5182     // Check for array bounds violations for each argument to the call. This
5183     // check only triggers warnings when the argument isn't a more complex Expr
5184     // with its own checking, such as a BinaryOperator.
5185     CheckArrayAccess(Arg);
5186 
5187     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5188     CheckStaticArrayArgument(CallLoc, Param, Arg);
5189 
5190     AllArgs.push_back(Arg);
5191   }
5192 
5193   // If this is a variadic call, handle args passed through "...".
5194   if (CallType != VariadicDoesNotApply) {
5195     // Assume that extern "C" functions with variadic arguments that
5196     // return __unknown_anytype aren't *really* variadic.
5197     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5198         FDecl->isExternC()) {
5199       for (Expr *A : Args.slice(ArgIx)) {
5200         QualType paramType; // ignored
5201         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5202         Invalid |= arg.isInvalid();
5203         AllArgs.push_back(arg.get());
5204       }
5205 
5206     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5207     } else {
5208       for (Expr *A : Args.slice(ArgIx)) {
5209         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5210         Invalid |= Arg.isInvalid();
5211         AllArgs.push_back(Arg.get());
5212       }
5213     }
5214 
5215     // Check for array bounds violations.
5216     for (Expr *A : Args.slice(ArgIx))
5217       CheckArrayAccess(A);
5218   }
5219   return Invalid;
5220 }
5221 
5222 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5223   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5224   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5225     TL = DTL.getOriginalLoc();
5226   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5227     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5228       << ATL.getLocalSourceRange();
5229 }
5230 
5231 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5232 /// array parameter, check that it is non-null, and that if it is formed by
5233 /// array-to-pointer decay, the underlying array is sufficiently large.
5234 ///
5235 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5236 /// array type derivation, then for each call to the function, the value of the
5237 /// corresponding actual argument shall provide access to the first element of
5238 /// an array with at least as many elements as specified by the size expression.
5239 void
5240 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5241                                ParmVarDecl *Param,
5242                                const Expr *ArgExpr) {
5243   // Static array parameters are not supported in C++.
5244   if (!Param || getLangOpts().CPlusPlus)
5245     return;
5246 
5247   QualType OrigTy = Param->getOriginalType();
5248 
5249   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5250   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5251     return;
5252 
5253   if (ArgExpr->isNullPointerConstant(Context,
5254                                      Expr::NPC_NeverValueDependent)) {
5255     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5256     DiagnoseCalleeStaticArrayParam(*this, Param);
5257     return;
5258   }
5259 
5260   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5261   if (!CAT)
5262     return;
5263 
5264   const ConstantArrayType *ArgCAT =
5265     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5266   if (!ArgCAT)
5267     return;
5268 
5269   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5270                                              ArgCAT->getElementType())) {
5271     if (ArgCAT->getSize().ult(CAT->getSize())) {
5272       Diag(CallLoc, diag::warn_static_array_too_small)
5273           << ArgExpr->getSourceRange()
5274           << (unsigned)ArgCAT->getSize().getZExtValue()
5275           << (unsigned)CAT->getSize().getZExtValue() << 0;
5276       DiagnoseCalleeStaticArrayParam(*this, Param);
5277     }
5278     return;
5279   }
5280 
5281   Optional<CharUnits> ArgSize =
5282       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5283   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5284   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5285     Diag(CallLoc, diag::warn_static_array_too_small)
5286         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5287         << (unsigned)ParmSize->getQuantity() << 1;
5288     DiagnoseCalleeStaticArrayParam(*this, Param);
5289   }
5290 }
5291 
5292 /// Given a function expression of unknown-any type, try to rebuild it
5293 /// to have a function type.
5294 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5295 
5296 /// Is the given type a placeholder that we need to lower out
5297 /// immediately during argument processing?
5298 static bool isPlaceholderToRemoveAsArg(QualType type) {
5299   // Placeholders are never sugared.
5300   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5301   if (!placeholder) return false;
5302 
5303   switch (placeholder->getKind()) {
5304   // Ignore all the non-placeholder types.
5305 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5306   case BuiltinType::Id:
5307 #include "clang/Basic/OpenCLImageTypes.def"
5308 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5309   case BuiltinType::Id:
5310 #include "clang/Basic/OpenCLExtensionTypes.def"
5311   // In practice we'll never use this, since all SVE types are sugared
5312   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5313 #define SVE_TYPE(Name, Id, SingletonId) \
5314   case BuiltinType::Id:
5315 #include "clang/Basic/AArch64SVEACLETypes.def"
5316 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5317 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5318 #include "clang/AST/BuiltinTypes.def"
5319     return false;
5320 
5321   // We cannot lower out overload sets; they might validly be resolved
5322   // by the call machinery.
5323   case BuiltinType::Overload:
5324     return false;
5325 
5326   // Unbridged casts in ARC can be handled in some call positions and
5327   // should be left in place.
5328   case BuiltinType::ARCUnbridgedCast:
5329     return false;
5330 
5331   // Pseudo-objects should be converted as soon as possible.
5332   case BuiltinType::PseudoObject:
5333     return true;
5334 
5335   // The debugger mode could theoretically but currently does not try
5336   // to resolve unknown-typed arguments based on known parameter types.
5337   case BuiltinType::UnknownAny:
5338     return true;
5339 
5340   // These are always invalid as call arguments and should be reported.
5341   case BuiltinType::BoundMember:
5342   case BuiltinType::BuiltinFn:
5343   case BuiltinType::OMPArraySection:
5344     return true;
5345 
5346   }
5347   llvm_unreachable("bad builtin type kind");
5348 }
5349 
5350 /// Check an argument list for placeholders that we won't try to
5351 /// handle later.
5352 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5353   // Apply this processing to all the arguments at once instead of
5354   // dying at the first failure.
5355   bool hasInvalid = false;
5356   for (size_t i = 0, e = args.size(); i != e; i++) {
5357     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5358       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5359       if (result.isInvalid()) hasInvalid = true;
5360       else args[i] = result.get();
5361     } else if (hasInvalid) {
5362       (void)S.CorrectDelayedTyposInExpr(args[i]);
5363     }
5364   }
5365   return hasInvalid;
5366 }
5367 
5368 /// If a builtin function has a pointer argument with no explicit address
5369 /// space, then it should be able to accept a pointer to any address
5370 /// space as input.  In order to do this, we need to replace the
5371 /// standard builtin declaration with one that uses the same address space
5372 /// as the call.
5373 ///
5374 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5375 ///                  it does not contain any pointer arguments without
5376 ///                  an address space qualifer.  Otherwise the rewritten
5377 ///                  FunctionDecl is returned.
5378 /// TODO: Handle pointer return types.
5379 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5380                                                 FunctionDecl *FDecl,
5381                                                 MultiExprArg ArgExprs) {
5382 
5383   QualType DeclType = FDecl->getType();
5384   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5385 
5386   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5387       ArgExprs.size() < FT->getNumParams())
5388     return nullptr;
5389 
5390   bool NeedsNewDecl = false;
5391   unsigned i = 0;
5392   SmallVector<QualType, 8> OverloadParams;
5393 
5394   for (QualType ParamType : FT->param_types()) {
5395 
5396     // Convert array arguments to pointer to simplify type lookup.
5397     ExprResult ArgRes =
5398         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5399     if (ArgRes.isInvalid())
5400       return nullptr;
5401     Expr *Arg = ArgRes.get();
5402     QualType ArgType = Arg->getType();
5403     if (!ParamType->isPointerType() ||
5404         ParamType.getQualifiers().hasAddressSpace() ||
5405         !ArgType->isPointerType() ||
5406         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5407       OverloadParams.push_back(ParamType);
5408       continue;
5409     }
5410 
5411     QualType PointeeType = ParamType->getPointeeType();
5412     if (PointeeType.getQualifiers().hasAddressSpace())
5413       continue;
5414 
5415     NeedsNewDecl = true;
5416     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5417 
5418     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5419     OverloadParams.push_back(Context.getPointerType(PointeeType));
5420   }
5421 
5422   if (!NeedsNewDecl)
5423     return nullptr;
5424 
5425   FunctionProtoType::ExtProtoInfo EPI;
5426   EPI.Variadic = FT->isVariadic();
5427   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5428                                                 OverloadParams, EPI);
5429   DeclContext *Parent = FDecl->getParent();
5430   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5431                                                     FDecl->getLocation(),
5432                                                     FDecl->getLocation(),
5433                                                     FDecl->getIdentifier(),
5434                                                     OverloadTy,
5435                                                     /*TInfo=*/nullptr,
5436                                                     SC_Extern, false,
5437                                                     /*hasPrototype=*/true);
5438   SmallVector<ParmVarDecl*, 16> Params;
5439   FT = cast<FunctionProtoType>(OverloadTy);
5440   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5441     QualType ParamType = FT->getParamType(i);
5442     ParmVarDecl *Parm =
5443         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5444                                 SourceLocation(), nullptr, ParamType,
5445                                 /*TInfo=*/nullptr, SC_None, nullptr);
5446     Parm->setScopeInfo(0, i);
5447     Params.push_back(Parm);
5448   }
5449   OverloadDecl->setParams(Params);
5450   return OverloadDecl;
5451 }
5452 
5453 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5454                                     FunctionDecl *Callee,
5455                                     MultiExprArg ArgExprs) {
5456   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5457   // similar attributes) really don't like it when functions are called with an
5458   // invalid number of args.
5459   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5460                          /*PartialOverloading=*/false) &&
5461       !Callee->isVariadic())
5462     return;
5463   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5464     return;
5465 
5466   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5467     S.Diag(Fn->getBeginLoc(),
5468            isa<CXXMethodDecl>(Callee)
5469                ? diag::err_ovl_no_viable_member_function_in_call
5470                : diag::err_ovl_no_viable_function_in_call)
5471         << Callee << Callee->getSourceRange();
5472     S.Diag(Callee->getLocation(),
5473            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5474         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5475     return;
5476   }
5477 }
5478 
5479 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5480     const UnresolvedMemberExpr *const UME, Sema &S) {
5481 
5482   const auto GetFunctionLevelDCIfCXXClass =
5483       [](Sema &S) -> const CXXRecordDecl * {
5484     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5485     if (!DC || !DC->getParent())
5486       return nullptr;
5487 
5488     // If the call to some member function was made from within a member
5489     // function body 'M' return return 'M's parent.
5490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5491       return MD->getParent()->getCanonicalDecl();
5492     // else the call was made from within a default member initializer of a
5493     // class, so return the class.
5494     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5495       return RD->getCanonicalDecl();
5496     return nullptr;
5497   };
5498   // If our DeclContext is neither a member function nor a class (in the
5499   // case of a lambda in a default member initializer), we can't have an
5500   // enclosing 'this'.
5501 
5502   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5503   if (!CurParentClass)
5504     return false;
5505 
5506   // The naming class for implicit member functions call is the class in which
5507   // name lookup starts.
5508   const CXXRecordDecl *const NamingClass =
5509       UME->getNamingClass()->getCanonicalDecl();
5510   assert(NamingClass && "Must have naming class even for implicit access");
5511 
5512   // If the unresolved member functions were found in a 'naming class' that is
5513   // related (either the same or derived from) to the class that contains the
5514   // member function that itself contained the implicit member access.
5515 
5516   return CurParentClass == NamingClass ||
5517          CurParentClass->isDerivedFrom(NamingClass);
5518 }
5519 
5520 static void
5521 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5522     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5523 
5524   if (!UME)
5525     return;
5526 
5527   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5528   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5529   // already been captured, or if this is an implicit member function call (if
5530   // it isn't, an attempt to capture 'this' should already have been made).
5531   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5532       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5533     return;
5534 
5535   // Check if the naming class in which the unresolved members were found is
5536   // related (same as or is a base of) to the enclosing class.
5537 
5538   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5539     return;
5540 
5541 
5542   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5543   // If the enclosing function is not dependent, then this lambda is
5544   // capture ready, so if we can capture this, do so.
5545   if (!EnclosingFunctionCtx->isDependentContext()) {
5546     // If the current lambda and all enclosing lambdas can capture 'this' -
5547     // then go ahead and capture 'this' (since our unresolved overload set
5548     // contains at least one non-static member function).
5549     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5550       S.CheckCXXThisCapture(CallLoc);
5551   } else if (S.CurContext->isDependentContext()) {
5552     // ... since this is an implicit member reference, that might potentially
5553     // involve a 'this' capture, mark 'this' for potential capture in
5554     // enclosing lambdas.
5555     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5556       CurLSI->addPotentialThisCapture(CallLoc);
5557   }
5558 }
5559 
5560 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5561                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5562                                Expr *ExecConfig) {
5563   ExprResult Call =
5564       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5565   if (Call.isInvalid())
5566     return Call;
5567 
5568   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5569   // language modes.
5570   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5571     if (ULE->hasExplicitTemplateArgs() &&
5572         ULE->decls_begin() == ULE->decls_end()) {
5573       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5574                                  ? diag::warn_cxx17_compat_adl_only_template_id
5575                                  : diag::ext_adl_only_template_id)
5576           << ULE->getName();
5577     }
5578   }
5579 
5580   return Call;
5581 }
5582 
5583 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5584 /// This provides the location of the left/right parens and a list of comma
5585 /// locations.
5586 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5587                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5588                                Expr *ExecConfig, bool IsExecConfig) {
5589   // Since this might be a postfix expression, get rid of ParenListExprs.
5590   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5591   if (Result.isInvalid()) return ExprError();
5592   Fn = Result.get();
5593 
5594   if (checkArgsForPlaceholders(*this, ArgExprs))
5595     return ExprError();
5596 
5597   if (getLangOpts().CPlusPlus) {
5598     // If this is a pseudo-destructor expression, build the call immediately.
5599     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5600       if (!ArgExprs.empty()) {
5601         // Pseudo-destructor calls should not have any arguments.
5602         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5603             << FixItHint::CreateRemoval(
5604                    SourceRange(ArgExprs.front()->getBeginLoc(),
5605                                ArgExprs.back()->getEndLoc()));
5606       }
5607 
5608       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5609                               VK_RValue, RParenLoc);
5610     }
5611     if (Fn->getType() == Context.PseudoObjectTy) {
5612       ExprResult result = CheckPlaceholderExpr(Fn);
5613       if (result.isInvalid()) return ExprError();
5614       Fn = result.get();
5615     }
5616 
5617     // Determine whether this is a dependent call inside a C++ template,
5618     // in which case we won't do any semantic analysis now.
5619     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5620       if (ExecConfig) {
5621         return CUDAKernelCallExpr::Create(
5622             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5623             Context.DependentTy, VK_RValue, RParenLoc);
5624       } else {
5625 
5626         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5627             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5628             Fn->getBeginLoc());
5629 
5630         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5631                                 VK_RValue, RParenLoc);
5632       }
5633     }
5634 
5635     // Determine whether this is a call to an object (C++ [over.call.object]).
5636     if (Fn->getType()->isRecordType())
5637       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5638                                           RParenLoc);
5639 
5640     if (Fn->getType() == Context.UnknownAnyTy) {
5641       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5642       if (result.isInvalid()) return ExprError();
5643       Fn = result.get();
5644     }
5645 
5646     if (Fn->getType() == Context.BoundMemberTy) {
5647       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5648                                        RParenLoc);
5649     }
5650   }
5651 
5652   // Check for overloaded calls.  This can happen even in C due to extensions.
5653   if (Fn->getType() == Context.OverloadTy) {
5654     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5655 
5656     // We aren't supposed to apply this logic if there's an '&' involved.
5657     if (!find.HasFormOfMemberPointer) {
5658       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5659         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5660                                 VK_RValue, RParenLoc);
5661       OverloadExpr *ovl = find.Expression;
5662       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5663         return BuildOverloadedCallExpr(
5664             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5665             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5666       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5667                                        RParenLoc);
5668     }
5669   }
5670 
5671   // If we're directly calling a function, get the appropriate declaration.
5672   if (Fn->getType() == Context.UnknownAnyTy) {
5673     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5674     if (result.isInvalid()) return ExprError();
5675     Fn = result.get();
5676   }
5677 
5678   Expr *NakedFn = Fn->IgnoreParens();
5679 
5680   bool CallingNDeclIndirectly = false;
5681   NamedDecl *NDecl = nullptr;
5682   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5683     if (UnOp->getOpcode() == UO_AddrOf) {
5684       CallingNDeclIndirectly = true;
5685       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5686     }
5687   }
5688 
5689   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5690     NDecl = DRE->getDecl();
5691 
5692     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5693     if (FDecl && FDecl->getBuiltinID()) {
5694       // Rewrite the function decl for this builtin by replacing parameters
5695       // with no explicit address space with the address space of the arguments
5696       // in ArgExprs.
5697       if ((FDecl =
5698                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5699         NDecl = FDecl;
5700         Fn = DeclRefExpr::Create(
5701             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5702             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5703             nullptr, DRE->isNonOdrUse());
5704       }
5705     }
5706   } else if (isa<MemberExpr>(NakedFn))
5707     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5708 
5709   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5710     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5711                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5712       return ExprError();
5713 
5714     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5715       return ExprError();
5716 
5717     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5718   }
5719 
5720   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5721                                ExecConfig, IsExecConfig);
5722 }
5723 
5724 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5725 ///
5726 /// __builtin_astype( value, dst type )
5727 ///
5728 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5729                                  SourceLocation BuiltinLoc,
5730                                  SourceLocation RParenLoc) {
5731   ExprValueKind VK = VK_RValue;
5732   ExprObjectKind OK = OK_Ordinary;
5733   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5734   QualType SrcTy = E->getType();
5735   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5736     return ExprError(Diag(BuiltinLoc,
5737                           diag::err_invalid_astype_of_different_size)
5738                      << DstTy
5739                      << SrcTy
5740                      << E->getSourceRange());
5741   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5742 }
5743 
5744 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5745 /// provided arguments.
5746 ///
5747 /// __builtin_convertvector( value, dst type )
5748 ///
5749 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5750                                         SourceLocation BuiltinLoc,
5751                                         SourceLocation RParenLoc) {
5752   TypeSourceInfo *TInfo;
5753   GetTypeFromParser(ParsedDestTy, &TInfo);
5754   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5755 }
5756 
5757 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5758 /// i.e. an expression not of \p OverloadTy.  The expression should
5759 /// unary-convert to an expression of function-pointer or
5760 /// block-pointer type.
5761 ///
5762 /// \param NDecl the declaration being called, if available
5763 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5764                                        SourceLocation LParenLoc,
5765                                        ArrayRef<Expr *> Args,
5766                                        SourceLocation RParenLoc, Expr *Config,
5767                                        bool IsExecConfig, ADLCallKind UsesADL) {
5768   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5769   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5770 
5771   // Functions with 'interrupt' attribute cannot be called directly.
5772   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5773     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5774     return ExprError();
5775   }
5776 
5777   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5778   // so there's some risk when calling out to non-interrupt handler functions
5779   // that the callee might not preserve them. This is easy to diagnose here,
5780   // but can be very challenging to debug.
5781   if (auto *Caller = getCurFunctionDecl())
5782     if (Caller->hasAttr<ARMInterruptAttr>()) {
5783       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5784       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5785         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5786     }
5787 
5788   // Promote the function operand.
5789   // We special-case function promotion here because we only allow promoting
5790   // builtin functions to function pointers in the callee of a call.
5791   ExprResult Result;
5792   QualType ResultTy;
5793   if (BuiltinID &&
5794       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5795     // Extract the return type from the (builtin) function pointer type.
5796     // FIXME Several builtins still have setType in
5797     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5798     // Builtins.def to ensure they are correct before removing setType calls.
5799     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5800     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5801     ResultTy = FDecl->getCallResultType();
5802   } else {
5803     Result = CallExprUnaryConversions(Fn);
5804     ResultTy = Context.BoolTy;
5805   }
5806   if (Result.isInvalid())
5807     return ExprError();
5808   Fn = Result.get();
5809 
5810   // Check for a valid function type, but only if it is not a builtin which
5811   // requires custom type checking. These will be handled by
5812   // CheckBuiltinFunctionCall below just after creation of the call expression.
5813   const FunctionType *FuncT = nullptr;
5814   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5815   retry:
5816     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5817       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5818       // have type pointer to function".
5819       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5820       if (!FuncT)
5821         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5822                          << Fn->getType() << Fn->getSourceRange());
5823     } else if (const BlockPointerType *BPT =
5824                    Fn->getType()->getAs<BlockPointerType>()) {
5825       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5826     } else {
5827       // Handle calls to expressions of unknown-any type.
5828       if (Fn->getType() == Context.UnknownAnyTy) {
5829         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5830         if (rewrite.isInvalid())
5831           return ExprError();
5832         Fn = rewrite.get();
5833         goto retry;
5834       }
5835 
5836       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5837                        << Fn->getType() << Fn->getSourceRange());
5838     }
5839   }
5840 
5841   // Get the number of parameters in the function prototype, if any.
5842   // We will allocate space for max(Args.size(), NumParams) arguments
5843   // in the call expression.
5844   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5845   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5846 
5847   CallExpr *TheCall;
5848   if (Config) {
5849     assert(UsesADL == ADLCallKind::NotADL &&
5850            "CUDAKernelCallExpr should not use ADL");
5851     TheCall =
5852         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5853                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5854   } else {
5855     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5856                                RParenLoc, NumParams, UsesADL);
5857   }
5858 
5859   if (!getLangOpts().CPlusPlus) {
5860     // Forget about the nulled arguments since typo correction
5861     // do not handle them well.
5862     TheCall->shrinkNumArgs(Args.size());
5863     // C cannot always handle TypoExpr nodes in builtin calls and direct
5864     // function calls as their argument checking don't necessarily handle
5865     // dependent types properly, so make sure any TypoExprs have been
5866     // dealt with.
5867     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5868     if (!Result.isUsable()) return ExprError();
5869     CallExpr *TheOldCall = TheCall;
5870     TheCall = dyn_cast<CallExpr>(Result.get());
5871     bool CorrectedTypos = TheCall != TheOldCall;
5872     if (!TheCall) return Result;
5873     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5874 
5875     // A new call expression node was created if some typos were corrected.
5876     // However it may not have been constructed with enough storage. In this
5877     // case, rebuild the node with enough storage. The waste of space is
5878     // immaterial since this only happens when some typos were corrected.
5879     if (CorrectedTypos && Args.size() < NumParams) {
5880       if (Config)
5881         TheCall = CUDAKernelCallExpr::Create(
5882             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5883             RParenLoc, NumParams);
5884       else
5885         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5886                                    RParenLoc, NumParams, UsesADL);
5887     }
5888     // We can now handle the nulled arguments for the default arguments.
5889     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5890   }
5891 
5892   // Bail out early if calling a builtin with custom type checking.
5893   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5894     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5895 
5896   if (getLangOpts().CUDA) {
5897     if (Config) {
5898       // CUDA: Kernel calls must be to global functions
5899       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5900         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5901             << FDecl << Fn->getSourceRange());
5902 
5903       // CUDA: Kernel function must have 'void' return type
5904       if (!FuncT->getReturnType()->isVoidType() &&
5905           !FuncT->getReturnType()->getAs<AutoType>() &&
5906           !FuncT->getReturnType()->isInstantiationDependentType())
5907         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5908             << Fn->getType() << Fn->getSourceRange());
5909     } else {
5910       // CUDA: Calls to global functions must be configured
5911       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5912         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5913             << FDecl << Fn->getSourceRange());
5914     }
5915   }
5916 
5917   // Check for a valid return type
5918   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5919                           FDecl))
5920     return ExprError();
5921 
5922   // We know the result type of the call, set it.
5923   TheCall->setType(FuncT->getCallResultType(Context));
5924   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5925 
5926   if (Proto) {
5927     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5928                                 IsExecConfig))
5929       return ExprError();
5930   } else {
5931     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5932 
5933     if (FDecl) {
5934       // Check if we have too few/too many template arguments, based
5935       // on our knowledge of the function definition.
5936       const FunctionDecl *Def = nullptr;
5937       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5938         Proto = Def->getType()->getAs<FunctionProtoType>();
5939        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5940           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5941           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5942       }
5943 
5944       // If the function we're calling isn't a function prototype, but we have
5945       // a function prototype from a prior declaratiom, use that prototype.
5946       if (!FDecl->hasPrototype())
5947         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5948     }
5949 
5950     // Promote the arguments (C99 6.5.2.2p6).
5951     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5952       Expr *Arg = Args[i];
5953 
5954       if (Proto && i < Proto->getNumParams()) {
5955         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5956             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5957         ExprResult ArgE =
5958             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5959         if (ArgE.isInvalid())
5960           return true;
5961 
5962         Arg = ArgE.getAs<Expr>();
5963 
5964       } else {
5965         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5966 
5967         if (ArgE.isInvalid())
5968           return true;
5969 
5970         Arg = ArgE.getAs<Expr>();
5971       }
5972 
5973       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5974                               diag::err_call_incomplete_argument, Arg))
5975         return ExprError();
5976 
5977       TheCall->setArg(i, Arg);
5978     }
5979   }
5980 
5981   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5982     if (!Method->isStatic())
5983       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5984         << Fn->getSourceRange());
5985 
5986   // Check for sentinels
5987   if (NDecl)
5988     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5989 
5990   // Do special checking on direct calls to functions.
5991   if (FDecl) {
5992     if (CheckFunctionCall(FDecl, TheCall, Proto))
5993       return ExprError();
5994 
5995     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5996 
5997     if (BuiltinID)
5998       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5999   } else if (NDecl) {
6000     if (CheckPointerCall(NDecl, TheCall, Proto))
6001       return ExprError();
6002   } else {
6003     if (CheckOtherCall(TheCall, Proto))
6004       return ExprError();
6005   }
6006 
6007   return MaybeBindToTemporary(TheCall);
6008 }
6009 
6010 ExprResult
6011 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6012                            SourceLocation RParenLoc, Expr *InitExpr) {
6013   assert(Ty && "ActOnCompoundLiteral(): missing type");
6014   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6015 
6016   TypeSourceInfo *TInfo;
6017   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6018   if (!TInfo)
6019     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6020 
6021   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6022 }
6023 
6024 ExprResult
6025 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6026                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6027   QualType literalType = TInfo->getType();
6028 
6029   if (literalType->isArrayType()) {
6030     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6031           diag::err_illegal_decl_array_incomplete_type,
6032           SourceRange(LParenLoc,
6033                       LiteralExpr->getSourceRange().getEnd())))
6034       return ExprError();
6035     if (literalType->isVariableArrayType())
6036       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6037         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6038   } else if (!literalType->isDependentType() &&
6039              RequireCompleteType(LParenLoc, literalType,
6040                diag::err_typecheck_decl_incomplete_type,
6041                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6042     return ExprError();
6043 
6044   InitializedEntity Entity
6045     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6046   InitializationKind Kind
6047     = InitializationKind::CreateCStyleCast(LParenLoc,
6048                                            SourceRange(LParenLoc, RParenLoc),
6049                                            /*InitList=*/true);
6050   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6051   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6052                                       &literalType);
6053   if (Result.isInvalid())
6054     return ExprError();
6055   LiteralExpr = Result.get();
6056 
6057   bool isFileScope = !CurContext->isFunctionOrMethod();
6058 
6059   // In C, compound literals are l-values for some reason.
6060   // For GCC compatibility, in C++, file-scope array compound literals with
6061   // constant initializers are also l-values, and compound literals are
6062   // otherwise prvalues.
6063   //
6064   // (GCC also treats C++ list-initialized file-scope array prvalues with
6065   // constant initializers as l-values, but that's non-conforming, so we don't
6066   // follow it there.)
6067   //
6068   // FIXME: It would be better to handle the lvalue cases as materializing and
6069   // lifetime-extending a temporary object, but our materialized temporaries
6070   // representation only supports lifetime extension from a variable, not "out
6071   // of thin air".
6072   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6073   // is bound to the result of applying array-to-pointer decay to the compound
6074   // literal.
6075   // FIXME: GCC supports compound literals of reference type, which should
6076   // obviously have a value kind derived from the kind of reference involved.
6077   ExprValueKind VK =
6078       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6079           ? VK_RValue
6080           : VK_LValue;
6081 
6082   if (isFileScope)
6083     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6084       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6085         Expr *Init = ILE->getInit(i);
6086         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6087       }
6088 
6089   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6090                                               VK, LiteralExpr, isFileScope);
6091   if (isFileScope) {
6092     if (!LiteralExpr->isTypeDependent() &&
6093         !LiteralExpr->isValueDependent() &&
6094         !literalType->isDependentType()) // C99 6.5.2.5p3
6095       if (CheckForConstantInitializer(LiteralExpr, literalType))
6096         return ExprError();
6097   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6098              literalType.getAddressSpace() != LangAS::Default) {
6099     // Embedded-C extensions to C99 6.5.2.5:
6100     //   "If the compound literal occurs inside the body of a function, the
6101     //   type name shall not be qualified by an address-space qualifier."
6102     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6103       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6104     return ExprError();
6105   }
6106 
6107   // Compound literals that have automatic storage duration are destroyed at
6108   // the end of the scope. Emit diagnostics if it is or contains a C union type
6109   // that is non-trivial to destruct.
6110   if (!isFileScope)
6111     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6112       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6113                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6114 
6115   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6116       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6117     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6118                                        E->getInitializer()->getExprLoc());
6119 
6120   return MaybeBindToTemporary(E);
6121 }
6122 
6123 ExprResult
6124 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6125                     SourceLocation RBraceLoc) {
6126   // Only produce each kind of designated initialization diagnostic once.
6127   SourceLocation FirstDesignator;
6128   bool DiagnosedArrayDesignator = false;
6129   bool DiagnosedNestedDesignator = false;
6130   bool DiagnosedMixedDesignator = false;
6131 
6132   // Check that any designated initializers are syntactically valid in the
6133   // current language mode.
6134   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6135     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6136       if (FirstDesignator.isInvalid())
6137         FirstDesignator = DIE->getBeginLoc();
6138 
6139       if (!getLangOpts().CPlusPlus)
6140         break;
6141 
6142       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6143         DiagnosedNestedDesignator = true;
6144         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6145           << DIE->getDesignatorsSourceRange();
6146       }
6147 
6148       for (auto &Desig : DIE->designators()) {
6149         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6150           DiagnosedArrayDesignator = true;
6151           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6152             << Desig.getSourceRange();
6153         }
6154       }
6155 
6156       if (!DiagnosedMixedDesignator &&
6157           !isa<DesignatedInitExpr>(InitArgList[0])) {
6158         DiagnosedMixedDesignator = true;
6159         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6160           << DIE->getSourceRange();
6161         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6162           << InitArgList[0]->getSourceRange();
6163       }
6164     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6165                isa<DesignatedInitExpr>(InitArgList[0])) {
6166       DiagnosedMixedDesignator = true;
6167       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6168       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6169         << DIE->getSourceRange();
6170       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6171         << InitArgList[I]->getSourceRange();
6172     }
6173   }
6174 
6175   if (FirstDesignator.isValid()) {
6176     // Only diagnose designated initiaization as a C++20 extension if we didn't
6177     // already diagnose use of (non-C++20) C99 designator syntax.
6178     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6179         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6180       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6181                                 ? diag::warn_cxx17_compat_designated_init
6182                                 : diag::ext_cxx_designated_init);
6183     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6184       Diag(FirstDesignator, diag::ext_designated_init);
6185     }
6186   }
6187 
6188   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6189 }
6190 
6191 ExprResult
6192 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6193                     SourceLocation RBraceLoc) {
6194   // Semantic analysis for initializers is done by ActOnDeclarator() and
6195   // CheckInitializer() - it requires knowledge of the object being initialized.
6196 
6197   // Immediately handle non-overload placeholders.  Overloads can be
6198   // resolved contextually, but everything else here can't.
6199   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6200     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6201       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6202 
6203       // Ignore failures; dropping the entire initializer list because
6204       // of one failure would be terrible for indexing/etc.
6205       if (result.isInvalid()) continue;
6206 
6207       InitArgList[I] = result.get();
6208     }
6209   }
6210 
6211   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6212                                                RBraceLoc);
6213   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6214   return E;
6215 }
6216 
6217 /// Do an explicit extend of the given block pointer if we're in ARC.
6218 void Sema::maybeExtendBlockObject(ExprResult &E) {
6219   assert(E.get()->getType()->isBlockPointerType());
6220   assert(E.get()->isRValue());
6221 
6222   // Only do this in an r-value context.
6223   if (!getLangOpts().ObjCAutoRefCount) return;
6224 
6225   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6226                                CK_ARCExtendBlockObject, E.get(),
6227                                /*base path*/ nullptr, VK_RValue);
6228   Cleanup.setExprNeedsCleanups(true);
6229 }
6230 
6231 /// Prepare a conversion of the given expression to an ObjC object
6232 /// pointer type.
6233 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6234   QualType type = E.get()->getType();
6235   if (type->isObjCObjectPointerType()) {
6236     return CK_BitCast;
6237   } else if (type->isBlockPointerType()) {
6238     maybeExtendBlockObject(E);
6239     return CK_BlockPointerToObjCPointerCast;
6240   } else {
6241     assert(type->isPointerType());
6242     return CK_CPointerToObjCPointerCast;
6243   }
6244 }
6245 
6246 /// Prepares for a scalar cast, performing all the necessary stages
6247 /// except the final cast and returning the kind required.
6248 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6249   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6250   // Also, callers should have filtered out the invalid cases with
6251   // pointers.  Everything else should be possible.
6252 
6253   QualType SrcTy = Src.get()->getType();
6254   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6255     return CK_NoOp;
6256 
6257   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6258   case Type::STK_MemberPointer:
6259     llvm_unreachable("member pointer type in C");
6260 
6261   case Type::STK_CPointer:
6262   case Type::STK_BlockPointer:
6263   case Type::STK_ObjCObjectPointer:
6264     switch (DestTy->getScalarTypeKind()) {
6265     case Type::STK_CPointer: {
6266       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6267       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6268       if (SrcAS != DestAS)
6269         return CK_AddressSpaceConversion;
6270       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6271         return CK_NoOp;
6272       return CK_BitCast;
6273     }
6274     case Type::STK_BlockPointer:
6275       return (SrcKind == Type::STK_BlockPointer
6276                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6277     case Type::STK_ObjCObjectPointer:
6278       if (SrcKind == Type::STK_ObjCObjectPointer)
6279         return CK_BitCast;
6280       if (SrcKind == Type::STK_CPointer)
6281         return CK_CPointerToObjCPointerCast;
6282       maybeExtendBlockObject(Src);
6283       return CK_BlockPointerToObjCPointerCast;
6284     case Type::STK_Bool:
6285       return CK_PointerToBoolean;
6286     case Type::STK_Integral:
6287       return CK_PointerToIntegral;
6288     case Type::STK_Floating:
6289     case Type::STK_FloatingComplex:
6290     case Type::STK_IntegralComplex:
6291     case Type::STK_MemberPointer:
6292     case Type::STK_FixedPoint:
6293       llvm_unreachable("illegal cast from pointer");
6294     }
6295     llvm_unreachable("Should have returned before this");
6296 
6297   case Type::STK_FixedPoint:
6298     switch (DestTy->getScalarTypeKind()) {
6299     case Type::STK_FixedPoint:
6300       return CK_FixedPointCast;
6301     case Type::STK_Bool:
6302       return CK_FixedPointToBoolean;
6303     case Type::STK_Integral:
6304       return CK_FixedPointToIntegral;
6305     case Type::STK_Floating:
6306     case Type::STK_IntegralComplex:
6307     case Type::STK_FloatingComplex:
6308       Diag(Src.get()->getExprLoc(),
6309            diag::err_unimplemented_conversion_with_fixed_point_type)
6310           << DestTy;
6311       return CK_IntegralCast;
6312     case Type::STK_CPointer:
6313     case Type::STK_ObjCObjectPointer:
6314     case Type::STK_BlockPointer:
6315     case Type::STK_MemberPointer:
6316       llvm_unreachable("illegal cast to pointer type");
6317     }
6318     llvm_unreachable("Should have returned before this");
6319 
6320   case Type::STK_Bool: // casting from bool is like casting from an integer
6321   case Type::STK_Integral:
6322     switch (DestTy->getScalarTypeKind()) {
6323     case Type::STK_CPointer:
6324     case Type::STK_ObjCObjectPointer:
6325     case Type::STK_BlockPointer:
6326       if (Src.get()->isNullPointerConstant(Context,
6327                                            Expr::NPC_ValueDependentIsNull))
6328         return CK_NullToPointer;
6329       return CK_IntegralToPointer;
6330     case Type::STK_Bool:
6331       return CK_IntegralToBoolean;
6332     case Type::STK_Integral:
6333       return CK_IntegralCast;
6334     case Type::STK_Floating:
6335       return CK_IntegralToFloating;
6336     case Type::STK_IntegralComplex:
6337       Src = ImpCastExprToType(Src.get(),
6338                       DestTy->castAs<ComplexType>()->getElementType(),
6339                       CK_IntegralCast);
6340       return CK_IntegralRealToComplex;
6341     case Type::STK_FloatingComplex:
6342       Src = ImpCastExprToType(Src.get(),
6343                       DestTy->castAs<ComplexType>()->getElementType(),
6344                       CK_IntegralToFloating);
6345       return CK_FloatingRealToComplex;
6346     case Type::STK_MemberPointer:
6347       llvm_unreachable("member pointer type in C");
6348     case Type::STK_FixedPoint:
6349       return CK_IntegralToFixedPoint;
6350     }
6351     llvm_unreachable("Should have returned before this");
6352 
6353   case Type::STK_Floating:
6354     switch (DestTy->getScalarTypeKind()) {
6355     case Type::STK_Floating:
6356       return CK_FloatingCast;
6357     case Type::STK_Bool:
6358       return CK_FloatingToBoolean;
6359     case Type::STK_Integral:
6360       return CK_FloatingToIntegral;
6361     case Type::STK_FloatingComplex:
6362       Src = ImpCastExprToType(Src.get(),
6363                               DestTy->castAs<ComplexType>()->getElementType(),
6364                               CK_FloatingCast);
6365       return CK_FloatingRealToComplex;
6366     case Type::STK_IntegralComplex:
6367       Src = ImpCastExprToType(Src.get(),
6368                               DestTy->castAs<ComplexType>()->getElementType(),
6369                               CK_FloatingToIntegral);
6370       return CK_IntegralRealToComplex;
6371     case Type::STK_CPointer:
6372     case Type::STK_ObjCObjectPointer:
6373     case Type::STK_BlockPointer:
6374       llvm_unreachable("valid float->pointer cast?");
6375     case Type::STK_MemberPointer:
6376       llvm_unreachable("member pointer type in C");
6377     case Type::STK_FixedPoint:
6378       Diag(Src.get()->getExprLoc(),
6379            diag::err_unimplemented_conversion_with_fixed_point_type)
6380           << SrcTy;
6381       return CK_IntegralCast;
6382     }
6383     llvm_unreachable("Should have returned before this");
6384 
6385   case Type::STK_FloatingComplex:
6386     switch (DestTy->getScalarTypeKind()) {
6387     case Type::STK_FloatingComplex:
6388       return CK_FloatingComplexCast;
6389     case Type::STK_IntegralComplex:
6390       return CK_FloatingComplexToIntegralComplex;
6391     case Type::STK_Floating: {
6392       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6393       if (Context.hasSameType(ET, DestTy))
6394         return CK_FloatingComplexToReal;
6395       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6396       return CK_FloatingCast;
6397     }
6398     case Type::STK_Bool:
6399       return CK_FloatingComplexToBoolean;
6400     case Type::STK_Integral:
6401       Src = ImpCastExprToType(Src.get(),
6402                               SrcTy->castAs<ComplexType>()->getElementType(),
6403                               CK_FloatingComplexToReal);
6404       return CK_FloatingToIntegral;
6405     case Type::STK_CPointer:
6406     case Type::STK_ObjCObjectPointer:
6407     case Type::STK_BlockPointer:
6408       llvm_unreachable("valid complex float->pointer cast?");
6409     case Type::STK_MemberPointer:
6410       llvm_unreachable("member pointer type in C");
6411     case Type::STK_FixedPoint:
6412       Diag(Src.get()->getExprLoc(),
6413            diag::err_unimplemented_conversion_with_fixed_point_type)
6414           << SrcTy;
6415       return CK_IntegralCast;
6416     }
6417     llvm_unreachable("Should have returned before this");
6418 
6419   case Type::STK_IntegralComplex:
6420     switch (DestTy->getScalarTypeKind()) {
6421     case Type::STK_FloatingComplex:
6422       return CK_IntegralComplexToFloatingComplex;
6423     case Type::STK_IntegralComplex:
6424       return CK_IntegralComplexCast;
6425     case Type::STK_Integral: {
6426       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6427       if (Context.hasSameType(ET, DestTy))
6428         return CK_IntegralComplexToReal;
6429       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6430       return CK_IntegralCast;
6431     }
6432     case Type::STK_Bool:
6433       return CK_IntegralComplexToBoolean;
6434     case Type::STK_Floating:
6435       Src = ImpCastExprToType(Src.get(),
6436                               SrcTy->castAs<ComplexType>()->getElementType(),
6437                               CK_IntegralComplexToReal);
6438       return CK_IntegralToFloating;
6439     case Type::STK_CPointer:
6440     case Type::STK_ObjCObjectPointer:
6441     case Type::STK_BlockPointer:
6442       llvm_unreachable("valid complex int->pointer cast?");
6443     case Type::STK_MemberPointer:
6444       llvm_unreachable("member pointer type in C");
6445     case Type::STK_FixedPoint:
6446       Diag(Src.get()->getExprLoc(),
6447            diag::err_unimplemented_conversion_with_fixed_point_type)
6448           << SrcTy;
6449       return CK_IntegralCast;
6450     }
6451     llvm_unreachable("Should have returned before this");
6452   }
6453 
6454   llvm_unreachable("Unhandled scalar cast");
6455 }
6456 
6457 static bool breakDownVectorType(QualType type, uint64_t &len,
6458                                 QualType &eltType) {
6459   // Vectors are simple.
6460   if (const VectorType *vecType = type->getAs<VectorType>()) {
6461     len = vecType->getNumElements();
6462     eltType = vecType->getElementType();
6463     assert(eltType->isScalarType());
6464     return true;
6465   }
6466 
6467   // We allow lax conversion to and from non-vector types, but only if
6468   // they're real types (i.e. non-complex, non-pointer scalar types).
6469   if (!type->isRealType()) return false;
6470 
6471   len = 1;
6472   eltType = type;
6473   return true;
6474 }
6475 
6476 /// Are the two types lax-compatible vector types?  That is, given
6477 /// that one of them is a vector, do they have equal storage sizes,
6478 /// where the storage size is the number of elements times the element
6479 /// size?
6480 ///
6481 /// This will also return false if either of the types is neither a
6482 /// vector nor a real type.
6483 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6484   assert(destTy->isVectorType() || srcTy->isVectorType());
6485 
6486   // Disallow lax conversions between scalars and ExtVectors (these
6487   // conversions are allowed for other vector types because common headers
6488   // depend on them).  Most scalar OP ExtVector cases are handled by the
6489   // splat path anyway, which does what we want (convert, not bitcast).
6490   // What this rules out for ExtVectors is crazy things like char4*float.
6491   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6492   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6493 
6494   uint64_t srcLen, destLen;
6495   QualType srcEltTy, destEltTy;
6496   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6497   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6498 
6499   // ASTContext::getTypeSize will return the size rounded up to a
6500   // power of 2, so instead of using that, we need to use the raw
6501   // element size multiplied by the element count.
6502   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6503   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6504 
6505   return (srcLen * srcEltSize == destLen * destEltSize);
6506 }
6507 
6508 /// Is this a legal conversion between two types, one of which is
6509 /// known to be a vector type?
6510 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6511   assert(destTy->isVectorType() || srcTy->isVectorType());
6512 
6513   switch (Context.getLangOpts().getLaxVectorConversions()) {
6514   case LangOptions::LaxVectorConversionKind::None:
6515     return false;
6516 
6517   case LangOptions::LaxVectorConversionKind::Integer:
6518     if (!srcTy->isIntegralOrEnumerationType()) {
6519       auto *Vec = srcTy->getAs<VectorType>();
6520       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6521         return false;
6522     }
6523     if (!destTy->isIntegralOrEnumerationType()) {
6524       auto *Vec = destTy->getAs<VectorType>();
6525       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6526         return false;
6527     }
6528     // OK, integer (vector) -> integer (vector) bitcast.
6529     break;
6530 
6531     case LangOptions::LaxVectorConversionKind::All:
6532     break;
6533   }
6534 
6535   return areLaxCompatibleVectorTypes(srcTy, destTy);
6536 }
6537 
6538 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6539                            CastKind &Kind) {
6540   assert(VectorTy->isVectorType() && "Not a vector type!");
6541 
6542   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6543     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6544       return Diag(R.getBegin(),
6545                   Ty->isVectorType() ?
6546                   diag::err_invalid_conversion_between_vectors :
6547                   diag::err_invalid_conversion_between_vector_and_integer)
6548         << VectorTy << Ty << R;
6549   } else
6550     return Diag(R.getBegin(),
6551                 diag::err_invalid_conversion_between_vector_and_scalar)
6552       << VectorTy << Ty << R;
6553 
6554   Kind = CK_BitCast;
6555   return false;
6556 }
6557 
6558 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6559   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6560 
6561   if (DestElemTy == SplattedExpr->getType())
6562     return SplattedExpr;
6563 
6564   assert(DestElemTy->isFloatingType() ||
6565          DestElemTy->isIntegralOrEnumerationType());
6566 
6567   CastKind CK;
6568   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6569     // OpenCL requires that we convert `true` boolean expressions to -1, but
6570     // only when splatting vectors.
6571     if (DestElemTy->isFloatingType()) {
6572       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6573       // in two steps: boolean to signed integral, then to floating.
6574       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6575                                                  CK_BooleanToSignedIntegral);
6576       SplattedExpr = CastExprRes.get();
6577       CK = CK_IntegralToFloating;
6578     } else {
6579       CK = CK_BooleanToSignedIntegral;
6580     }
6581   } else {
6582     ExprResult CastExprRes = SplattedExpr;
6583     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6584     if (CastExprRes.isInvalid())
6585       return ExprError();
6586     SplattedExpr = CastExprRes.get();
6587   }
6588   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6589 }
6590 
6591 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6592                                     Expr *CastExpr, CastKind &Kind) {
6593   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6594 
6595   QualType SrcTy = CastExpr->getType();
6596 
6597   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6598   // an ExtVectorType.
6599   // In OpenCL, casts between vectors of different types are not allowed.
6600   // (See OpenCL 6.2).
6601   if (SrcTy->isVectorType()) {
6602     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6603         (getLangOpts().OpenCL &&
6604          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6605       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6606         << DestTy << SrcTy << R;
6607       return ExprError();
6608     }
6609     Kind = CK_BitCast;
6610     return CastExpr;
6611   }
6612 
6613   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6614   // conversion will take place first from scalar to elt type, and then
6615   // splat from elt type to vector.
6616   if (SrcTy->isPointerType())
6617     return Diag(R.getBegin(),
6618                 diag::err_invalid_conversion_between_vector_and_scalar)
6619       << DestTy << SrcTy << R;
6620 
6621   Kind = CK_VectorSplat;
6622   return prepareVectorSplat(DestTy, CastExpr);
6623 }
6624 
6625 ExprResult
6626 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6627                     Declarator &D, ParsedType &Ty,
6628                     SourceLocation RParenLoc, Expr *CastExpr) {
6629   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6630          "ActOnCastExpr(): missing type or expr");
6631 
6632   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6633   if (D.isInvalidType())
6634     return ExprError();
6635 
6636   if (getLangOpts().CPlusPlus) {
6637     // Check that there are no default arguments (C++ only).
6638     CheckExtraCXXDefaultArguments(D);
6639   } else {
6640     // Make sure any TypoExprs have been dealt with.
6641     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6642     if (!Res.isUsable())
6643       return ExprError();
6644     CastExpr = Res.get();
6645   }
6646 
6647   checkUnusedDeclAttributes(D);
6648 
6649   QualType castType = castTInfo->getType();
6650   Ty = CreateParsedType(castType, castTInfo);
6651 
6652   bool isVectorLiteral = false;
6653 
6654   // Check for an altivec or OpenCL literal,
6655   // i.e. all the elements are integer constants.
6656   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6657   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6658   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6659        && castType->isVectorType() && (PE || PLE)) {
6660     if (PLE && PLE->getNumExprs() == 0) {
6661       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6662       return ExprError();
6663     }
6664     if (PE || PLE->getNumExprs() == 1) {
6665       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6666       if (!E->getType()->isVectorType())
6667         isVectorLiteral = true;
6668     }
6669     else
6670       isVectorLiteral = true;
6671   }
6672 
6673   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6674   // then handle it as such.
6675   if (isVectorLiteral)
6676     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6677 
6678   // If the Expr being casted is a ParenListExpr, handle it specially.
6679   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6680   // sequence of BinOp comma operators.
6681   if (isa<ParenListExpr>(CastExpr)) {
6682     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6683     if (Result.isInvalid()) return ExprError();
6684     CastExpr = Result.get();
6685   }
6686 
6687   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6688       !getSourceManager().isInSystemMacro(LParenLoc))
6689     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6690 
6691   CheckTollFreeBridgeCast(castType, CastExpr);
6692 
6693   CheckObjCBridgeRelatedCast(castType, CastExpr);
6694 
6695   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6696 
6697   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6698 }
6699 
6700 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6701                                     SourceLocation RParenLoc, Expr *E,
6702                                     TypeSourceInfo *TInfo) {
6703   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6704          "Expected paren or paren list expression");
6705 
6706   Expr **exprs;
6707   unsigned numExprs;
6708   Expr *subExpr;
6709   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6710   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6711     LiteralLParenLoc = PE->getLParenLoc();
6712     LiteralRParenLoc = PE->getRParenLoc();
6713     exprs = PE->getExprs();
6714     numExprs = PE->getNumExprs();
6715   } else { // isa<ParenExpr> by assertion at function entrance
6716     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6717     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6718     subExpr = cast<ParenExpr>(E)->getSubExpr();
6719     exprs = &subExpr;
6720     numExprs = 1;
6721   }
6722 
6723   QualType Ty = TInfo->getType();
6724   assert(Ty->isVectorType() && "Expected vector type");
6725 
6726   SmallVector<Expr *, 8> initExprs;
6727   const VectorType *VTy = Ty->castAs<VectorType>();
6728   unsigned numElems = VTy->getNumElements();
6729 
6730   // '(...)' form of vector initialization in AltiVec: the number of
6731   // initializers must be one or must match the size of the vector.
6732   // If a single value is specified in the initializer then it will be
6733   // replicated to all the components of the vector
6734   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6735     // The number of initializers must be one or must match the size of the
6736     // vector. If a single value is specified in the initializer then it will
6737     // be replicated to all the components of the vector
6738     if (numExprs == 1) {
6739       QualType ElemTy = VTy->getElementType();
6740       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6741       if (Literal.isInvalid())
6742         return ExprError();
6743       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6744                                   PrepareScalarCast(Literal, ElemTy));
6745       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6746     }
6747     else if (numExprs < numElems) {
6748       Diag(E->getExprLoc(),
6749            diag::err_incorrect_number_of_vector_initializers);
6750       return ExprError();
6751     }
6752     else
6753       initExprs.append(exprs, exprs + numExprs);
6754   }
6755   else {
6756     // For OpenCL, when the number of initializers is a single value,
6757     // it will be replicated to all components of the vector.
6758     if (getLangOpts().OpenCL &&
6759         VTy->getVectorKind() == VectorType::GenericVector &&
6760         numExprs == 1) {
6761         QualType ElemTy = VTy->getElementType();
6762         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6763         if (Literal.isInvalid())
6764           return ExprError();
6765         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6766                                     PrepareScalarCast(Literal, ElemTy));
6767         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6768     }
6769 
6770     initExprs.append(exprs, exprs + numExprs);
6771   }
6772   // FIXME: This means that pretty-printing the final AST will produce curly
6773   // braces instead of the original commas.
6774   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6775                                                    initExprs, LiteralRParenLoc);
6776   initE->setType(Ty);
6777   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6778 }
6779 
6780 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6781 /// the ParenListExpr into a sequence of comma binary operators.
6782 ExprResult
6783 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6784   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6785   if (!E)
6786     return OrigExpr;
6787 
6788   ExprResult Result(E->getExpr(0));
6789 
6790   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6791     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6792                         E->getExpr(i));
6793 
6794   if (Result.isInvalid()) return ExprError();
6795 
6796   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6797 }
6798 
6799 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6800                                     SourceLocation R,
6801                                     MultiExprArg Val) {
6802   return ParenListExpr::Create(Context, L, Val, R);
6803 }
6804 
6805 /// Emit a specialized diagnostic when one expression is a null pointer
6806 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6807 /// emitted.
6808 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6809                                       SourceLocation QuestionLoc) {
6810   Expr *NullExpr = LHSExpr;
6811   Expr *NonPointerExpr = RHSExpr;
6812   Expr::NullPointerConstantKind NullKind =
6813       NullExpr->isNullPointerConstant(Context,
6814                                       Expr::NPC_ValueDependentIsNotNull);
6815 
6816   if (NullKind == Expr::NPCK_NotNull) {
6817     NullExpr = RHSExpr;
6818     NonPointerExpr = LHSExpr;
6819     NullKind =
6820         NullExpr->isNullPointerConstant(Context,
6821                                         Expr::NPC_ValueDependentIsNotNull);
6822   }
6823 
6824   if (NullKind == Expr::NPCK_NotNull)
6825     return false;
6826 
6827   if (NullKind == Expr::NPCK_ZeroExpression)
6828     return false;
6829 
6830   if (NullKind == Expr::NPCK_ZeroLiteral) {
6831     // In this case, check to make sure that we got here from a "NULL"
6832     // string in the source code.
6833     NullExpr = NullExpr->IgnoreParenImpCasts();
6834     SourceLocation loc = NullExpr->getExprLoc();
6835     if (!findMacroSpelling(loc, "NULL"))
6836       return false;
6837   }
6838 
6839   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6840   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6841       << NonPointerExpr->getType() << DiagType
6842       << NonPointerExpr->getSourceRange();
6843   return true;
6844 }
6845 
6846 /// Return false if the condition expression is valid, true otherwise.
6847 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6848   QualType CondTy = Cond->getType();
6849 
6850   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6851   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6852     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6853       << CondTy << Cond->getSourceRange();
6854     return true;
6855   }
6856 
6857   // C99 6.5.15p2
6858   if (CondTy->isScalarType()) return false;
6859 
6860   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6861     << CondTy << Cond->getSourceRange();
6862   return true;
6863 }
6864 
6865 /// Handle when one or both operands are void type.
6866 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6867                                          ExprResult &RHS) {
6868     Expr *LHSExpr = LHS.get();
6869     Expr *RHSExpr = RHS.get();
6870 
6871     if (!LHSExpr->getType()->isVoidType())
6872       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6873           << RHSExpr->getSourceRange();
6874     if (!RHSExpr->getType()->isVoidType())
6875       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6876           << LHSExpr->getSourceRange();
6877     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6878     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6879     return S.Context.VoidTy;
6880 }
6881 
6882 /// Return false if the NullExpr can be promoted to PointerTy,
6883 /// true otherwise.
6884 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6885                                         QualType PointerTy) {
6886   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6887       !NullExpr.get()->isNullPointerConstant(S.Context,
6888                                             Expr::NPC_ValueDependentIsNull))
6889     return true;
6890 
6891   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6892   return false;
6893 }
6894 
6895 /// Checks compatibility between two pointers and return the resulting
6896 /// type.
6897 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6898                                                      ExprResult &RHS,
6899                                                      SourceLocation Loc) {
6900   QualType LHSTy = LHS.get()->getType();
6901   QualType RHSTy = RHS.get()->getType();
6902 
6903   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6904     // Two identical pointers types are always compatible.
6905     return LHSTy;
6906   }
6907 
6908   QualType lhptee, rhptee;
6909 
6910   // Get the pointee types.
6911   bool IsBlockPointer = false;
6912   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6913     lhptee = LHSBTy->getPointeeType();
6914     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6915     IsBlockPointer = true;
6916   } else {
6917     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6918     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6919   }
6920 
6921   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6922   // differently qualified versions of compatible types, the result type is
6923   // a pointer to an appropriately qualified version of the composite
6924   // type.
6925 
6926   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6927   // clause doesn't make sense for our extensions. E.g. address space 2 should
6928   // be incompatible with address space 3: they may live on different devices or
6929   // anything.
6930   Qualifiers lhQual = lhptee.getQualifiers();
6931   Qualifiers rhQual = rhptee.getQualifiers();
6932 
6933   LangAS ResultAddrSpace = LangAS::Default;
6934   LangAS LAddrSpace = lhQual.getAddressSpace();
6935   LangAS RAddrSpace = rhQual.getAddressSpace();
6936 
6937   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6938   // spaces is disallowed.
6939   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6940     ResultAddrSpace = LAddrSpace;
6941   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6942     ResultAddrSpace = RAddrSpace;
6943   else {
6944     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6945         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6946         << RHS.get()->getSourceRange();
6947     return QualType();
6948   }
6949 
6950   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6951   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6952   lhQual.removeCVRQualifiers();
6953   rhQual.removeCVRQualifiers();
6954 
6955   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6956   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6957   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6958   // qual types are compatible iff
6959   //  * corresponded types are compatible
6960   //  * CVR qualifiers are equal
6961   //  * address spaces are equal
6962   // Thus for conditional operator we merge CVR and address space unqualified
6963   // pointees and if there is a composite type we return a pointer to it with
6964   // merged qualifiers.
6965   LHSCastKind =
6966       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6967   RHSCastKind =
6968       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6969   lhQual.removeAddressSpace();
6970   rhQual.removeAddressSpace();
6971 
6972   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6973   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6974 
6975   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6976 
6977   if (CompositeTy.isNull()) {
6978     // In this situation, we assume void* type. No especially good
6979     // reason, but this is what gcc does, and we do have to pick
6980     // to get a consistent AST.
6981     QualType incompatTy;
6982     incompatTy = S.Context.getPointerType(
6983         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6984     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6985     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6986 
6987     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6988     // for casts between types with incompatible address space qualifiers.
6989     // For the following code the compiler produces casts between global and
6990     // local address spaces of the corresponded innermost pointees:
6991     // local int *global *a;
6992     // global int *global *b;
6993     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6994     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6995         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6996         << RHS.get()->getSourceRange();
6997 
6998     return incompatTy;
6999   }
7000 
7001   // The pointer types are compatible.
7002   // In case of OpenCL ResultTy should have the address space qualifier
7003   // which is a superset of address spaces of both the 2nd and the 3rd
7004   // operands of the conditional operator.
7005   QualType ResultTy = [&, ResultAddrSpace]() {
7006     if (S.getLangOpts().OpenCL) {
7007       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7008       CompositeQuals.setAddressSpace(ResultAddrSpace);
7009       return S.Context
7010           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7011           .withCVRQualifiers(MergedCVRQual);
7012     }
7013     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7014   }();
7015   if (IsBlockPointer)
7016     ResultTy = S.Context.getBlockPointerType(ResultTy);
7017   else
7018     ResultTy = S.Context.getPointerType(ResultTy);
7019 
7020   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7021   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7022   return ResultTy;
7023 }
7024 
7025 /// Return the resulting type when the operands are both block pointers.
7026 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7027                                                           ExprResult &LHS,
7028                                                           ExprResult &RHS,
7029                                                           SourceLocation Loc) {
7030   QualType LHSTy = LHS.get()->getType();
7031   QualType RHSTy = RHS.get()->getType();
7032 
7033   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7034     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7035       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7036       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7037       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7038       return destType;
7039     }
7040     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7041       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7042       << RHS.get()->getSourceRange();
7043     return QualType();
7044   }
7045 
7046   // We have 2 block pointer types.
7047   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7048 }
7049 
7050 /// Return the resulting type when the operands are both pointers.
7051 static QualType
7052 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7053                                             ExprResult &RHS,
7054                                             SourceLocation Loc) {
7055   // get the pointer types
7056   QualType LHSTy = LHS.get()->getType();
7057   QualType RHSTy = RHS.get()->getType();
7058 
7059   // get the "pointed to" types
7060   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7061   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7062 
7063   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7064   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7065     // Figure out necessary qualifiers (C99 6.5.15p6)
7066     QualType destPointee
7067       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7068     QualType destType = S.Context.getPointerType(destPointee);
7069     // Add qualifiers if necessary.
7070     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7071     // Promote to void*.
7072     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7073     return destType;
7074   }
7075   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7076     QualType destPointee
7077       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7078     QualType destType = S.Context.getPointerType(destPointee);
7079     // Add qualifiers if necessary.
7080     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7081     // Promote to void*.
7082     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7083     return destType;
7084   }
7085 
7086   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7087 }
7088 
7089 /// Return false if the first expression is not an integer and the second
7090 /// expression is not a pointer, true otherwise.
7091 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7092                                         Expr* PointerExpr, SourceLocation Loc,
7093                                         bool IsIntFirstExpr) {
7094   if (!PointerExpr->getType()->isPointerType() ||
7095       !Int.get()->getType()->isIntegerType())
7096     return false;
7097 
7098   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7099   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7100 
7101   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7102     << Expr1->getType() << Expr2->getType()
7103     << Expr1->getSourceRange() << Expr2->getSourceRange();
7104   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7105                             CK_IntegralToPointer);
7106   return true;
7107 }
7108 
7109 /// Simple conversion between integer and floating point types.
7110 ///
7111 /// Used when handling the OpenCL conditional operator where the
7112 /// condition is a vector while the other operands are scalar.
7113 ///
7114 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7115 /// types are either integer or floating type. Between the two
7116 /// operands, the type with the higher rank is defined as the "result
7117 /// type". The other operand needs to be promoted to the same type. No
7118 /// other type promotion is allowed. We cannot use
7119 /// UsualArithmeticConversions() for this purpose, since it always
7120 /// promotes promotable types.
7121 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7122                                             ExprResult &RHS,
7123                                             SourceLocation QuestionLoc) {
7124   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7125   if (LHS.isInvalid())
7126     return QualType();
7127   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7128   if (RHS.isInvalid())
7129     return QualType();
7130 
7131   // For conversion purposes, we ignore any qualifiers.
7132   // For example, "const float" and "float" are equivalent.
7133   QualType LHSType =
7134     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7135   QualType RHSType =
7136     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7137 
7138   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7139     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7140       << LHSType << LHS.get()->getSourceRange();
7141     return QualType();
7142   }
7143 
7144   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7145     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7146       << RHSType << RHS.get()->getSourceRange();
7147     return QualType();
7148   }
7149 
7150   // If both types are identical, no conversion is needed.
7151   if (LHSType == RHSType)
7152     return LHSType;
7153 
7154   // Now handle "real" floating types (i.e. float, double, long double).
7155   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7156     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7157                                  /*IsCompAssign = */ false);
7158 
7159   // Finally, we have two differing integer types.
7160   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7161   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7162 }
7163 
7164 /// Convert scalar operands to a vector that matches the
7165 ///        condition in length.
7166 ///
7167 /// Used when handling the OpenCL conditional operator where the
7168 /// condition is a vector while the other operands are scalar.
7169 ///
7170 /// We first compute the "result type" for the scalar operands
7171 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7172 /// into a vector of that type where the length matches the condition
7173 /// vector type. s6.11.6 requires that the element types of the result
7174 /// and the condition must have the same number of bits.
7175 static QualType
7176 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7177                               QualType CondTy, SourceLocation QuestionLoc) {
7178   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7179   if (ResTy.isNull()) return QualType();
7180 
7181   const VectorType *CV = CondTy->getAs<VectorType>();
7182   assert(CV);
7183 
7184   // Determine the vector result type
7185   unsigned NumElements = CV->getNumElements();
7186   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7187 
7188   // Ensure that all types have the same number of bits
7189   if (S.Context.getTypeSize(CV->getElementType())
7190       != S.Context.getTypeSize(ResTy)) {
7191     // Since VectorTy is created internally, it does not pretty print
7192     // with an OpenCL name. Instead, we just print a description.
7193     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7194     SmallString<64> Str;
7195     llvm::raw_svector_ostream OS(Str);
7196     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7197     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7198       << CondTy << OS.str();
7199     return QualType();
7200   }
7201 
7202   // Convert operands to the vector result type
7203   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7204   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7205 
7206   return VectorTy;
7207 }
7208 
7209 /// Return false if this is a valid OpenCL condition vector
7210 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7211                                        SourceLocation QuestionLoc) {
7212   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7213   // integral type.
7214   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7215   assert(CondTy);
7216   QualType EleTy = CondTy->getElementType();
7217   if (EleTy->isIntegerType()) return false;
7218 
7219   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7220     << Cond->getType() << Cond->getSourceRange();
7221   return true;
7222 }
7223 
7224 /// Return false if the vector condition type and the vector
7225 ///        result type are compatible.
7226 ///
7227 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7228 /// number of elements, and their element types have the same number
7229 /// of bits.
7230 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7231                               SourceLocation QuestionLoc) {
7232   const VectorType *CV = CondTy->getAs<VectorType>();
7233   const VectorType *RV = VecResTy->getAs<VectorType>();
7234   assert(CV && RV);
7235 
7236   if (CV->getNumElements() != RV->getNumElements()) {
7237     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7238       << CondTy << VecResTy;
7239     return true;
7240   }
7241 
7242   QualType CVE = CV->getElementType();
7243   QualType RVE = RV->getElementType();
7244 
7245   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7246     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7247       << CondTy << VecResTy;
7248     return true;
7249   }
7250 
7251   return false;
7252 }
7253 
7254 /// Return the resulting type for the conditional operator in
7255 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7256 ///        s6.3.i) when the condition is a vector type.
7257 static QualType
7258 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7259                              ExprResult &LHS, ExprResult &RHS,
7260                              SourceLocation QuestionLoc) {
7261   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7262   if (Cond.isInvalid())
7263     return QualType();
7264   QualType CondTy = Cond.get()->getType();
7265 
7266   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7267     return QualType();
7268 
7269   // If either operand is a vector then find the vector type of the
7270   // result as specified in OpenCL v1.1 s6.3.i.
7271   if (LHS.get()->getType()->isVectorType() ||
7272       RHS.get()->getType()->isVectorType()) {
7273     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7274                                               /*isCompAssign*/false,
7275                                               /*AllowBothBool*/true,
7276                                               /*AllowBoolConversions*/false);
7277     if (VecResTy.isNull()) return QualType();
7278     // The result type must match the condition type as specified in
7279     // OpenCL v1.1 s6.11.6.
7280     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7281       return QualType();
7282     return VecResTy;
7283   }
7284 
7285   // Both operands are scalar.
7286   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7287 }
7288 
7289 /// Return true if the Expr is block type
7290 static bool checkBlockType(Sema &S, const Expr *E) {
7291   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7292     QualType Ty = CE->getCallee()->getType();
7293     if (Ty->isBlockPointerType()) {
7294       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7295       return true;
7296     }
7297   }
7298   return false;
7299 }
7300 
7301 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7302 /// In that case, LHS = cond.
7303 /// C99 6.5.15
7304 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7305                                         ExprResult &RHS, ExprValueKind &VK,
7306                                         ExprObjectKind &OK,
7307                                         SourceLocation QuestionLoc) {
7308 
7309   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7310   if (!LHSResult.isUsable()) return QualType();
7311   LHS = LHSResult;
7312 
7313   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7314   if (!RHSResult.isUsable()) return QualType();
7315   RHS = RHSResult;
7316 
7317   // C++ is sufficiently different to merit its own checker.
7318   if (getLangOpts().CPlusPlus)
7319     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7320 
7321   VK = VK_RValue;
7322   OK = OK_Ordinary;
7323 
7324   // The OpenCL operator with a vector condition is sufficiently
7325   // different to merit its own checker.
7326   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7327     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7328 
7329   // First, check the condition.
7330   Cond = UsualUnaryConversions(Cond.get());
7331   if (Cond.isInvalid())
7332     return QualType();
7333   if (checkCondition(*this, Cond.get(), QuestionLoc))
7334     return QualType();
7335 
7336   // Now check the two expressions.
7337   if (LHS.get()->getType()->isVectorType() ||
7338       RHS.get()->getType()->isVectorType())
7339     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7340                                /*AllowBothBool*/true,
7341                                /*AllowBoolConversions*/false);
7342 
7343   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7344   if (LHS.isInvalid() || RHS.isInvalid())
7345     return QualType();
7346 
7347   QualType LHSTy = LHS.get()->getType();
7348   QualType RHSTy = RHS.get()->getType();
7349 
7350   // Diagnose attempts to convert between __float128 and long double where
7351   // such conversions currently can't be handled.
7352   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7353     Diag(QuestionLoc,
7354          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7355       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7356     return QualType();
7357   }
7358 
7359   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7360   // selection operator (?:).
7361   if (getLangOpts().OpenCL &&
7362       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7363     return QualType();
7364   }
7365 
7366   // If both operands have arithmetic type, do the usual arithmetic conversions
7367   // to find a common type: C99 6.5.15p3,5.
7368   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7369     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7370     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7371 
7372     return ResTy;
7373   }
7374 
7375   // If both operands are the same structure or union type, the result is that
7376   // type.
7377   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7378     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7379       if (LHSRT->getDecl() == RHSRT->getDecl())
7380         // "If both the operands have structure or union type, the result has
7381         // that type."  This implies that CV qualifiers are dropped.
7382         return LHSTy.getUnqualifiedType();
7383     // FIXME: Type of conditional expression must be complete in C mode.
7384   }
7385 
7386   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7387   // The following || allows only one side to be void (a GCC-ism).
7388   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7389     return checkConditionalVoidType(*this, LHS, RHS);
7390   }
7391 
7392   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7393   // the type of the other operand."
7394   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7395   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7396 
7397   // All objective-c pointer type analysis is done here.
7398   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7399                                                         QuestionLoc);
7400   if (LHS.isInvalid() || RHS.isInvalid())
7401     return QualType();
7402   if (!compositeType.isNull())
7403     return compositeType;
7404 
7405 
7406   // Handle block pointer types.
7407   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7408     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7409                                                      QuestionLoc);
7410 
7411   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7412   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7413     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7414                                                        QuestionLoc);
7415 
7416   // GCC compatibility: soften pointer/integer mismatch.  Note that
7417   // null pointers have been filtered out by this point.
7418   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7419       /*IsIntFirstExpr=*/true))
7420     return RHSTy;
7421   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7422       /*IsIntFirstExpr=*/false))
7423     return LHSTy;
7424 
7425   // Emit a better diagnostic if one of the expressions is a null pointer
7426   // constant and the other is not a pointer type. In this case, the user most
7427   // likely forgot to take the address of the other expression.
7428   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7429     return QualType();
7430 
7431   // Otherwise, the operands are not compatible.
7432   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7433     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7434     << RHS.get()->getSourceRange();
7435   return QualType();
7436 }
7437 
7438 /// FindCompositeObjCPointerType - Helper method to find composite type of
7439 /// two objective-c pointer types of the two input expressions.
7440 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7441                                             SourceLocation QuestionLoc) {
7442   QualType LHSTy = LHS.get()->getType();
7443   QualType RHSTy = RHS.get()->getType();
7444 
7445   // Handle things like Class and struct objc_class*.  Here we case the result
7446   // to the pseudo-builtin, because that will be implicitly cast back to the
7447   // redefinition type if an attempt is made to access its fields.
7448   if (LHSTy->isObjCClassType() &&
7449       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7450     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7451     return LHSTy;
7452   }
7453   if (RHSTy->isObjCClassType() &&
7454       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7455     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7456     return RHSTy;
7457   }
7458   // And the same for struct objc_object* / id
7459   if (LHSTy->isObjCIdType() &&
7460       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7461     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7462     return LHSTy;
7463   }
7464   if (RHSTy->isObjCIdType() &&
7465       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7466     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7467     return RHSTy;
7468   }
7469   // And the same for struct objc_selector* / SEL
7470   if (Context.isObjCSelType(LHSTy) &&
7471       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7472     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7473     return LHSTy;
7474   }
7475   if (Context.isObjCSelType(RHSTy) &&
7476       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7477     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7478     return RHSTy;
7479   }
7480   // Check constraints for Objective-C object pointers types.
7481   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7482 
7483     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7484       // Two identical object pointer types are always compatible.
7485       return LHSTy;
7486     }
7487     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7488     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7489     QualType compositeType = LHSTy;
7490 
7491     // If both operands are interfaces and either operand can be
7492     // assigned to the other, use that type as the composite
7493     // type. This allows
7494     //   xxx ? (A*) a : (B*) b
7495     // where B is a subclass of A.
7496     //
7497     // Additionally, as for assignment, if either type is 'id'
7498     // allow silent coercion. Finally, if the types are
7499     // incompatible then make sure to use 'id' as the composite
7500     // type so the result is acceptable for sending messages to.
7501 
7502     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7503     // It could return the composite type.
7504     if (!(compositeType =
7505           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7506       // Nothing more to do.
7507     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7508       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7509     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7510       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7511     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7512                 RHSOPT->isObjCQualifiedIdType()) &&
7513                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7514                                                          true)) {
7515       // Need to handle "id<xx>" explicitly.
7516       // GCC allows qualified id and any Objective-C type to devolve to
7517       // id. Currently localizing to here until clear this should be
7518       // part of ObjCQualifiedIdTypesAreCompatible.
7519       compositeType = Context.getObjCIdType();
7520     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7521       compositeType = Context.getObjCIdType();
7522     } else {
7523       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7524       << LHSTy << RHSTy
7525       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7526       QualType incompatTy = Context.getObjCIdType();
7527       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7528       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7529       return incompatTy;
7530     }
7531     // The object pointer types are compatible.
7532     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7533     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7534     return compositeType;
7535   }
7536   // Check Objective-C object pointer types and 'void *'
7537   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7538     if (getLangOpts().ObjCAutoRefCount) {
7539       // ARC forbids the implicit conversion of object pointers to 'void *',
7540       // so these types are not compatible.
7541       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7542           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7543       LHS = RHS = true;
7544       return QualType();
7545     }
7546     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7547     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7548     QualType destPointee
7549     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7550     QualType destType = Context.getPointerType(destPointee);
7551     // Add qualifiers if necessary.
7552     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7553     // Promote to void*.
7554     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7555     return destType;
7556   }
7557   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7558     if (getLangOpts().ObjCAutoRefCount) {
7559       // ARC forbids the implicit conversion of object pointers to 'void *',
7560       // so these types are not compatible.
7561       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7562           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7563       LHS = RHS = true;
7564       return QualType();
7565     }
7566     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7567     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7568     QualType destPointee
7569     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7570     QualType destType = Context.getPointerType(destPointee);
7571     // Add qualifiers if necessary.
7572     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7573     // Promote to void*.
7574     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7575     return destType;
7576   }
7577   return QualType();
7578 }
7579 
7580 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7581 /// ParenRange in parentheses.
7582 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7583                                const PartialDiagnostic &Note,
7584                                SourceRange ParenRange) {
7585   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7586   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7587       EndLoc.isValid()) {
7588     Self.Diag(Loc, Note)
7589       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7590       << FixItHint::CreateInsertion(EndLoc, ")");
7591   } else {
7592     // We can't display the parentheses, so just show the bare note.
7593     Self.Diag(Loc, Note) << ParenRange;
7594   }
7595 }
7596 
7597 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7598   return BinaryOperator::isAdditiveOp(Opc) ||
7599          BinaryOperator::isMultiplicativeOp(Opc) ||
7600          BinaryOperator::isShiftOp(Opc);
7601 }
7602 
7603 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7604 /// expression, either using a built-in or overloaded operator,
7605 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7606 /// expression.
7607 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7608                                    Expr **RHSExprs) {
7609   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7610   E = E->IgnoreImpCasts();
7611   E = E->IgnoreConversionOperator();
7612   E = E->IgnoreImpCasts();
7613   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7614     E = MTE->GetTemporaryExpr();
7615     E = E->IgnoreImpCasts();
7616   }
7617 
7618   // Built-in binary operator.
7619   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7620     if (IsArithmeticOp(OP->getOpcode())) {
7621       *Opcode = OP->getOpcode();
7622       *RHSExprs = OP->getRHS();
7623       return true;
7624     }
7625   }
7626 
7627   // Overloaded operator.
7628   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7629     if (Call->getNumArgs() != 2)
7630       return false;
7631 
7632     // Make sure this is really a binary operator that is safe to pass into
7633     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7634     OverloadedOperatorKind OO = Call->getOperator();
7635     if (OO < OO_Plus || OO > OO_Arrow ||
7636         OO == OO_PlusPlus || OO == OO_MinusMinus)
7637       return false;
7638 
7639     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7640     if (IsArithmeticOp(OpKind)) {
7641       *Opcode = OpKind;
7642       *RHSExprs = Call->getArg(1);
7643       return true;
7644     }
7645   }
7646 
7647   return false;
7648 }
7649 
7650 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7651 /// or is a logical expression such as (x==y) which has int type, but is
7652 /// commonly interpreted as boolean.
7653 static bool ExprLooksBoolean(Expr *E) {
7654   E = E->IgnoreParenImpCasts();
7655 
7656   if (E->getType()->isBooleanType())
7657     return true;
7658   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7659     return OP->isComparisonOp() || OP->isLogicalOp();
7660   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7661     return OP->getOpcode() == UO_LNot;
7662   if (E->getType()->isPointerType())
7663     return true;
7664   // FIXME: What about overloaded operator calls returning "unspecified boolean
7665   // type"s (commonly pointer-to-members)?
7666 
7667   return false;
7668 }
7669 
7670 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7671 /// and binary operator are mixed in a way that suggests the programmer assumed
7672 /// the conditional operator has higher precedence, for example:
7673 /// "int x = a + someBinaryCondition ? 1 : 2".
7674 static void DiagnoseConditionalPrecedence(Sema &Self,
7675                                           SourceLocation OpLoc,
7676                                           Expr *Condition,
7677                                           Expr *LHSExpr,
7678                                           Expr *RHSExpr) {
7679   BinaryOperatorKind CondOpcode;
7680   Expr *CondRHS;
7681 
7682   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7683     return;
7684   if (!ExprLooksBoolean(CondRHS))
7685     return;
7686 
7687   // The condition is an arithmetic binary expression, with a right-
7688   // hand side that looks boolean, so warn.
7689 
7690   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7691       << Condition->getSourceRange()
7692       << BinaryOperator::getOpcodeStr(CondOpcode);
7693 
7694   SuggestParentheses(
7695       Self, OpLoc,
7696       Self.PDiag(diag::note_precedence_silence)
7697           << BinaryOperator::getOpcodeStr(CondOpcode),
7698       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7699 
7700   SuggestParentheses(Self, OpLoc,
7701                      Self.PDiag(diag::note_precedence_conditional_first),
7702                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7703 }
7704 
7705 /// Compute the nullability of a conditional expression.
7706 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7707                                               QualType LHSTy, QualType RHSTy,
7708                                               ASTContext &Ctx) {
7709   if (!ResTy->isAnyPointerType())
7710     return ResTy;
7711 
7712   auto GetNullability = [&Ctx](QualType Ty) {
7713     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7714     if (Kind)
7715       return *Kind;
7716     return NullabilityKind::Unspecified;
7717   };
7718 
7719   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7720   NullabilityKind MergedKind;
7721 
7722   // Compute nullability of a binary conditional expression.
7723   if (IsBin) {
7724     if (LHSKind == NullabilityKind::NonNull)
7725       MergedKind = NullabilityKind::NonNull;
7726     else
7727       MergedKind = RHSKind;
7728   // Compute nullability of a normal conditional expression.
7729   } else {
7730     if (LHSKind == NullabilityKind::Nullable ||
7731         RHSKind == NullabilityKind::Nullable)
7732       MergedKind = NullabilityKind::Nullable;
7733     else if (LHSKind == NullabilityKind::NonNull)
7734       MergedKind = RHSKind;
7735     else if (RHSKind == NullabilityKind::NonNull)
7736       MergedKind = LHSKind;
7737     else
7738       MergedKind = NullabilityKind::Unspecified;
7739   }
7740 
7741   // Return if ResTy already has the correct nullability.
7742   if (GetNullability(ResTy) == MergedKind)
7743     return ResTy;
7744 
7745   // Strip all nullability from ResTy.
7746   while (ResTy->getNullability(Ctx))
7747     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7748 
7749   // Create a new AttributedType with the new nullability kind.
7750   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7751   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7752 }
7753 
7754 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7755 /// in the case of a the GNU conditional expr extension.
7756 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7757                                     SourceLocation ColonLoc,
7758                                     Expr *CondExpr, Expr *LHSExpr,
7759                                     Expr *RHSExpr) {
7760   if (!getLangOpts().CPlusPlus) {
7761     // C cannot handle TypoExpr nodes in the condition because it
7762     // doesn't handle dependent types properly, so make sure any TypoExprs have
7763     // been dealt with before checking the operands.
7764     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7765     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7766     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7767 
7768     if (!CondResult.isUsable())
7769       return ExprError();
7770 
7771     if (LHSExpr) {
7772       if (!LHSResult.isUsable())
7773         return ExprError();
7774     }
7775 
7776     if (!RHSResult.isUsable())
7777       return ExprError();
7778 
7779     CondExpr = CondResult.get();
7780     LHSExpr = LHSResult.get();
7781     RHSExpr = RHSResult.get();
7782   }
7783 
7784   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7785   // was the condition.
7786   OpaqueValueExpr *opaqueValue = nullptr;
7787   Expr *commonExpr = nullptr;
7788   if (!LHSExpr) {
7789     commonExpr = CondExpr;
7790     // Lower out placeholder types first.  This is important so that we don't
7791     // try to capture a placeholder. This happens in few cases in C++; such
7792     // as Objective-C++'s dictionary subscripting syntax.
7793     if (commonExpr->hasPlaceholderType()) {
7794       ExprResult result = CheckPlaceholderExpr(commonExpr);
7795       if (!result.isUsable()) return ExprError();
7796       commonExpr = result.get();
7797     }
7798     // We usually want to apply unary conversions *before* saving, except
7799     // in the special case of a C++ l-value conditional.
7800     if (!(getLangOpts().CPlusPlus
7801           && !commonExpr->isTypeDependent()
7802           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7803           && commonExpr->isGLValue()
7804           && commonExpr->isOrdinaryOrBitFieldObject()
7805           && RHSExpr->isOrdinaryOrBitFieldObject()
7806           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7807       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7808       if (commonRes.isInvalid())
7809         return ExprError();
7810       commonExpr = commonRes.get();
7811     }
7812 
7813     // If the common expression is a class or array prvalue, materialize it
7814     // so that we can safely refer to it multiple times.
7815     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7816                                    commonExpr->getType()->isArrayType())) {
7817       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7818       if (MatExpr.isInvalid())
7819         return ExprError();
7820       commonExpr = MatExpr.get();
7821     }
7822 
7823     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7824                                                 commonExpr->getType(),
7825                                                 commonExpr->getValueKind(),
7826                                                 commonExpr->getObjectKind(),
7827                                                 commonExpr);
7828     LHSExpr = CondExpr = opaqueValue;
7829   }
7830 
7831   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7832   ExprValueKind VK = VK_RValue;
7833   ExprObjectKind OK = OK_Ordinary;
7834   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7835   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7836                                              VK, OK, QuestionLoc);
7837   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7838       RHS.isInvalid())
7839     return ExprError();
7840 
7841   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7842                                 RHS.get());
7843 
7844   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7845 
7846   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7847                                          Context);
7848 
7849   if (!commonExpr)
7850     return new (Context)
7851         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7852                             RHS.get(), result, VK, OK);
7853 
7854   return new (Context) BinaryConditionalOperator(
7855       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7856       ColonLoc, result, VK, OK);
7857 }
7858 
7859 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7860 // being closely modeled after the C99 spec:-). The odd characteristic of this
7861 // routine is it effectively iqnores the qualifiers on the top level pointee.
7862 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7863 // FIXME: add a couple examples in this comment.
7864 static Sema::AssignConvertType
7865 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7866   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7867   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7868 
7869   // get the "pointed to" type (ignoring qualifiers at the top level)
7870   const Type *lhptee, *rhptee;
7871   Qualifiers lhq, rhq;
7872   std::tie(lhptee, lhq) =
7873       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7874   std::tie(rhptee, rhq) =
7875       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7876 
7877   Sema::AssignConvertType ConvTy = Sema::Compatible;
7878 
7879   // C99 6.5.16.1p1: This following citation is common to constraints
7880   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7881   // qualifiers of the type *pointed to* by the right;
7882 
7883   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7884   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7885       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7886     // Ignore lifetime for further calculation.
7887     lhq.removeObjCLifetime();
7888     rhq.removeObjCLifetime();
7889   }
7890 
7891   if (!lhq.compatiblyIncludes(rhq)) {
7892     // Treat address-space mismatches as fatal.
7893     if (!lhq.isAddressSpaceSupersetOf(rhq))
7894       return Sema::IncompatiblePointerDiscardsQualifiers;
7895 
7896     // It's okay to add or remove GC or lifetime qualifiers when converting to
7897     // and from void*.
7898     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7899                         .compatiblyIncludes(
7900                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7901              && (lhptee->isVoidType() || rhptee->isVoidType()))
7902       ; // keep old
7903 
7904     // Treat lifetime mismatches as fatal.
7905     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7906       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7907 
7908     // For GCC/MS compatibility, other qualifier mismatches are treated
7909     // as still compatible in C.
7910     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7911   }
7912 
7913   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7914   // incomplete type and the other is a pointer to a qualified or unqualified
7915   // version of void...
7916   if (lhptee->isVoidType()) {
7917     if (rhptee->isIncompleteOrObjectType())
7918       return ConvTy;
7919 
7920     // As an extension, we allow cast to/from void* to function pointer.
7921     assert(rhptee->isFunctionType());
7922     return Sema::FunctionVoidPointer;
7923   }
7924 
7925   if (rhptee->isVoidType()) {
7926     if (lhptee->isIncompleteOrObjectType())
7927       return ConvTy;
7928 
7929     // As an extension, we allow cast to/from void* to function pointer.
7930     assert(lhptee->isFunctionType());
7931     return Sema::FunctionVoidPointer;
7932   }
7933 
7934   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7935   // unqualified versions of compatible types, ...
7936   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7937   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7938     // Check if the pointee types are compatible ignoring the sign.
7939     // We explicitly check for char so that we catch "char" vs
7940     // "unsigned char" on systems where "char" is unsigned.
7941     if (lhptee->isCharType())
7942       ltrans = S.Context.UnsignedCharTy;
7943     else if (lhptee->hasSignedIntegerRepresentation())
7944       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7945 
7946     if (rhptee->isCharType())
7947       rtrans = S.Context.UnsignedCharTy;
7948     else if (rhptee->hasSignedIntegerRepresentation())
7949       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7950 
7951     if (ltrans == rtrans) {
7952       // Types are compatible ignoring the sign. Qualifier incompatibility
7953       // takes priority over sign incompatibility because the sign
7954       // warning can be disabled.
7955       if (ConvTy != Sema::Compatible)
7956         return ConvTy;
7957 
7958       return Sema::IncompatiblePointerSign;
7959     }
7960 
7961     // If we are a multi-level pointer, it's possible that our issue is simply
7962     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7963     // the eventual target type is the same and the pointers have the same
7964     // level of indirection, this must be the issue.
7965     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7966       do {
7967         std::tie(lhptee, lhq) =
7968           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7969         std::tie(rhptee, rhq) =
7970           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7971 
7972         // Inconsistent address spaces at this point is invalid, even if the
7973         // address spaces would be compatible.
7974         // FIXME: This doesn't catch address space mismatches for pointers of
7975         // different nesting levels, like:
7976         //   __local int *** a;
7977         //   int ** b = a;
7978         // It's not clear how to actually determine when such pointers are
7979         // invalidly incompatible.
7980         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7981           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7982 
7983       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7984 
7985       if (lhptee == rhptee)
7986         return Sema::IncompatibleNestedPointerQualifiers;
7987     }
7988 
7989     // General pointer incompatibility takes priority over qualifiers.
7990     return Sema::IncompatiblePointer;
7991   }
7992   if (!S.getLangOpts().CPlusPlus &&
7993       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7994     return Sema::IncompatiblePointer;
7995   return ConvTy;
7996 }
7997 
7998 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7999 /// block pointer types are compatible or whether a block and normal pointer
8000 /// are compatible. It is more restrict than comparing two function pointer
8001 // types.
8002 static Sema::AssignConvertType
8003 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8004                                     QualType RHSType) {
8005   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8006   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8007 
8008   QualType lhptee, rhptee;
8009 
8010   // get the "pointed to" type (ignoring qualifiers at the top level)
8011   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8012   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8013 
8014   // In C++, the types have to match exactly.
8015   if (S.getLangOpts().CPlusPlus)
8016     return Sema::IncompatibleBlockPointer;
8017 
8018   Sema::AssignConvertType ConvTy = Sema::Compatible;
8019 
8020   // For blocks we enforce that qualifiers are identical.
8021   Qualifiers LQuals = lhptee.getLocalQualifiers();
8022   Qualifiers RQuals = rhptee.getLocalQualifiers();
8023   if (S.getLangOpts().OpenCL) {
8024     LQuals.removeAddressSpace();
8025     RQuals.removeAddressSpace();
8026   }
8027   if (LQuals != RQuals)
8028     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8029 
8030   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8031   // assignment.
8032   // The current behavior is similar to C++ lambdas. A block might be
8033   // assigned to a variable iff its return type and parameters are compatible
8034   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8035   // an assignment. Presumably it should behave in way that a function pointer
8036   // assignment does in C, so for each parameter and return type:
8037   //  * CVR and address space of LHS should be a superset of CVR and address
8038   //  space of RHS.
8039   //  * unqualified types should be compatible.
8040   if (S.getLangOpts().OpenCL) {
8041     if (!S.Context.typesAreBlockPointerCompatible(
8042             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8043             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8044       return Sema::IncompatibleBlockPointer;
8045   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8046     return Sema::IncompatibleBlockPointer;
8047 
8048   return ConvTy;
8049 }
8050 
8051 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8052 /// for assignment compatibility.
8053 static Sema::AssignConvertType
8054 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8055                                    QualType RHSType) {
8056   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8057   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8058 
8059   if (LHSType->isObjCBuiltinType()) {
8060     // Class is not compatible with ObjC object pointers.
8061     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8062         !RHSType->isObjCQualifiedClassType())
8063       return Sema::IncompatiblePointer;
8064     return Sema::Compatible;
8065   }
8066   if (RHSType->isObjCBuiltinType()) {
8067     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8068         !LHSType->isObjCQualifiedClassType())
8069       return Sema::IncompatiblePointer;
8070     return Sema::Compatible;
8071   }
8072   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8073   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8074 
8075   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8076       // make an exception for id<P>
8077       !LHSType->isObjCQualifiedIdType())
8078     return Sema::CompatiblePointerDiscardsQualifiers;
8079 
8080   if (S.Context.typesAreCompatible(LHSType, RHSType))
8081     return Sema::Compatible;
8082   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8083     return Sema::IncompatibleObjCQualifiedId;
8084   return Sema::IncompatiblePointer;
8085 }
8086 
8087 Sema::AssignConvertType
8088 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8089                                  QualType LHSType, QualType RHSType) {
8090   // Fake up an opaque expression.  We don't actually care about what
8091   // cast operations are required, so if CheckAssignmentConstraints
8092   // adds casts to this they'll be wasted, but fortunately that doesn't
8093   // usually happen on valid code.
8094   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8095   ExprResult RHSPtr = &RHSExpr;
8096   CastKind K;
8097 
8098   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8099 }
8100 
8101 /// This helper function returns true if QT is a vector type that has element
8102 /// type ElementType.
8103 static bool isVector(QualType QT, QualType ElementType) {
8104   if (const VectorType *VT = QT->getAs<VectorType>())
8105     return VT->getElementType() == ElementType;
8106   return false;
8107 }
8108 
8109 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8110 /// has code to accommodate several GCC extensions when type checking
8111 /// pointers. Here are some objectionable examples that GCC considers warnings:
8112 ///
8113 ///  int a, *pint;
8114 ///  short *pshort;
8115 ///  struct foo *pfoo;
8116 ///
8117 ///  pint = pshort; // warning: assignment from incompatible pointer type
8118 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8119 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8120 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8121 ///
8122 /// As a result, the code for dealing with pointers is more complex than the
8123 /// C99 spec dictates.
8124 ///
8125 /// Sets 'Kind' for any result kind except Incompatible.
8126 Sema::AssignConvertType
8127 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8128                                  CastKind &Kind, bool ConvertRHS) {
8129   QualType RHSType = RHS.get()->getType();
8130   QualType OrigLHSType = LHSType;
8131 
8132   // Get canonical types.  We're not formatting these types, just comparing
8133   // them.
8134   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8135   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8136 
8137   // Common case: no conversion required.
8138   if (LHSType == RHSType) {
8139     Kind = CK_NoOp;
8140     return Compatible;
8141   }
8142 
8143   // If we have an atomic type, try a non-atomic assignment, then just add an
8144   // atomic qualification step.
8145   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8146     Sema::AssignConvertType result =
8147       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8148     if (result != Compatible)
8149       return result;
8150     if (Kind != CK_NoOp && ConvertRHS)
8151       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8152     Kind = CK_NonAtomicToAtomic;
8153     return Compatible;
8154   }
8155 
8156   // If the left-hand side is a reference type, then we are in a
8157   // (rare!) case where we've allowed the use of references in C,
8158   // e.g., as a parameter type in a built-in function. In this case,
8159   // just make sure that the type referenced is compatible with the
8160   // right-hand side type. The caller is responsible for adjusting
8161   // LHSType so that the resulting expression does not have reference
8162   // type.
8163   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8164     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8165       Kind = CK_LValueBitCast;
8166       return Compatible;
8167     }
8168     return Incompatible;
8169   }
8170 
8171   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8172   // to the same ExtVector type.
8173   if (LHSType->isExtVectorType()) {
8174     if (RHSType->isExtVectorType())
8175       return Incompatible;
8176     if (RHSType->isArithmeticType()) {
8177       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8178       if (ConvertRHS)
8179         RHS = prepareVectorSplat(LHSType, RHS.get());
8180       Kind = CK_VectorSplat;
8181       return Compatible;
8182     }
8183   }
8184 
8185   // Conversions to or from vector type.
8186   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8187     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8188       // Allow assignments of an AltiVec vector type to an equivalent GCC
8189       // vector type and vice versa
8190       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8191         Kind = CK_BitCast;
8192         return Compatible;
8193       }
8194 
8195       // If we are allowing lax vector conversions, and LHS and RHS are both
8196       // vectors, the total size only needs to be the same. This is a bitcast;
8197       // no bits are changed but the result type is different.
8198       if (isLaxVectorConversion(RHSType, LHSType)) {
8199         Kind = CK_BitCast;
8200         return IncompatibleVectors;
8201       }
8202     }
8203 
8204     // When the RHS comes from another lax conversion (e.g. binops between
8205     // scalars and vectors) the result is canonicalized as a vector. When the
8206     // LHS is also a vector, the lax is allowed by the condition above. Handle
8207     // the case where LHS is a scalar.
8208     if (LHSType->isScalarType()) {
8209       const VectorType *VecType = RHSType->getAs<VectorType>();
8210       if (VecType && VecType->getNumElements() == 1 &&
8211           isLaxVectorConversion(RHSType, LHSType)) {
8212         ExprResult *VecExpr = &RHS;
8213         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8214         Kind = CK_BitCast;
8215         return Compatible;
8216       }
8217     }
8218 
8219     return Incompatible;
8220   }
8221 
8222   // Diagnose attempts to convert between __float128 and long double where
8223   // such conversions currently can't be handled.
8224   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8225     return Incompatible;
8226 
8227   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8228   // discards the imaginary part.
8229   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8230       !LHSType->getAs<ComplexType>())
8231     return Incompatible;
8232 
8233   // Arithmetic conversions.
8234   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8235       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8236     if (ConvertRHS)
8237       Kind = PrepareScalarCast(RHS, LHSType);
8238     return Compatible;
8239   }
8240 
8241   // Conversions to normal pointers.
8242   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8243     // U* -> T*
8244     if (isa<PointerType>(RHSType)) {
8245       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8246       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8247       if (AddrSpaceL != AddrSpaceR)
8248         Kind = CK_AddressSpaceConversion;
8249       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8250         Kind = CK_NoOp;
8251       else
8252         Kind = CK_BitCast;
8253       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8254     }
8255 
8256     // int -> T*
8257     if (RHSType->isIntegerType()) {
8258       Kind = CK_IntegralToPointer; // FIXME: null?
8259       return IntToPointer;
8260     }
8261 
8262     // C pointers are not compatible with ObjC object pointers,
8263     // with two exceptions:
8264     if (isa<ObjCObjectPointerType>(RHSType)) {
8265       //  - conversions to void*
8266       if (LHSPointer->getPointeeType()->isVoidType()) {
8267         Kind = CK_BitCast;
8268         return Compatible;
8269       }
8270 
8271       //  - conversions from 'Class' to the redefinition type
8272       if (RHSType->isObjCClassType() &&
8273           Context.hasSameType(LHSType,
8274                               Context.getObjCClassRedefinitionType())) {
8275         Kind = CK_BitCast;
8276         return Compatible;
8277       }
8278 
8279       Kind = CK_BitCast;
8280       return IncompatiblePointer;
8281     }
8282 
8283     // U^ -> void*
8284     if (RHSType->getAs<BlockPointerType>()) {
8285       if (LHSPointer->getPointeeType()->isVoidType()) {
8286         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8287         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8288                                 ->getPointeeType()
8289                                 .getAddressSpace();
8290         Kind =
8291             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8292         return Compatible;
8293       }
8294     }
8295 
8296     return Incompatible;
8297   }
8298 
8299   // Conversions to block pointers.
8300   if (isa<BlockPointerType>(LHSType)) {
8301     // U^ -> T^
8302     if (RHSType->isBlockPointerType()) {
8303       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8304                               ->getPointeeType()
8305                               .getAddressSpace();
8306       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8307                               ->getPointeeType()
8308                               .getAddressSpace();
8309       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8310       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8311     }
8312 
8313     // int or null -> T^
8314     if (RHSType->isIntegerType()) {
8315       Kind = CK_IntegralToPointer; // FIXME: null
8316       return IntToBlockPointer;
8317     }
8318 
8319     // id -> T^
8320     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8321       Kind = CK_AnyPointerToBlockPointerCast;
8322       return Compatible;
8323     }
8324 
8325     // void* -> T^
8326     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8327       if (RHSPT->getPointeeType()->isVoidType()) {
8328         Kind = CK_AnyPointerToBlockPointerCast;
8329         return Compatible;
8330       }
8331 
8332     return Incompatible;
8333   }
8334 
8335   // Conversions to Objective-C pointers.
8336   if (isa<ObjCObjectPointerType>(LHSType)) {
8337     // A* -> B*
8338     if (RHSType->isObjCObjectPointerType()) {
8339       Kind = CK_BitCast;
8340       Sema::AssignConvertType result =
8341         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8342       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8343           result == Compatible &&
8344           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8345         result = IncompatibleObjCWeakRef;
8346       return result;
8347     }
8348 
8349     // int or null -> A*
8350     if (RHSType->isIntegerType()) {
8351       Kind = CK_IntegralToPointer; // FIXME: null
8352       return IntToPointer;
8353     }
8354 
8355     // In general, C pointers are not compatible with ObjC object pointers,
8356     // with two exceptions:
8357     if (isa<PointerType>(RHSType)) {
8358       Kind = CK_CPointerToObjCPointerCast;
8359 
8360       //  - conversions from 'void*'
8361       if (RHSType->isVoidPointerType()) {
8362         return Compatible;
8363       }
8364 
8365       //  - conversions to 'Class' from its redefinition type
8366       if (LHSType->isObjCClassType() &&
8367           Context.hasSameType(RHSType,
8368                               Context.getObjCClassRedefinitionType())) {
8369         return Compatible;
8370       }
8371 
8372       return IncompatiblePointer;
8373     }
8374 
8375     // Only under strict condition T^ is compatible with an Objective-C pointer.
8376     if (RHSType->isBlockPointerType() &&
8377         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8378       if (ConvertRHS)
8379         maybeExtendBlockObject(RHS);
8380       Kind = CK_BlockPointerToObjCPointerCast;
8381       return Compatible;
8382     }
8383 
8384     return Incompatible;
8385   }
8386 
8387   // Conversions from pointers that are not covered by the above.
8388   if (isa<PointerType>(RHSType)) {
8389     // T* -> _Bool
8390     if (LHSType == Context.BoolTy) {
8391       Kind = CK_PointerToBoolean;
8392       return Compatible;
8393     }
8394 
8395     // T* -> int
8396     if (LHSType->isIntegerType()) {
8397       Kind = CK_PointerToIntegral;
8398       return PointerToInt;
8399     }
8400 
8401     return Incompatible;
8402   }
8403 
8404   // Conversions from Objective-C pointers that are not covered by the above.
8405   if (isa<ObjCObjectPointerType>(RHSType)) {
8406     // T* -> _Bool
8407     if (LHSType == Context.BoolTy) {
8408       Kind = CK_PointerToBoolean;
8409       return Compatible;
8410     }
8411 
8412     // T* -> int
8413     if (LHSType->isIntegerType()) {
8414       Kind = CK_PointerToIntegral;
8415       return PointerToInt;
8416     }
8417 
8418     return Incompatible;
8419   }
8420 
8421   // struct A -> struct B
8422   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8423     if (Context.typesAreCompatible(LHSType, RHSType)) {
8424       Kind = CK_NoOp;
8425       return Compatible;
8426     }
8427   }
8428 
8429   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8430     Kind = CK_IntToOCLSampler;
8431     return Compatible;
8432   }
8433 
8434   return Incompatible;
8435 }
8436 
8437 /// Constructs a transparent union from an expression that is
8438 /// used to initialize the transparent union.
8439 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8440                                       ExprResult &EResult, QualType UnionType,
8441                                       FieldDecl *Field) {
8442   // Build an initializer list that designates the appropriate member
8443   // of the transparent union.
8444   Expr *E = EResult.get();
8445   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8446                                                    E, SourceLocation());
8447   Initializer->setType(UnionType);
8448   Initializer->setInitializedFieldInUnion(Field);
8449 
8450   // Build a compound literal constructing a value of the transparent
8451   // union type from this initializer list.
8452   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8453   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8454                                         VK_RValue, Initializer, false);
8455 }
8456 
8457 Sema::AssignConvertType
8458 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8459                                                ExprResult &RHS) {
8460   QualType RHSType = RHS.get()->getType();
8461 
8462   // If the ArgType is a Union type, we want to handle a potential
8463   // transparent_union GCC extension.
8464   const RecordType *UT = ArgType->getAsUnionType();
8465   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8466     return Incompatible;
8467 
8468   // The field to initialize within the transparent union.
8469   RecordDecl *UD = UT->getDecl();
8470   FieldDecl *InitField = nullptr;
8471   // It's compatible if the expression matches any of the fields.
8472   for (auto *it : UD->fields()) {
8473     if (it->getType()->isPointerType()) {
8474       // If the transparent union contains a pointer type, we allow:
8475       // 1) void pointer
8476       // 2) null pointer constant
8477       if (RHSType->isPointerType())
8478         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8479           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8480           InitField = it;
8481           break;
8482         }
8483 
8484       if (RHS.get()->isNullPointerConstant(Context,
8485                                            Expr::NPC_ValueDependentIsNull)) {
8486         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8487                                 CK_NullToPointer);
8488         InitField = it;
8489         break;
8490       }
8491     }
8492 
8493     CastKind Kind;
8494     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8495           == Compatible) {
8496       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8497       InitField = it;
8498       break;
8499     }
8500   }
8501 
8502   if (!InitField)
8503     return Incompatible;
8504 
8505   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8506   return Compatible;
8507 }
8508 
8509 Sema::AssignConvertType
8510 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8511                                        bool Diagnose,
8512                                        bool DiagnoseCFAudited,
8513                                        bool ConvertRHS) {
8514   // We need to be able to tell the caller whether we diagnosed a problem, if
8515   // they ask us to issue diagnostics.
8516   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8517 
8518   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8519   // we can't avoid *all* modifications at the moment, so we need some somewhere
8520   // to put the updated value.
8521   ExprResult LocalRHS = CallerRHS;
8522   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8523 
8524   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8525     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8526       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8527           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8528         Diag(RHS.get()->getExprLoc(),
8529              diag::warn_noderef_to_dereferenceable_pointer)
8530             << RHS.get()->getSourceRange();
8531       }
8532     }
8533   }
8534 
8535   if (getLangOpts().CPlusPlus) {
8536     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8537       // C++ 5.17p3: If the left operand is not of class type, the
8538       // expression is implicitly converted (C++ 4) to the
8539       // cv-unqualified type of the left operand.
8540       QualType RHSType = RHS.get()->getType();
8541       if (Diagnose) {
8542         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8543                                         AA_Assigning);
8544       } else {
8545         ImplicitConversionSequence ICS =
8546             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8547                                   /*SuppressUserConversions=*/false,
8548                                   /*AllowExplicit=*/false,
8549                                   /*InOverloadResolution=*/false,
8550                                   /*CStyle=*/false,
8551                                   /*AllowObjCWritebackConversion=*/false);
8552         if (ICS.isFailure())
8553           return Incompatible;
8554         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8555                                         ICS, AA_Assigning);
8556       }
8557       if (RHS.isInvalid())
8558         return Incompatible;
8559       Sema::AssignConvertType result = Compatible;
8560       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8561           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8562         result = IncompatibleObjCWeakRef;
8563       return result;
8564     }
8565 
8566     // FIXME: Currently, we fall through and treat C++ classes like C
8567     // structures.
8568     // FIXME: We also fall through for atomics; not sure what should
8569     // happen there, though.
8570   } else if (RHS.get()->getType() == Context.OverloadTy) {
8571     // As a set of extensions to C, we support overloading on functions. These
8572     // functions need to be resolved here.
8573     DeclAccessPair DAP;
8574     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8575             RHS.get(), LHSType, /*Complain=*/false, DAP))
8576       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8577     else
8578       return Incompatible;
8579   }
8580 
8581   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8582   // a null pointer constant.
8583   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8584        LHSType->isBlockPointerType()) &&
8585       RHS.get()->isNullPointerConstant(Context,
8586                                        Expr::NPC_ValueDependentIsNull)) {
8587     if (Diagnose || ConvertRHS) {
8588       CastKind Kind;
8589       CXXCastPath Path;
8590       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8591                              /*IgnoreBaseAccess=*/false, Diagnose);
8592       if (ConvertRHS)
8593         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8594     }
8595     return Compatible;
8596   }
8597 
8598   // OpenCL queue_t type assignment.
8599   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8600                                  Context, Expr::NPC_ValueDependentIsNull)) {
8601     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8602     return Compatible;
8603   }
8604 
8605   // This check seems unnatural, however it is necessary to ensure the proper
8606   // conversion of functions/arrays. If the conversion were done for all
8607   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8608   // expressions that suppress this implicit conversion (&, sizeof).
8609   //
8610   // Suppress this for references: C++ 8.5.3p5.
8611   if (!LHSType->isReferenceType()) {
8612     // FIXME: We potentially allocate here even if ConvertRHS is false.
8613     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8614     if (RHS.isInvalid())
8615       return Incompatible;
8616   }
8617   CastKind Kind;
8618   Sema::AssignConvertType result =
8619     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8620 
8621   // C99 6.5.16.1p2: The value of the right operand is converted to the
8622   // type of the assignment expression.
8623   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8624   // so that we can use references in built-in functions even in C.
8625   // The getNonReferenceType() call makes sure that the resulting expression
8626   // does not have reference type.
8627   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8628     QualType Ty = LHSType.getNonLValueExprType(Context);
8629     Expr *E = RHS.get();
8630 
8631     // Check for various Objective-C errors. If we are not reporting
8632     // diagnostics and just checking for errors, e.g., during overload
8633     // resolution, return Incompatible to indicate the failure.
8634     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8635         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8636                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8637       if (!Diagnose)
8638         return Incompatible;
8639     }
8640     if (getLangOpts().ObjC &&
8641         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8642                                            E->getType(), E, Diagnose) ||
8643          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8644       if (!Diagnose)
8645         return Incompatible;
8646       // Replace the expression with a corrected version and continue so we
8647       // can find further errors.
8648       RHS = E;
8649       return Compatible;
8650     }
8651 
8652     if (ConvertRHS)
8653       RHS = ImpCastExprToType(E, Ty, Kind);
8654   }
8655 
8656   return result;
8657 }
8658 
8659 namespace {
8660 /// The original operand to an operator, prior to the application of the usual
8661 /// arithmetic conversions and converting the arguments of a builtin operator
8662 /// candidate.
8663 struct OriginalOperand {
8664   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8665     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8666       Op = MTE->GetTemporaryExpr();
8667     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8668       Op = BTE->getSubExpr();
8669     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8670       Orig = ICE->getSubExprAsWritten();
8671       Conversion = ICE->getConversionFunction();
8672     }
8673   }
8674 
8675   QualType getType() const { return Orig->getType(); }
8676 
8677   Expr *Orig;
8678   NamedDecl *Conversion;
8679 };
8680 }
8681 
8682 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8683                                ExprResult &RHS) {
8684   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8685 
8686   Diag(Loc, diag::err_typecheck_invalid_operands)
8687     << OrigLHS.getType() << OrigRHS.getType()
8688     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8689 
8690   // If a user-defined conversion was applied to either of the operands prior
8691   // to applying the built-in operator rules, tell the user about it.
8692   if (OrigLHS.Conversion) {
8693     Diag(OrigLHS.Conversion->getLocation(),
8694          diag::note_typecheck_invalid_operands_converted)
8695       << 0 << LHS.get()->getType();
8696   }
8697   if (OrigRHS.Conversion) {
8698     Diag(OrigRHS.Conversion->getLocation(),
8699          diag::note_typecheck_invalid_operands_converted)
8700       << 1 << RHS.get()->getType();
8701   }
8702 
8703   return QualType();
8704 }
8705 
8706 // Diagnose cases where a scalar was implicitly converted to a vector and
8707 // diagnose the underlying types. Otherwise, diagnose the error
8708 // as invalid vector logical operands for non-C++ cases.
8709 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8710                                             ExprResult &RHS) {
8711   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8712   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8713 
8714   bool LHSNatVec = LHSType->isVectorType();
8715   bool RHSNatVec = RHSType->isVectorType();
8716 
8717   if (!(LHSNatVec && RHSNatVec)) {
8718     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8719     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8720     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8721         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8722         << Vector->getSourceRange();
8723     return QualType();
8724   }
8725 
8726   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8727       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8728       << RHS.get()->getSourceRange();
8729 
8730   return QualType();
8731 }
8732 
8733 /// Try to convert a value of non-vector type to a vector type by converting
8734 /// the type to the element type of the vector and then performing a splat.
8735 /// If the language is OpenCL, we only use conversions that promote scalar
8736 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8737 /// for float->int.
8738 ///
8739 /// OpenCL V2.0 6.2.6.p2:
8740 /// An error shall occur if any scalar operand type has greater rank
8741 /// than the type of the vector element.
8742 ///
8743 /// \param scalar - if non-null, actually perform the conversions
8744 /// \return true if the operation fails (but without diagnosing the failure)
8745 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8746                                      QualType scalarTy,
8747                                      QualType vectorEltTy,
8748                                      QualType vectorTy,
8749                                      unsigned &DiagID) {
8750   // The conversion to apply to the scalar before splatting it,
8751   // if necessary.
8752   CastKind scalarCast = CK_NoOp;
8753 
8754   if (vectorEltTy->isIntegralType(S.Context)) {
8755     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8756         (scalarTy->isIntegerType() &&
8757          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8758       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8759       return true;
8760     }
8761     if (!scalarTy->isIntegralType(S.Context))
8762       return true;
8763     scalarCast = CK_IntegralCast;
8764   } else if (vectorEltTy->isRealFloatingType()) {
8765     if (scalarTy->isRealFloatingType()) {
8766       if (S.getLangOpts().OpenCL &&
8767           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8768         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8769         return true;
8770       }
8771       scalarCast = CK_FloatingCast;
8772     }
8773     else if (scalarTy->isIntegralType(S.Context))
8774       scalarCast = CK_IntegralToFloating;
8775     else
8776       return true;
8777   } else {
8778     return true;
8779   }
8780 
8781   // Adjust scalar if desired.
8782   if (scalar) {
8783     if (scalarCast != CK_NoOp)
8784       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8785     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8786   }
8787   return false;
8788 }
8789 
8790 /// Convert vector E to a vector with the same number of elements but different
8791 /// element type.
8792 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8793   const auto *VecTy = E->getType()->getAs<VectorType>();
8794   assert(VecTy && "Expression E must be a vector");
8795   QualType NewVecTy = S.Context.getVectorType(ElementType,
8796                                               VecTy->getNumElements(),
8797                                               VecTy->getVectorKind());
8798 
8799   // Look through the implicit cast. Return the subexpression if its type is
8800   // NewVecTy.
8801   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8802     if (ICE->getSubExpr()->getType() == NewVecTy)
8803       return ICE->getSubExpr();
8804 
8805   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8806   return S.ImpCastExprToType(E, NewVecTy, Cast);
8807 }
8808 
8809 /// Test if a (constant) integer Int can be casted to another integer type
8810 /// IntTy without losing precision.
8811 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8812                                       QualType OtherIntTy) {
8813   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8814 
8815   // Reject cases where the value of the Int is unknown as that would
8816   // possibly cause truncation, but accept cases where the scalar can be
8817   // demoted without loss of precision.
8818   Expr::EvalResult EVResult;
8819   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8820   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8821   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8822   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8823 
8824   if (CstInt) {
8825     // If the scalar is constant and is of a higher order and has more active
8826     // bits that the vector element type, reject it.
8827     llvm::APSInt Result = EVResult.Val.getInt();
8828     unsigned NumBits = IntSigned
8829                            ? (Result.isNegative() ? Result.getMinSignedBits()
8830                                                   : Result.getActiveBits())
8831                            : Result.getActiveBits();
8832     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8833       return true;
8834 
8835     // If the signedness of the scalar type and the vector element type
8836     // differs and the number of bits is greater than that of the vector
8837     // element reject it.
8838     return (IntSigned != OtherIntSigned &&
8839             NumBits > S.Context.getIntWidth(OtherIntTy));
8840   }
8841 
8842   // Reject cases where the value of the scalar is not constant and it's
8843   // order is greater than that of the vector element type.
8844   return (Order < 0);
8845 }
8846 
8847 /// Test if a (constant) integer Int can be casted to floating point type
8848 /// FloatTy without losing precision.
8849 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8850                                      QualType FloatTy) {
8851   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8852 
8853   // Determine if the integer constant can be expressed as a floating point
8854   // number of the appropriate type.
8855   Expr::EvalResult EVResult;
8856   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8857 
8858   uint64_t Bits = 0;
8859   if (CstInt) {
8860     // Reject constants that would be truncated if they were converted to
8861     // the floating point type. Test by simple to/from conversion.
8862     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8863     //        could be avoided if there was a convertFromAPInt method
8864     //        which could signal back if implicit truncation occurred.
8865     llvm::APSInt Result = EVResult.Val.getInt();
8866     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8867     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8868                            llvm::APFloat::rmTowardZero);
8869     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8870                              !IntTy->hasSignedIntegerRepresentation());
8871     bool Ignored = false;
8872     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8873                            &Ignored);
8874     if (Result != ConvertBack)
8875       return true;
8876   } else {
8877     // Reject types that cannot be fully encoded into the mantissa of
8878     // the float.
8879     Bits = S.Context.getTypeSize(IntTy);
8880     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8881         S.Context.getFloatTypeSemantics(FloatTy));
8882     if (Bits > FloatPrec)
8883       return true;
8884   }
8885 
8886   return false;
8887 }
8888 
8889 /// Attempt to convert and splat Scalar into a vector whose types matches
8890 /// Vector following GCC conversion rules. The rule is that implicit
8891 /// conversion can occur when Scalar can be casted to match Vector's element
8892 /// type without causing truncation of Scalar.
8893 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8894                                         ExprResult *Vector) {
8895   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8896   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8897   const VectorType *VT = VectorTy->getAs<VectorType>();
8898 
8899   assert(!isa<ExtVectorType>(VT) &&
8900          "ExtVectorTypes should not be handled here!");
8901 
8902   QualType VectorEltTy = VT->getElementType();
8903 
8904   // Reject cases where the vector element type or the scalar element type are
8905   // not integral or floating point types.
8906   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8907     return true;
8908 
8909   // The conversion to apply to the scalar before splatting it,
8910   // if necessary.
8911   CastKind ScalarCast = CK_NoOp;
8912 
8913   // Accept cases where the vector elements are integers and the scalar is
8914   // an integer.
8915   // FIXME: Notionally if the scalar was a floating point value with a precise
8916   //        integral representation, we could cast it to an appropriate integer
8917   //        type and then perform the rest of the checks here. GCC will perform
8918   //        this conversion in some cases as determined by the input language.
8919   //        We should accept it on a language independent basis.
8920   if (VectorEltTy->isIntegralType(S.Context) &&
8921       ScalarTy->isIntegralType(S.Context) &&
8922       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8923 
8924     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8925       return true;
8926 
8927     ScalarCast = CK_IntegralCast;
8928   } else if (VectorEltTy->isRealFloatingType()) {
8929     if (ScalarTy->isRealFloatingType()) {
8930 
8931       // Reject cases where the scalar type is not a constant and has a higher
8932       // Order than the vector element type.
8933       llvm::APFloat Result(0.0);
8934       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8935       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8936       if (!CstScalar && Order < 0)
8937         return true;
8938 
8939       // If the scalar cannot be safely casted to the vector element type,
8940       // reject it.
8941       if (CstScalar) {
8942         bool Truncated = false;
8943         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8944                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8945         if (Truncated)
8946           return true;
8947       }
8948 
8949       ScalarCast = CK_FloatingCast;
8950     } else if (ScalarTy->isIntegralType(S.Context)) {
8951       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8952         return true;
8953 
8954       ScalarCast = CK_IntegralToFloating;
8955     } else
8956       return true;
8957   }
8958 
8959   // Adjust scalar if desired.
8960   if (Scalar) {
8961     if (ScalarCast != CK_NoOp)
8962       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8963     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8964   }
8965   return false;
8966 }
8967 
8968 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8969                                    SourceLocation Loc, bool IsCompAssign,
8970                                    bool AllowBothBool,
8971                                    bool AllowBoolConversions) {
8972   if (!IsCompAssign) {
8973     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8974     if (LHS.isInvalid())
8975       return QualType();
8976   }
8977   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8978   if (RHS.isInvalid())
8979     return QualType();
8980 
8981   // For conversion purposes, we ignore any qualifiers.
8982   // For example, "const float" and "float" are equivalent.
8983   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8984   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8985 
8986   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8987   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8988   assert(LHSVecType || RHSVecType);
8989 
8990   // AltiVec-style "vector bool op vector bool" combinations are allowed
8991   // for some operators but not others.
8992   if (!AllowBothBool &&
8993       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8994       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8995     return InvalidOperands(Loc, LHS, RHS);
8996 
8997   // If the vector types are identical, return.
8998   if (Context.hasSameType(LHSType, RHSType))
8999     return LHSType;
9000 
9001   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9002   if (LHSVecType && RHSVecType &&
9003       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9004     if (isa<ExtVectorType>(LHSVecType)) {
9005       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9006       return LHSType;
9007     }
9008 
9009     if (!IsCompAssign)
9010       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9011     return RHSType;
9012   }
9013 
9014   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9015   // can be mixed, with the result being the non-bool type.  The non-bool
9016   // operand must have integer element type.
9017   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9018       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9019       (Context.getTypeSize(LHSVecType->getElementType()) ==
9020        Context.getTypeSize(RHSVecType->getElementType()))) {
9021     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9022         LHSVecType->getElementType()->isIntegerType() &&
9023         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9024       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9025       return LHSType;
9026     }
9027     if (!IsCompAssign &&
9028         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9029         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9030         RHSVecType->getElementType()->isIntegerType()) {
9031       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9032       return RHSType;
9033     }
9034   }
9035 
9036   // If there's a vector type and a scalar, try to convert the scalar to
9037   // the vector element type and splat.
9038   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9039   if (!RHSVecType) {
9040     if (isa<ExtVectorType>(LHSVecType)) {
9041       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9042                                     LHSVecType->getElementType(), LHSType,
9043                                     DiagID))
9044         return LHSType;
9045     } else {
9046       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9047         return LHSType;
9048     }
9049   }
9050   if (!LHSVecType) {
9051     if (isa<ExtVectorType>(RHSVecType)) {
9052       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9053                                     LHSType, RHSVecType->getElementType(),
9054                                     RHSType, DiagID))
9055         return RHSType;
9056     } else {
9057       if (LHS.get()->getValueKind() == VK_LValue ||
9058           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9059         return RHSType;
9060     }
9061   }
9062 
9063   // FIXME: The code below also handles conversion between vectors and
9064   // non-scalars, we should break this down into fine grained specific checks
9065   // and emit proper diagnostics.
9066   QualType VecType = LHSVecType ? LHSType : RHSType;
9067   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9068   QualType OtherType = LHSVecType ? RHSType : LHSType;
9069   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9070   if (isLaxVectorConversion(OtherType, VecType)) {
9071     // If we're allowing lax vector conversions, only the total (data) size
9072     // needs to be the same. For non compound assignment, if one of the types is
9073     // scalar, the result is always the vector type.
9074     if (!IsCompAssign) {
9075       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9076       return VecType;
9077     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9078     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9079     // type. Note that this is already done by non-compound assignments in
9080     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9081     // <1 x T> -> T. The result is also a vector type.
9082     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9083                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9084       ExprResult *RHSExpr = &RHS;
9085       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9086       return VecType;
9087     }
9088   }
9089 
9090   // Okay, the expression is invalid.
9091 
9092   // If there's a non-vector, non-real operand, diagnose that.
9093   if ((!RHSVecType && !RHSType->isRealType()) ||
9094       (!LHSVecType && !LHSType->isRealType())) {
9095     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9096       << LHSType << RHSType
9097       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9098     return QualType();
9099   }
9100 
9101   // OpenCL V1.1 6.2.6.p1:
9102   // If the operands are of more than one vector type, then an error shall
9103   // occur. Implicit conversions between vector types are not permitted, per
9104   // section 6.2.1.
9105   if (getLangOpts().OpenCL &&
9106       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9107       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9108     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9109                                                            << RHSType;
9110     return QualType();
9111   }
9112 
9113 
9114   // If there is a vector type that is not a ExtVector and a scalar, we reach
9115   // this point if scalar could not be converted to the vector's element type
9116   // without truncation.
9117   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9118       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9119     QualType Scalar = LHSVecType ? RHSType : LHSType;
9120     QualType Vector = LHSVecType ? LHSType : RHSType;
9121     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9122     Diag(Loc,
9123          diag::err_typecheck_vector_not_convertable_implict_truncation)
9124         << ScalarOrVector << Scalar << Vector;
9125 
9126     return QualType();
9127   }
9128 
9129   // Otherwise, use the generic diagnostic.
9130   Diag(Loc, DiagID)
9131     << LHSType << RHSType
9132     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9133   return QualType();
9134 }
9135 
9136 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9137 // expression.  These are mainly cases where the null pointer is used as an
9138 // integer instead of a pointer.
9139 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9140                                 SourceLocation Loc, bool IsCompare) {
9141   // The canonical way to check for a GNU null is with isNullPointerConstant,
9142   // but we use a bit of a hack here for speed; this is a relatively
9143   // hot path, and isNullPointerConstant is slow.
9144   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9145   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9146 
9147   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9148 
9149   // Avoid analyzing cases where the result will either be invalid (and
9150   // diagnosed as such) or entirely valid and not something to warn about.
9151   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9152       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9153     return;
9154 
9155   // Comparison operations would not make sense with a null pointer no matter
9156   // what the other expression is.
9157   if (!IsCompare) {
9158     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9159         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9160         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9161     return;
9162   }
9163 
9164   // The rest of the operations only make sense with a null pointer
9165   // if the other expression is a pointer.
9166   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9167       NonNullType->canDecayToPointerType())
9168     return;
9169 
9170   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9171       << LHSNull /* LHS is NULL */ << NonNullType
9172       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9173 }
9174 
9175 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9176                                           SourceLocation Loc) {
9177   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9178   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9179   if (!LUE || !RUE)
9180     return;
9181   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9182       RUE->getKind() != UETT_SizeOf)
9183     return;
9184 
9185   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9186   QualType LHSTy = LHSArg->getType();
9187   QualType RHSTy;
9188 
9189   if (RUE->isArgumentType())
9190     RHSTy = RUE->getArgumentType();
9191   else
9192     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9193 
9194   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9195     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9196       return;
9197 
9198     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9199     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9200       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9201         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9202             << LHSArgDecl;
9203     }
9204   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9205     QualType ArrayElemTy = ArrayTy->getElementType();
9206     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9207         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9208         ArrayElemTy->isCharType() ||
9209         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9210       return;
9211     S.Diag(Loc, diag::warn_division_sizeof_array)
9212         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9213     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9214       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9215         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9216             << LHSArgDecl;
9217     }
9218 
9219     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9220   }
9221 }
9222 
9223 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9224                                                ExprResult &RHS,
9225                                                SourceLocation Loc, bool IsDiv) {
9226   // Check for division/remainder by zero.
9227   Expr::EvalResult RHSValue;
9228   if (!RHS.get()->isValueDependent() &&
9229       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9230       RHSValue.Val.getInt() == 0)
9231     S.DiagRuntimeBehavior(Loc, RHS.get(),
9232                           S.PDiag(diag::warn_remainder_division_by_zero)
9233                             << IsDiv << RHS.get()->getSourceRange());
9234 }
9235 
9236 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9237                                            SourceLocation Loc,
9238                                            bool IsCompAssign, bool IsDiv) {
9239   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9240 
9241   if (LHS.get()->getType()->isVectorType() ||
9242       RHS.get()->getType()->isVectorType())
9243     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9244                                /*AllowBothBool*/getLangOpts().AltiVec,
9245                                /*AllowBoolConversions*/false);
9246 
9247   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9248   if (LHS.isInvalid() || RHS.isInvalid())
9249     return QualType();
9250 
9251 
9252   if (compType.isNull() || !compType->isArithmeticType())
9253     return InvalidOperands(Loc, LHS, RHS);
9254   if (IsDiv) {
9255     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9256     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9257   }
9258   return compType;
9259 }
9260 
9261 QualType Sema::CheckRemainderOperands(
9262   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9263   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9264 
9265   if (LHS.get()->getType()->isVectorType() ||
9266       RHS.get()->getType()->isVectorType()) {
9267     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9268         RHS.get()->getType()->hasIntegerRepresentation())
9269       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9270                                  /*AllowBothBool*/getLangOpts().AltiVec,
9271                                  /*AllowBoolConversions*/false);
9272     return InvalidOperands(Loc, LHS, RHS);
9273   }
9274 
9275   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9276   if (LHS.isInvalid() || RHS.isInvalid())
9277     return QualType();
9278 
9279   if (compType.isNull() || !compType->isIntegerType())
9280     return InvalidOperands(Loc, LHS, RHS);
9281   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9282   return compType;
9283 }
9284 
9285 /// Diagnose invalid arithmetic on two void pointers.
9286 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9287                                                 Expr *LHSExpr, Expr *RHSExpr) {
9288   S.Diag(Loc, S.getLangOpts().CPlusPlus
9289                 ? diag::err_typecheck_pointer_arith_void_type
9290                 : diag::ext_gnu_void_ptr)
9291     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9292                             << RHSExpr->getSourceRange();
9293 }
9294 
9295 /// Diagnose invalid arithmetic on a void pointer.
9296 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9297                                             Expr *Pointer) {
9298   S.Diag(Loc, S.getLangOpts().CPlusPlus
9299                 ? diag::err_typecheck_pointer_arith_void_type
9300                 : diag::ext_gnu_void_ptr)
9301     << 0 /* one pointer */ << Pointer->getSourceRange();
9302 }
9303 
9304 /// Diagnose invalid arithmetic on a null pointer.
9305 ///
9306 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9307 /// idiom, which we recognize as a GNU extension.
9308 ///
9309 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9310                                             Expr *Pointer, bool IsGNUIdiom) {
9311   if (IsGNUIdiom)
9312     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9313       << Pointer->getSourceRange();
9314   else
9315     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9316       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9317 }
9318 
9319 /// Diagnose invalid arithmetic on two function pointers.
9320 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9321                                                     Expr *LHS, Expr *RHS) {
9322   assert(LHS->getType()->isAnyPointerType());
9323   assert(RHS->getType()->isAnyPointerType());
9324   S.Diag(Loc, S.getLangOpts().CPlusPlus
9325                 ? diag::err_typecheck_pointer_arith_function_type
9326                 : diag::ext_gnu_ptr_func_arith)
9327     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9328     // We only show the second type if it differs from the first.
9329     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9330                                                    RHS->getType())
9331     << RHS->getType()->getPointeeType()
9332     << LHS->getSourceRange() << RHS->getSourceRange();
9333 }
9334 
9335 /// Diagnose invalid arithmetic on a function pointer.
9336 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9337                                                 Expr *Pointer) {
9338   assert(Pointer->getType()->isAnyPointerType());
9339   S.Diag(Loc, S.getLangOpts().CPlusPlus
9340                 ? diag::err_typecheck_pointer_arith_function_type
9341                 : diag::ext_gnu_ptr_func_arith)
9342     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9343     << 0 /* one pointer, so only one type */
9344     << Pointer->getSourceRange();
9345 }
9346 
9347 /// Emit error if Operand is incomplete pointer type
9348 ///
9349 /// \returns True if pointer has incomplete type
9350 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9351                                                  Expr *Operand) {
9352   QualType ResType = Operand->getType();
9353   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9354     ResType = ResAtomicType->getValueType();
9355 
9356   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9357   QualType PointeeTy = ResType->getPointeeType();
9358   return S.RequireCompleteType(Loc, PointeeTy,
9359                                diag::err_typecheck_arithmetic_incomplete_type,
9360                                PointeeTy, Operand->getSourceRange());
9361 }
9362 
9363 /// Check the validity of an arithmetic pointer operand.
9364 ///
9365 /// If the operand has pointer type, this code will check for pointer types
9366 /// which are invalid in arithmetic operations. These will be diagnosed
9367 /// appropriately, including whether or not the use is supported as an
9368 /// extension.
9369 ///
9370 /// \returns True when the operand is valid to use (even if as an extension).
9371 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9372                                             Expr *Operand) {
9373   QualType ResType = Operand->getType();
9374   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9375     ResType = ResAtomicType->getValueType();
9376 
9377   if (!ResType->isAnyPointerType()) return true;
9378 
9379   QualType PointeeTy = ResType->getPointeeType();
9380   if (PointeeTy->isVoidType()) {
9381     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9382     return !S.getLangOpts().CPlusPlus;
9383   }
9384   if (PointeeTy->isFunctionType()) {
9385     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9386     return !S.getLangOpts().CPlusPlus;
9387   }
9388 
9389   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9390 
9391   return true;
9392 }
9393 
9394 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9395 /// operands.
9396 ///
9397 /// This routine will diagnose any invalid arithmetic on pointer operands much
9398 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9399 /// for emitting a single diagnostic even for operations where both LHS and RHS
9400 /// are (potentially problematic) pointers.
9401 ///
9402 /// \returns True when the operand is valid to use (even if as an extension).
9403 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9404                                                 Expr *LHSExpr, Expr *RHSExpr) {
9405   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9406   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9407   if (!isLHSPointer && !isRHSPointer) return true;
9408 
9409   QualType LHSPointeeTy, RHSPointeeTy;
9410   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9411   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9412 
9413   // if both are pointers check if operation is valid wrt address spaces
9414   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9415     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9416     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9417     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9418       S.Diag(Loc,
9419              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9420           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9421           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9422       return false;
9423     }
9424   }
9425 
9426   // Check for arithmetic on pointers to incomplete types.
9427   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9428   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9429   if (isLHSVoidPtr || isRHSVoidPtr) {
9430     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9431     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9432     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9433 
9434     return !S.getLangOpts().CPlusPlus;
9435   }
9436 
9437   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9438   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9439   if (isLHSFuncPtr || isRHSFuncPtr) {
9440     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9441     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9442                                                                 RHSExpr);
9443     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9444 
9445     return !S.getLangOpts().CPlusPlus;
9446   }
9447 
9448   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9449     return false;
9450   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9451     return false;
9452 
9453   return true;
9454 }
9455 
9456 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9457 /// literal.
9458 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9459                                   Expr *LHSExpr, Expr *RHSExpr) {
9460   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9461   Expr* IndexExpr = RHSExpr;
9462   if (!StrExpr) {
9463     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9464     IndexExpr = LHSExpr;
9465   }
9466 
9467   bool IsStringPlusInt = StrExpr &&
9468       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9469   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9470     return;
9471 
9472   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9473   Self.Diag(OpLoc, diag::warn_string_plus_int)
9474       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9475 
9476   // Only print a fixit for "str" + int, not for int + "str".
9477   if (IndexExpr == RHSExpr) {
9478     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9479     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9480         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9481         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9482         << FixItHint::CreateInsertion(EndLoc, "]");
9483   } else
9484     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9485 }
9486 
9487 /// Emit a warning when adding a char literal to a string.
9488 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9489                                    Expr *LHSExpr, Expr *RHSExpr) {
9490   const Expr *StringRefExpr = LHSExpr;
9491   const CharacterLiteral *CharExpr =
9492       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9493 
9494   if (!CharExpr) {
9495     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9496     StringRefExpr = RHSExpr;
9497   }
9498 
9499   if (!CharExpr || !StringRefExpr)
9500     return;
9501 
9502   const QualType StringType = StringRefExpr->getType();
9503 
9504   // Return if not a PointerType.
9505   if (!StringType->isAnyPointerType())
9506     return;
9507 
9508   // Return if not a CharacterType.
9509   if (!StringType->getPointeeType()->isAnyCharacterType())
9510     return;
9511 
9512   ASTContext &Ctx = Self.getASTContext();
9513   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9514 
9515   const QualType CharType = CharExpr->getType();
9516   if (!CharType->isAnyCharacterType() &&
9517       CharType->isIntegerType() &&
9518       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9519     Self.Diag(OpLoc, diag::warn_string_plus_char)
9520         << DiagRange << Ctx.CharTy;
9521   } else {
9522     Self.Diag(OpLoc, diag::warn_string_plus_char)
9523         << DiagRange << CharExpr->getType();
9524   }
9525 
9526   // Only print a fixit for str + char, not for char + str.
9527   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9528     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9529     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9530         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9531         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9532         << FixItHint::CreateInsertion(EndLoc, "]");
9533   } else {
9534     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9535   }
9536 }
9537 
9538 /// Emit error when two pointers are incompatible.
9539 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9540                                            Expr *LHSExpr, Expr *RHSExpr) {
9541   assert(LHSExpr->getType()->isAnyPointerType());
9542   assert(RHSExpr->getType()->isAnyPointerType());
9543   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9544     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9545     << RHSExpr->getSourceRange();
9546 }
9547 
9548 // C99 6.5.6
9549 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9550                                      SourceLocation Loc, BinaryOperatorKind Opc,
9551                                      QualType* CompLHSTy) {
9552   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9553 
9554   if (LHS.get()->getType()->isVectorType() ||
9555       RHS.get()->getType()->isVectorType()) {
9556     QualType compType = CheckVectorOperands(
9557         LHS, RHS, Loc, CompLHSTy,
9558         /*AllowBothBool*/getLangOpts().AltiVec,
9559         /*AllowBoolConversions*/getLangOpts().ZVector);
9560     if (CompLHSTy) *CompLHSTy = compType;
9561     return compType;
9562   }
9563 
9564   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9565   if (LHS.isInvalid() || RHS.isInvalid())
9566     return QualType();
9567 
9568   // Diagnose "string literal" '+' int and string '+' "char literal".
9569   if (Opc == BO_Add) {
9570     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9571     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9572   }
9573 
9574   // handle the common case first (both operands are arithmetic).
9575   if (!compType.isNull() && compType->isArithmeticType()) {
9576     if (CompLHSTy) *CompLHSTy = compType;
9577     return compType;
9578   }
9579 
9580   // Type-checking.  Ultimately the pointer's going to be in PExp;
9581   // note that we bias towards the LHS being the pointer.
9582   Expr *PExp = LHS.get(), *IExp = RHS.get();
9583 
9584   bool isObjCPointer;
9585   if (PExp->getType()->isPointerType()) {
9586     isObjCPointer = false;
9587   } else if (PExp->getType()->isObjCObjectPointerType()) {
9588     isObjCPointer = true;
9589   } else {
9590     std::swap(PExp, IExp);
9591     if (PExp->getType()->isPointerType()) {
9592       isObjCPointer = false;
9593     } else if (PExp->getType()->isObjCObjectPointerType()) {
9594       isObjCPointer = true;
9595     } else {
9596       return InvalidOperands(Loc, LHS, RHS);
9597     }
9598   }
9599   assert(PExp->getType()->isAnyPointerType());
9600 
9601   if (!IExp->getType()->isIntegerType())
9602     return InvalidOperands(Loc, LHS, RHS);
9603 
9604   // Adding to a null pointer results in undefined behavior.
9605   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9606           Context, Expr::NPC_ValueDependentIsNotNull)) {
9607     // In C++ adding zero to a null pointer is defined.
9608     Expr::EvalResult KnownVal;
9609     if (!getLangOpts().CPlusPlus ||
9610         (!IExp->isValueDependent() &&
9611          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9612           KnownVal.Val.getInt() != 0))) {
9613       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9614       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9615           Context, BO_Add, PExp, IExp);
9616       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9617     }
9618   }
9619 
9620   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9621     return QualType();
9622 
9623   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9624     return QualType();
9625 
9626   // Check array bounds for pointer arithemtic
9627   CheckArrayAccess(PExp, IExp);
9628 
9629   if (CompLHSTy) {
9630     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9631     if (LHSTy.isNull()) {
9632       LHSTy = LHS.get()->getType();
9633       if (LHSTy->isPromotableIntegerType())
9634         LHSTy = Context.getPromotedIntegerType(LHSTy);
9635     }
9636     *CompLHSTy = LHSTy;
9637   }
9638 
9639   return PExp->getType();
9640 }
9641 
9642 // C99 6.5.6
9643 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9644                                         SourceLocation Loc,
9645                                         QualType* CompLHSTy) {
9646   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9647 
9648   if (LHS.get()->getType()->isVectorType() ||
9649       RHS.get()->getType()->isVectorType()) {
9650     QualType compType = CheckVectorOperands(
9651         LHS, RHS, Loc, CompLHSTy,
9652         /*AllowBothBool*/getLangOpts().AltiVec,
9653         /*AllowBoolConversions*/getLangOpts().ZVector);
9654     if (CompLHSTy) *CompLHSTy = compType;
9655     return compType;
9656   }
9657 
9658   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9659   if (LHS.isInvalid() || RHS.isInvalid())
9660     return QualType();
9661 
9662   // Enforce type constraints: C99 6.5.6p3.
9663 
9664   // Handle the common case first (both operands are arithmetic).
9665   if (!compType.isNull() && compType->isArithmeticType()) {
9666     if (CompLHSTy) *CompLHSTy = compType;
9667     return compType;
9668   }
9669 
9670   // Either ptr - int   or   ptr - ptr.
9671   if (LHS.get()->getType()->isAnyPointerType()) {
9672     QualType lpointee = LHS.get()->getType()->getPointeeType();
9673 
9674     // Diagnose bad cases where we step over interface counts.
9675     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9676         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9677       return QualType();
9678 
9679     // The result type of a pointer-int computation is the pointer type.
9680     if (RHS.get()->getType()->isIntegerType()) {
9681       // Subtracting from a null pointer should produce a warning.
9682       // The last argument to the diagnose call says this doesn't match the
9683       // GNU int-to-pointer idiom.
9684       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9685                                            Expr::NPC_ValueDependentIsNotNull)) {
9686         // In C++ adding zero to a null pointer is defined.
9687         Expr::EvalResult KnownVal;
9688         if (!getLangOpts().CPlusPlus ||
9689             (!RHS.get()->isValueDependent() &&
9690              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9691               KnownVal.Val.getInt() != 0))) {
9692           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9693         }
9694       }
9695 
9696       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9697         return QualType();
9698 
9699       // Check array bounds for pointer arithemtic
9700       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9701                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9702 
9703       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9704       return LHS.get()->getType();
9705     }
9706 
9707     // Handle pointer-pointer subtractions.
9708     if (const PointerType *RHSPTy
9709           = RHS.get()->getType()->getAs<PointerType>()) {
9710       QualType rpointee = RHSPTy->getPointeeType();
9711 
9712       if (getLangOpts().CPlusPlus) {
9713         // Pointee types must be the same: C++ [expr.add]
9714         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9715           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9716         }
9717       } else {
9718         // Pointee types must be compatible C99 6.5.6p3
9719         if (!Context.typesAreCompatible(
9720                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9721                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9722           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9723           return QualType();
9724         }
9725       }
9726 
9727       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9728                                                LHS.get(), RHS.get()))
9729         return QualType();
9730 
9731       // FIXME: Add warnings for nullptr - ptr.
9732 
9733       // The pointee type may have zero size.  As an extension, a structure or
9734       // union may have zero size or an array may have zero length.  In this
9735       // case subtraction does not make sense.
9736       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9737         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9738         if (ElementSize.isZero()) {
9739           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9740             << rpointee.getUnqualifiedType()
9741             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9742         }
9743       }
9744 
9745       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9746       return Context.getPointerDiffType();
9747     }
9748   }
9749 
9750   return InvalidOperands(Loc, LHS, RHS);
9751 }
9752 
9753 static bool isScopedEnumerationType(QualType T) {
9754   if (const EnumType *ET = T->getAs<EnumType>())
9755     return ET->getDecl()->isScoped();
9756   return false;
9757 }
9758 
9759 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9760                                    SourceLocation Loc, BinaryOperatorKind Opc,
9761                                    QualType LHSType) {
9762   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9763   // so skip remaining warnings as we don't want to modify values within Sema.
9764   if (S.getLangOpts().OpenCL)
9765     return;
9766 
9767   // Check right/shifter operand
9768   Expr::EvalResult RHSResult;
9769   if (RHS.get()->isValueDependent() ||
9770       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9771     return;
9772   llvm::APSInt Right = RHSResult.Val.getInt();
9773 
9774   if (Right.isNegative()) {
9775     S.DiagRuntimeBehavior(Loc, RHS.get(),
9776                           S.PDiag(diag::warn_shift_negative)
9777                             << RHS.get()->getSourceRange());
9778     return;
9779   }
9780   llvm::APInt LeftBits(Right.getBitWidth(),
9781                        S.Context.getTypeSize(LHS.get()->getType()));
9782   if (Right.uge(LeftBits)) {
9783     S.DiagRuntimeBehavior(Loc, RHS.get(),
9784                           S.PDiag(diag::warn_shift_gt_typewidth)
9785                             << RHS.get()->getSourceRange());
9786     return;
9787   }
9788   if (Opc != BO_Shl)
9789     return;
9790 
9791   // When left shifting an ICE which is signed, we can check for overflow which
9792   // according to C++ standards prior to C++2a has undefined behavior
9793   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9794   // more than the maximum value representable in the result type, so never
9795   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9796   // expression is still probably a bug.)
9797   Expr::EvalResult LHSResult;
9798   if (LHS.get()->isValueDependent() ||
9799       LHSType->hasUnsignedIntegerRepresentation() ||
9800       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9801     return;
9802   llvm::APSInt Left = LHSResult.Val.getInt();
9803 
9804   // If LHS does not have a signed type and non-negative value
9805   // then, the behavior is undefined before C++2a. Warn about it.
9806   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9807       !S.getLangOpts().CPlusPlus2a) {
9808     S.DiagRuntimeBehavior(Loc, LHS.get(),
9809                           S.PDiag(diag::warn_shift_lhs_negative)
9810                             << LHS.get()->getSourceRange());
9811     return;
9812   }
9813 
9814   llvm::APInt ResultBits =
9815       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9816   if (LeftBits.uge(ResultBits))
9817     return;
9818   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9819   Result = Result.shl(Right);
9820 
9821   // Print the bit representation of the signed integer as an unsigned
9822   // hexadecimal number.
9823   SmallString<40> HexResult;
9824   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9825 
9826   // If we are only missing a sign bit, this is less likely to result in actual
9827   // bugs -- if the result is cast back to an unsigned type, it will have the
9828   // expected value. Thus we place this behind a different warning that can be
9829   // turned off separately if needed.
9830   if (LeftBits == ResultBits - 1) {
9831     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9832         << HexResult << LHSType
9833         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9834     return;
9835   }
9836 
9837   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9838     << HexResult.str() << Result.getMinSignedBits() << LHSType
9839     << Left.getBitWidth() << LHS.get()->getSourceRange()
9840     << RHS.get()->getSourceRange();
9841 }
9842 
9843 /// Return the resulting type when a vector is shifted
9844 ///        by a scalar or vector shift amount.
9845 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9846                                  SourceLocation Loc, bool IsCompAssign) {
9847   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9848   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9849       !LHS.get()->getType()->isVectorType()) {
9850     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9851       << RHS.get()->getType() << LHS.get()->getType()
9852       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9853     return QualType();
9854   }
9855 
9856   if (!IsCompAssign) {
9857     LHS = S.UsualUnaryConversions(LHS.get());
9858     if (LHS.isInvalid()) return QualType();
9859   }
9860 
9861   RHS = S.UsualUnaryConversions(RHS.get());
9862   if (RHS.isInvalid()) return QualType();
9863 
9864   QualType LHSType = LHS.get()->getType();
9865   // Note that LHS might be a scalar because the routine calls not only in
9866   // OpenCL case.
9867   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9868   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9869 
9870   // Note that RHS might not be a vector.
9871   QualType RHSType = RHS.get()->getType();
9872   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9873   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9874 
9875   // The operands need to be integers.
9876   if (!LHSEleType->isIntegerType()) {
9877     S.Diag(Loc, diag::err_typecheck_expect_int)
9878       << LHS.get()->getType() << LHS.get()->getSourceRange();
9879     return QualType();
9880   }
9881 
9882   if (!RHSEleType->isIntegerType()) {
9883     S.Diag(Loc, diag::err_typecheck_expect_int)
9884       << RHS.get()->getType() << RHS.get()->getSourceRange();
9885     return QualType();
9886   }
9887 
9888   if (!LHSVecTy) {
9889     assert(RHSVecTy);
9890     if (IsCompAssign)
9891       return RHSType;
9892     if (LHSEleType != RHSEleType) {
9893       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9894       LHSEleType = RHSEleType;
9895     }
9896     QualType VecTy =
9897         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9898     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9899     LHSType = VecTy;
9900   } else if (RHSVecTy) {
9901     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9902     // are applied component-wise. So if RHS is a vector, then ensure
9903     // that the number of elements is the same as LHS...
9904     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9905       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9906         << LHS.get()->getType() << RHS.get()->getType()
9907         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9908       return QualType();
9909     }
9910     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9911       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9912       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9913       if (LHSBT != RHSBT &&
9914           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9915         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9916             << LHS.get()->getType() << RHS.get()->getType()
9917             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9918       }
9919     }
9920   } else {
9921     // ...else expand RHS to match the number of elements in LHS.
9922     QualType VecTy =
9923       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9924     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9925   }
9926 
9927   return LHSType;
9928 }
9929 
9930 // C99 6.5.7
9931 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9932                                   SourceLocation Loc, BinaryOperatorKind Opc,
9933                                   bool IsCompAssign) {
9934   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9935 
9936   // Vector shifts promote their scalar inputs to vector type.
9937   if (LHS.get()->getType()->isVectorType() ||
9938       RHS.get()->getType()->isVectorType()) {
9939     if (LangOpts.ZVector) {
9940       // The shift operators for the z vector extensions work basically
9941       // like general shifts, except that neither the LHS nor the RHS is
9942       // allowed to be a "vector bool".
9943       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9944         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9945           return InvalidOperands(Loc, LHS, RHS);
9946       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9947         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9948           return InvalidOperands(Loc, LHS, RHS);
9949     }
9950     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9951   }
9952 
9953   // Shifts don't perform usual arithmetic conversions, they just do integer
9954   // promotions on each operand. C99 6.5.7p3
9955 
9956   // For the LHS, do usual unary conversions, but then reset them away
9957   // if this is a compound assignment.
9958   ExprResult OldLHS = LHS;
9959   LHS = UsualUnaryConversions(LHS.get());
9960   if (LHS.isInvalid())
9961     return QualType();
9962   QualType LHSType = LHS.get()->getType();
9963   if (IsCompAssign) LHS = OldLHS;
9964 
9965   // The RHS is simpler.
9966   RHS = UsualUnaryConversions(RHS.get());
9967   if (RHS.isInvalid())
9968     return QualType();
9969   QualType RHSType = RHS.get()->getType();
9970 
9971   // C99 6.5.7p2: Each of the operands shall have integer type.
9972   if (!LHSType->hasIntegerRepresentation() ||
9973       !RHSType->hasIntegerRepresentation())
9974     return InvalidOperands(Loc, LHS, RHS);
9975 
9976   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9977   // hasIntegerRepresentation() above instead of this.
9978   if (isScopedEnumerationType(LHSType) ||
9979       isScopedEnumerationType(RHSType)) {
9980     return InvalidOperands(Loc, LHS, RHS);
9981   }
9982   // Sanity-check shift operands
9983   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9984 
9985   // "The type of the result is that of the promoted left operand."
9986   return LHSType;
9987 }
9988 
9989 /// If two different enums are compared, raise a warning.
9990 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9991                                 Expr *RHS) {
9992   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9993   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9994 
9995   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9996   if (!LHSEnumType)
9997     return;
9998   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9999   if (!RHSEnumType)
10000     return;
10001 
10002   // Ignore anonymous enums.
10003   if (!LHSEnumType->getDecl()->getIdentifier() &&
10004       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10005     return;
10006   if (!RHSEnumType->getDecl()->getIdentifier() &&
10007       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10008     return;
10009 
10010   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
10011     return;
10012 
10013   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
10014       << LHSStrippedType << RHSStrippedType
10015       << LHS->getSourceRange() << RHS->getSourceRange();
10016 }
10017 
10018 /// Diagnose bad pointer comparisons.
10019 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10020                                               ExprResult &LHS, ExprResult &RHS,
10021                                               bool IsError) {
10022   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10023                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10024     << LHS.get()->getType() << RHS.get()->getType()
10025     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10026 }
10027 
10028 /// Returns false if the pointers are converted to a composite type,
10029 /// true otherwise.
10030 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10031                                            ExprResult &LHS, ExprResult &RHS) {
10032   // C++ [expr.rel]p2:
10033   //   [...] Pointer conversions (4.10) and qualification
10034   //   conversions (4.4) are performed on pointer operands (or on
10035   //   a pointer operand and a null pointer constant) to bring
10036   //   them to their composite pointer type. [...]
10037   //
10038   // C++ [expr.eq]p1 uses the same notion for (in)equality
10039   // comparisons of pointers.
10040 
10041   QualType LHSType = LHS.get()->getType();
10042   QualType RHSType = RHS.get()->getType();
10043   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10044          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10045 
10046   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10047   if (T.isNull()) {
10048     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
10049         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
10050       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10051     else
10052       S.InvalidOperands(Loc, LHS, RHS);
10053     return true;
10054   }
10055 
10056   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10057   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10058   return false;
10059 }
10060 
10061 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10062                                                     ExprResult &LHS,
10063                                                     ExprResult &RHS,
10064                                                     bool IsError) {
10065   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10066                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10067     << LHS.get()->getType() << RHS.get()->getType()
10068     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10069 }
10070 
10071 static bool isObjCObjectLiteral(ExprResult &E) {
10072   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10073   case Stmt::ObjCArrayLiteralClass:
10074   case Stmt::ObjCDictionaryLiteralClass:
10075   case Stmt::ObjCStringLiteralClass:
10076   case Stmt::ObjCBoxedExprClass:
10077     return true;
10078   default:
10079     // Note that ObjCBoolLiteral is NOT an object literal!
10080     return false;
10081   }
10082 }
10083 
10084 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10085   const ObjCObjectPointerType *Type =
10086     LHS->getType()->getAs<ObjCObjectPointerType>();
10087 
10088   // If this is not actually an Objective-C object, bail out.
10089   if (!Type)
10090     return false;
10091 
10092   // Get the LHS object's interface type.
10093   QualType InterfaceType = Type->getPointeeType();
10094 
10095   // If the RHS isn't an Objective-C object, bail out.
10096   if (!RHS->getType()->isObjCObjectPointerType())
10097     return false;
10098 
10099   // Try to find the -isEqual: method.
10100   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10101   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10102                                                       InterfaceType,
10103                                                       /*IsInstance=*/true);
10104   if (!Method) {
10105     if (Type->isObjCIdType()) {
10106       // For 'id', just check the global pool.
10107       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10108                                                   /*receiverId=*/true);
10109     } else {
10110       // Check protocols.
10111       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10112                                              /*IsInstance=*/true);
10113     }
10114   }
10115 
10116   if (!Method)
10117     return false;
10118 
10119   QualType T = Method->parameters()[0]->getType();
10120   if (!T->isObjCObjectPointerType())
10121     return false;
10122 
10123   QualType R = Method->getReturnType();
10124   if (!R->isScalarType())
10125     return false;
10126 
10127   return true;
10128 }
10129 
10130 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10131   FromE = FromE->IgnoreParenImpCasts();
10132   switch (FromE->getStmtClass()) {
10133     default:
10134       break;
10135     case Stmt::ObjCStringLiteralClass:
10136       // "string literal"
10137       return LK_String;
10138     case Stmt::ObjCArrayLiteralClass:
10139       // "array literal"
10140       return LK_Array;
10141     case Stmt::ObjCDictionaryLiteralClass:
10142       // "dictionary literal"
10143       return LK_Dictionary;
10144     case Stmt::BlockExprClass:
10145       return LK_Block;
10146     case Stmt::ObjCBoxedExprClass: {
10147       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10148       switch (Inner->getStmtClass()) {
10149         case Stmt::IntegerLiteralClass:
10150         case Stmt::FloatingLiteralClass:
10151         case Stmt::CharacterLiteralClass:
10152         case Stmt::ObjCBoolLiteralExprClass:
10153         case Stmt::CXXBoolLiteralExprClass:
10154           // "numeric literal"
10155           return LK_Numeric;
10156         case Stmt::ImplicitCastExprClass: {
10157           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10158           // Boolean literals can be represented by implicit casts.
10159           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10160             return LK_Numeric;
10161           break;
10162         }
10163         default:
10164           break;
10165       }
10166       return LK_Boxed;
10167     }
10168   }
10169   return LK_None;
10170 }
10171 
10172 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10173                                           ExprResult &LHS, ExprResult &RHS,
10174                                           BinaryOperator::Opcode Opc){
10175   Expr *Literal;
10176   Expr *Other;
10177   if (isObjCObjectLiteral(LHS)) {
10178     Literal = LHS.get();
10179     Other = RHS.get();
10180   } else {
10181     Literal = RHS.get();
10182     Other = LHS.get();
10183   }
10184 
10185   // Don't warn on comparisons against nil.
10186   Other = Other->IgnoreParenCasts();
10187   if (Other->isNullPointerConstant(S.getASTContext(),
10188                                    Expr::NPC_ValueDependentIsNotNull))
10189     return;
10190 
10191   // This should be kept in sync with warn_objc_literal_comparison.
10192   // LK_String should always be after the other literals, since it has its own
10193   // warning flag.
10194   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10195   assert(LiteralKind != Sema::LK_Block);
10196   if (LiteralKind == Sema::LK_None) {
10197     llvm_unreachable("Unknown Objective-C object literal kind");
10198   }
10199 
10200   if (LiteralKind == Sema::LK_String)
10201     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10202       << Literal->getSourceRange();
10203   else
10204     S.Diag(Loc, diag::warn_objc_literal_comparison)
10205       << LiteralKind << Literal->getSourceRange();
10206 
10207   if (BinaryOperator::isEqualityOp(Opc) &&
10208       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10209     SourceLocation Start = LHS.get()->getBeginLoc();
10210     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10211     CharSourceRange OpRange =
10212       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10213 
10214     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10215       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10216       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10217       << FixItHint::CreateInsertion(End, "]");
10218   }
10219 }
10220 
10221 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10222 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10223                                            ExprResult &RHS, SourceLocation Loc,
10224                                            BinaryOperatorKind Opc) {
10225   // Check that left hand side is !something.
10226   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10227   if (!UO || UO->getOpcode() != UO_LNot) return;
10228 
10229   // Only check if the right hand side is non-bool arithmetic type.
10230   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10231 
10232   // Make sure that the something in !something is not bool.
10233   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10234   if (SubExpr->isKnownToHaveBooleanValue()) return;
10235 
10236   // Emit warning.
10237   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10238   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10239       << Loc << IsBitwiseOp;
10240 
10241   // First note suggest !(x < y)
10242   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10243   SourceLocation FirstClose = RHS.get()->getEndLoc();
10244   FirstClose = S.getLocForEndOfToken(FirstClose);
10245   if (FirstClose.isInvalid())
10246     FirstOpen = SourceLocation();
10247   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10248       << IsBitwiseOp
10249       << FixItHint::CreateInsertion(FirstOpen, "(")
10250       << FixItHint::CreateInsertion(FirstClose, ")");
10251 
10252   // Second note suggests (!x) < y
10253   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10254   SourceLocation SecondClose = LHS.get()->getEndLoc();
10255   SecondClose = S.getLocForEndOfToken(SecondClose);
10256   if (SecondClose.isInvalid())
10257     SecondOpen = SourceLocation();
10258   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10259       << FixItHint::CreateInsertion(SecondOpen, "(")
10260       << FixItHint::CreateInsertion(SecondClose, ")");
10261 }
10262 
10263 // Returns true if E refers to a non-weak array.
10264 static bool checkForArray(const Expr *E) {
10265   const ValueDecl *D = nullptr;
10266   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10267     D = DR->getDecl();
10268   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10269     if (Mem->isImplicitAccess())
10270       D = Mem->getMemberDecl();
10271   }
10272   if (!D)
10273     return false;
10274   return D->getType()->isArrayType() && !D->isWeak();
10275 }
10276 
10277 /// Diagnose some forms of syntactically-obvious tautological comparison.
10278 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10279                                            Expr *LHS, Expr *RHS,
10280                                            BinaryOperatorKind Opc) {
10281   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10282   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10283 
10284   QualType LHSType = LHS->getType();
10285   QualType RHSType = RHS->getType();
10286   if (LHSType->hasFloatingRepresentation() ||
10287       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10288       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10289       S.inTemplateInstantiation())
10290     return;
10291 
10292   // Comparisons between two array types are ill-formed for operator<=>, so
10293   // we shouldn't emit any additional warnings about it.
10294   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10295     return;
10296 
10297   // For non-floating point types, check for self-comparisons of the form
10298   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10299   // often indicate logic errors in the program.
10300   //
10301   // NOTE: Don't warn about comparison expressions resulting from macro
10302   // expansion. Also don't warn about comparisons which are only self
10303   // comparisons within a template instantiation. The warnings should catch
10304   // obvious cases in the definition of the template anyways. The idea is to
10305   // warn when the typed comparison operator will always evaluate to the same
10306   // result.
10307 
10308   // Used for indexing into %select in warn_comparison_always
10309   enum {
10310     AlwaysConstant,
10311     AlwaysTrue,
10312     AlwaysFalse,
10313     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10314   };
10315 
10316   if (Expr::isSameComparisonOperand(LHS, RHS)) {
10317     unsigned Result;
10318     switch (Opc) {
10319     case BO_EQ: case BO_LE: case BO_GE:
10320       Result = AlwaysTrue;
10321       break;
10322     case BO_NE: case BO_LT: case BO_GT:
10323       Result = AlwaysFalse;
10324       break;
10325     case BO_Cmp:
10326       Result = AlwaysEqual;
10327       break;
10328     default:
10329       Result = AlwaysConstant;
10330       break;
10331     }
10332     S.DiagRuntimeBehavior(Loc, nullptr,
10333                           S.PDiag(diag::warn_comparison_always)
10334                               << 0 /*self-comparison*/
10335                               << Result);
10336   } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10337     // What is it always going to evaluate to?
10338     unsigned Result;
10339     switch(Opc) {
10340     case BO_EQ: // e.g. array1 == array2
10341       Result = AlwaysFalse;
10342       break;
10343     case BO_NE: // e.g. array1 != array2
10344       Result = AlwaysTrue;
10345       break;
10346     default: // e.g. array1 <= array2
10347       // The best we can say is 'a constant'
10348       Result = AlwaysConstant;
10349       break;
10350     }
10351     S.DiagRuntimeBehavior(Loc, nullptr,
10352                           S.PDiag(diag::warn_comparison_always)
10353                               << 1 /*array comparison*/
10354                               << Result);
10355   }
10356 
10357   if (isa<CastExpr>(LHSStripped))
10358     LHSStripped = LHSStripped->IgnoreParenCasts();
10359   if (isa<CastExpr>(RHSStripped))
10360     RHSStripped = RHSStripped->IgnoreParenCasts();
10361 
10362   // Warn about comparisons against a string constant (unless the other
10363   // operand is null); the user probably wants strcmp.
10364   Expr *LiteralString = nullptr;
10365   Expr *LiteralStringStripped = nullptr;
10366   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10367       !RHSStripped->isNullPointerConstant(S.Context,
10368                                           Expr::NPC_ValueDependentIsNull)) {
10369     LiteralString = LHS;
10370     LiteralStringStripped = LHSStripped;
10371   } else if ((isa<StringLiteral>(RHSStripped) ||
10372               isa<ObjCEncodeExpr>(RHSStripped)) &&
10373              !LHSStripped->isNullPointerConstant(S.Context,
10374                                           Expr::NPC_ValueDependentIsNull)) {
10375     LiteralString = RHS;
10376     LiteralStringStripped = RHSStripped;
10377   }
10378 
10379   if (LiteralString) {
10380     S.DiagRuntimeBehavior(Loc, nullptr,
10381                           S.PDiag(diag::warn_stringcompare)
10382                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10383                               << LiteralString->getSourceRange());
10384   }
10385 }
10386 
10387 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10388   switch (CK) {
10389   default: {
10390 #ifndef NDEBUG
10391     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10392                  << "\n";
10393 #endif
10394     llvm_unreachable("unhandled cast kind");
10395   }
10396   case CK_UserDefinedConversion:
10397     return ICK_Identity;
10398   case CK_LValueToRValue:
10399     return ICK_Lvalue_To_Rvalue;
10400   case CK_ArrayToPointerDecay:
10401     return ICK_Array_To_Pointer;
10402   case CK_FunctionToPointerDecay:
10403     return ICK_Function_To_Pointer;
10404   case CK_IntegralCast:
10405     return ICK_Integral_Conversion;
10406   case CK_FloatingCast:
10407     return ICK_Floating_Conversion;
10408   case CK_IntegralToFloating:
10409   case CK_FloatingToIntegral:
10410     return ICK_Floating_Integral;
10411   case CK_IntegralComplexCast:
10412   case CK_FloatingComplexCast:
10413   case CK_FloatingComplexToIntegralComplex:
10414   case CK_IntegralComplexToFloatingComplex:
10415     return ICK_Complex_Conversion;
10416   case CK_FloatingComplexToReal:
10417   case CK_FloatingRealToComplex:
10418   case CK_IntegralComplexToReal:
10419   case CK_IntegralRealToComplex:
10420     return ICK_Complex_Real;
10421   }
10422 }
10423 
10424 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10425                                              QualType FromType,
10426                                              SourceLocation Loc) {
10427   // Check for a narrowing implicit conversion.
10428   StandardConversionSequence SCS;
10429   SCS.setAsIdentityConversion();
10430   SCS.setToType(0, FromType);
10431   SCS.setToType(1, ToType);
10432   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10433     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10434 
10435   APValue PreNarrowingValue;
10436   QualType PreNarrowingType;
10437   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10438                                PreNarrowingType,
10439                                /*IgnoreFloatToIntegralConversion*/ true)) {
10440   case NK_Dependent_Narrowing:
10441     // Implicit conversion to a narrower type, but the expression is
10442     // value-dependent so we can't tell whether it's actually narrowing.
10443   case NK_Not_Narrowing:
10444     return false;
10445 
10446   case NK_Constant_Narrowing:
10447     // Implicit conversion to a narrower type, and the value is not a constant
10448     // expression.
10449     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10450         << /*Constant*/ 1
10451         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10452     return true;
10453 
10454   case NK_Variable_Narrowing:
10455     // Implicit conversion to a narrower type, and the value is not a constant
10456     // expression.
10457   case NK_Type_Narrowing:
10458     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10459         << /*Constant*/ 0 << FromType << ToType;
10460     // TODO: It's not a constant expression, but what if the user intended it
10461     // to be? Can we produce notes to help them figure out why it isn't?
10462     return true;
10463   }
10464   llvm_unreachable("unhandled case in switch");
10465 }
10466 
10467 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10468                                                          ExprResult &LHS,
10469                                                          ExprResult &RHS,
10470                                                          SourceLocation Loc) {
10471   using CCT = ComparisonCategoryType;
10472 
10473   QualType LHSType = LHS.get()->getType();
10474   QualType RHSType = RHS.get()->getType();
10475   // Dig out the original argument type and expression before implicit casts
10476   // were applied. These are the types/expressions we need to check the
10477   // [expr.spaceship] requirements against.
10478   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10479   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10480   QualType LHSStrippedType = LHSStripped.get()->getType();
10481   QualType RHSStrippedType = RHSStripped.get()->getType();
10482 
10483   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10484   // other is not, the program is ill-formed.
10485   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10486     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10487     return QualType();
10488   }
10489 
10490   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10491                     RHSStrippedType->isEnumeralType();
10492   if (NumEnumArgs == 1) {
10493     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10494     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10495     if (OtherTy->hasFloatingRepresentation()) {
10496       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10497       return QualType();
10498     }
10499   }
10500   if (NumEnumArgs == 2) {
10501     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10502     // type E, the operator yields the result of converting the operands
10503     // to the underlying type of E and applying <=> to the converted operands.
10504     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10505       S.InvalidOperands(Loc, LHS, RHS);
10506       return QualType();
10507     }
10508     QualType IntType =
10509         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10510     assert(IntType->isArithmeticType());
10511 
10512     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10513     // promote the boolean type, and all other promotable integer types, to
10514     // avoid this.
10515     if (IntType->isPromotableIntegerType())
10516       IntType = S.Context.getPromotedIntegerType(IntType);
10517 
10518     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10519     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10520     LHSType = RHSType = IntType;
10521   }
10522 
10523   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10524   // usual arithmetic conversions are applied to the operands.
10525   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10526   if (LHS.isInvalid() || RHS.isInvalid())
10527     return QualType();
10528   if (Type.isNull())
10529     return S.InvalidOperands(Loc, LHS, RHS);
10530   assert(Type->isArithmeticType() || Type->isEnumeralType());
10531 
10532   bool HasNarrowing = checkThreeWayNarrowingConversion(
10533       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10534   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10535                                                    RHS.get()->getBeginLoc());
10536   if (HasNarrowing)
10537     return QualType();
10538 
10539   assert(!Type.isNull() && "composite type for <=> has not been set");
10540 
10541   auto TypeKind = [&]() {
10542     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10543       if (CT->getElementType()->hasFloatingRepresentation())
10544         return CCT::WeakEquality;
10545       return CCT::StrongEquality;
10546     }
10547     if (Type->isIntegralOrEnumerationType())
10548       return CCT::StrongOrdering;
10549     if (Type->hasFloatingRepresentation())
10550       return CCT::PartialOrdering;
10551     llvm_unreachable("other types are unimplemented");
10552   }();
10553 
10554   return S.CheckComparisonCategoryType(TypeKind, Loc);
10555 }
10556 
10557 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10558                                                  ExprResult &RHS,
10559                                                  SourceLocation Loc,
10560                                                  BinaryOperatorKind Opc) {
10561   if (Opc == BO_Cmp)
10562     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10563 
10564   // C99 6.5.8p3 / C99 6.5.9p4
10565   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10566   if (LHS.isInvalid() || RHS.isInvalid())
10567     return QualType();
10568   if (Type.isNull())
10569     return S.InvalidOperands(Loc, LHS, RHS);
10570   assert(Type->isArithmeticType() || Type->isEnumeralType());
10571 
10572   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10573 
10574   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10575     return S.InvalidOperands(Loc, LHS, RHS);
10576 
10577   // Check for comparisons of floating point operands using != and ==.
10578   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10579     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10580 
10581   // The result of comparisons is 'bool' in C++, 'int' in C.
10582   return S.Context.getLogicalOperationType();
10583 }
10584 
10585 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10586   if (!NullE.get()->getType()->isAnyPointerType())
10587     return;
10588   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10589   if (!E.get()->getType()->isAnyPointerType() &&
10590       E.get()->isNullPointerConstant(Context,
10591                                      Expr::NPC_ValueDependentIsNotNull) ==
10592         Expr::NPCK_ZeroExpression) {
10593     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10594       if (CL->getValue() == 0)
10595         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10596             << NullValue
10597             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10598                                             NullValue ? "NULL" : "(void *)0");
10599     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10600         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10601         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10602         if (T == Context.CharTy)
10603           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10604               << NullValue
10605               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10606                                               NullValue ? "NULL" : "(void *)0");
10607       }
10608   }
10609 }
10610 
10611 // C99 6.5.8, C++ [expr.rel]
10612 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10613                                     SourceLocation Loc,
10614                                     BinaryOperatorKind Opc) {
10615   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10616   bool IsThreeWay = Opc == BO_Cmp;
10617   auto IsAnyPointerType = [](ExprResult E) {
10618     QualType Ty = E.get()->getType();
10619     return Ty->isPointerType() || Ty->isMemberPointerType();
10620   };
10621 
10622   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10623   // type, array-to-pointer, ..., conversions are performed on both operands to
10624   // bring them to their composite type.
10625   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10626   // any type-related checks.
10627   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10628     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10629     if (LHS.isInvalid())
10630       return QualType();
10631     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10632     if (RHS.isInvalid())
10633       return QualType();
10634   } else {
10635     LHS = DefaultLvalueConversion(LHS.get());
10636     if (LHS.isInvalid())
10637       return QualType();
10638     RHS = DefaultLvalueConversion(RHS.get());
10639     if (RHS.isInvalid())
10640       return QualType();
10641   }
10642 
10643   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10644   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10645     CheckPtrComparisonWithNullChar(LHS, RHS);
10646     CheckPtrComparisonWithNullChar(RHS, LHS);
10647   }
10648 
10649   // Handle vector comparisons separately.
10650   if (LHS.get()->getType()->isVectorType() ||
10651       RHS.get()->getType()->isVectorType())
10652     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10653 
10654   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10655   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10656 
10657   QualType LHSType = LHS.get()->getType();
10658   QualType RHSType = RHS.get()->getType();
10659   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10660       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10661     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10662 
10663   const Expr::NullPointerConstantKind LHSNullKind =
10664       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10665   const Expr::NullPointerConstantKind RHSNullKind =
10666       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10667   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10668   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10669 
10670   auto computeResultTy = [&]() {
10671     if (Opc != BO_Cmp)
10672       return Context.getLogicalOperationType();
10673     assert(getLangOpts().CPlusPlus);
10674     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10675 
10676     QualType CompositeTy = LHS.get()->getType();
10677     assert(!CompositeTy->isReferenceType());
10678 
10679     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10680       return CheckComparisonCategoryType(Kind, Loc);
10681     };
10682 
10683     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10684     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10685     // result is of type std::strong_equality
10686     if (CompositeTy->isFunctionPointerType() ||
10687         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10688       // FIXME: consider making the function pointer case produce
10689       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10690       // and direction polls
10691       return buildResultTy(ComparisonCategoryType::StrongEquality);
10692 
10693     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10694     // pointer type, p <=> q is of type std::strong_ordering.
10695     if (CompositeTy->isPointerType()) {
10696       // P0946R0: Comparisons between a null pointer constant and an object
10697       // pointer result in std::strong_equality
10698       if (LHSIsNull != RHSIsNull)
10699         return buildResultTy(ComparisonCategoryType::StrongEquality);
10700       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10701     }
10702     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10703     // TODO: Extend support for operator<=> to ObjC types.
10704     return InvalidOperands(Loc, LHS, RHS);
10705   };
10706 
10707 
10708   if (!IsRelational && LHSIsNull != RHSIsNull) {
10709     bool IsEquality = Opc == BO_EQ;
10710     if (RHSIsNull)
10711       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10712                                    RHS.get()->getSourceRange());
10713     else
10714       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10715                                    LHS.get()->getSourceRange());
10716   }
10717 
10718   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10719       (RHSType->isIntegerType() && !RHSIsNull)) {
10720     // Skip normal pointer conversion checks in this case; we have better
10721     // diagnostics for this below.
10722   } else if (getLangOpts().CPlusPlus) {
10723     // Equality comparison of a function pointer to a void pointer is invalid,
10724     // but we allow it as an extension.
10725     // FIXME: If we really want to allow this, should it be part of composite
10726     // pointer type computation so it works in conditionals too?
10727     if (!IsRelational &&
10728         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10729          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10730       // This is a gcc extension compatibility comparison.
10731       // In a SFINAE context, we treat this as a hard error to maintain
10732       // conformance with the C++ standard.
10733       diagnoseFunctionPointerToVoidComparison(
10734           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10735 
10736       if (isSFINAEContext())
10737         return QualType();
10738 
10739       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10740       return computeResultTy();
10741     }
10742 
10743     // C++ [expr.eq]p2:
10744     //   If at least one operand is a pointer [...] bring them to their
10745     //   composite pointer type.
10746     // C++ [expr.spaceship]p6
10747     //  If at least one of the operands is of pointer type, [...] bring them
10748     //  to their composite pointer type.
10749     // C++ [expr.rel]p2:
10750     //   If both operands are pointers, [...] bring them to their composite
10751     //   pointer type.
10752     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10753             (IsRelational ? 2 : 1) &&
10754         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10755                                          RHSType->isObjCObjectPointerType()))) {
10756       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10757         return QualType();
10758       return computeResultTy();
10759     }
10760   } else if (LHSType->isPointerType() &&
10761              RHSType->isPointerType()) { // C99 6.5.8p2
10762     // All of the following pointer-related warnings are GCC extensions, except
10763     // when handling null pointer constants.
10764     QualType LCanPointeeTy =
10765       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10766     QualType RCanPointeeTy =
10767       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10768 
10769     // C99 6.5.9p2 and C99 6.5.8p2
10770     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10771                                    RCanPointeeTy.getUnqualifiedType())) {
10772       // Valid unless a relational comparison of function pointers
10773       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10774         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10775           << LHSType << RHSType << LHS.get()->getSourceRange()
10776           << RHS.get()->getSourceRange();
10777       }
10778     } else if (!IsRelational &&
10779                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10780       // Valid unless comparison between non-null pointer and function pointer
10781       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10782           && !LHSIsNull && !RHSIsNull)
10783         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10784                                                 /*isError*/false);
10785     } else {
10786       // Invalid
10787       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10788     }
10789     if (LCanPointeeTy != RCanPointeeTy) {
10790       // Treat NULL constant as a special case in OpenCL.
10791       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10792         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10793         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10794           Diag(Loc,
10795                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10796               << LHSType << RHSType << 0 /* comparison */
10797               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10798         }
10799       }
10800       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10801       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10802       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10803                                                : CK_BitCast;
10804       if (LHSIsNull && !RHSIsNull)
10805         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10806       else
10807         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10808     }
10809     return computeResultTy();
10810   }
10811 
10812   if (getLangOpts().CPlusPlus) {
10813     // C++ [expr.eq]p4:
10814     //   Two operands of type std::nullptr_t or one operand of type
10815     //   std::nullptr_t and the other a null pointer constant compare equal.
10816     if (!IsRelational && LHSIsNull && RHSIsNull) {
10817       if (LHSType->isNullPtrType()) {
10818         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10819         return computeResultTy();
10820       }
10821       if (RHSType->isNullPtrType()) {
10822         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10823         return computeResultTy();
10824       }
10825     }
10826 
10827     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10828     // These aren't covered by the composite pointer type rules.
10829     if (!IsRelational && RHSType->isNullPtrType() &&
10830         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10831       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10832       return computeResultTy();
10833     }
10834     if (!IsRelational && LHSType->isNullPtrType() &&
10835         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10836       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10837       return computeResultTy();
10838     }
10839 
10840     if (IsRelational &&
10841         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10842          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10843       // HACK: Relational comparison of nullptr_t against a pointer type is
10844       // invalid per DR583, but we allow it within std::less<> and friends,
10845       // since otherwise common uses of it break.
10846       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10847       // friends to have std::nullptr_t overload candidates.
10848       DeclContext *DC = CurContext;
10849       if (isa<FunctionDecl>(DC))
10850         DC = DC->getParent();
10851       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10852         if (CTSD->isInStdNamespace() &&
10853             llvm::StringSwitch<bool>(CTSD->getName())
10854                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10855                 .Default(false)) {
10856           if (RHSType->isNullPtrType())
10857             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10858           else
10859             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10860           return computeResultTy();
10861         }
10862       }
10863     }
10864 
10865     // C++ [expr.eq]p2:
10866     //   If at least one operand is a pointer to member, [...] bring them to
10867     //   their composite pointer type.
10868     if (!IsRelational &&
10869         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10870       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10871         return QualType();
10872       else
10873         return computeResultTy();
10874     }
10875   }
10876 
10877   // Handle block pointer types.
10878   if (!IsRelational && LHSType->isBlockPointerType() &&
10879       RHSType->isBlockPointerType()) {
10880     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10881     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10882 
10883     if (!LHSIsNull && !RHSIsNull &&
10884         !Context.typesAreCompatible(lpointee, rpointee)) {
10885       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10886         << LHSType << RHSType << LHS.get()->getSourceRange()
10887         << RHS.get()->getSourceRange();
10888     }
10889     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10890     return computeResultTy();
10891   }
10892 
10893   // Allow block pointers to be compared with null pointer constants.
10894   if (!IsRelational
10895       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10896           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10897     if (!LHSIsNull && !RHSIsNull) {
10898       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10899              ->getPointeeType()->isVoidType())
10900             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10901                 ->getPointeeType()->isVoidType())))
10902         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10903           << LHSType << RHSType << LHS.get()->getSourceRange()
10904           << RHS.get()->getSourceRange();
10905     }
10906     if (LHSIsNull && !RHSIsNull)
10907       LHS = ImpCastExprToType(LHS.get(), RHSType,
10908                               RHSType->isPointerType() ? CK_BitCast
10909                                 : CK_AnyPointerToBlockPointerCast);
10910     else
10911       RHS = ImpCastExprToType(RHS.get(), LHSType,
10912                               LHSType->isPointerType() ? CK_BitCast
10913                                 : CK_AnyPointerToBlockPointerCast);
10914     return computeResultTy();
10915   }
10916 
10917   if (LHSType->isObjCObjectPointerType() ||
10918       RHSType->isObjCObjectPointerType()) {
10919     const PointerType *LPT = LHSType->getAs<PointerType>();
10920     const PointerType *RPT = RHSType->getAs<PointerType>();
10921     if (LPT || RPT) {
10922       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10923       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10924 
10925       if (!LPtrToVoid && !RPtrToVoid &&
10926           !Context.typesAreCompatible(LHSType, RHSType)) {
10927         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10928                                           /*isError*/false);
10929       }
10930       if (LHSIsNull && !RHSIsNull) {
10931         Expr *E = LHS.get();
10932         if (getLangOpts().ObjCAutoRefCount)
10933           CheckObjCConversion(SourceRange(), RHSType, E,
10934                               CCK_ImplicitConversion);
10935         LHS = ImpCastExprToType(E, RHSType,
10936                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10937       }
10938       else {
10939         Expr *E = RHS.get();
10940         if (getLangOpts().ObjCAutoRefCount)
10941           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10942                               /*Diagnose=*/true,
10943                               /*DiagnoseCFAudited=*/false, Opc);
10944         RHS = ImpCastExprToType(E, LHSType,
10945                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10946       }
10947       return computeResultTy();
10948     }
10949     if (LHSType->isObjCObjectPointerType() &&
10950         RHSType->isObjCObjectPointerType()) {
10951       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10952         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10953                                           /*isError*/false);
10954       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10955         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10956 
10957       if (LHSIsNull && !RHSIsNull)
10958         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10959       else
10960         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10961       return computeResultTy();
10962     }
10963 
10964     if (!IsRelational && LHSType->isBlockPointerType() &&
10965         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10966       LHS = ImpCastExprToType(LHS.get(), RHSType,
10967                               CK_BlockPointerToObjCPointerCast);
10968       return computeResultTy();
10969     } else if (!IsRelational &&
10970                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10971                RHSType->isBlockPointerType()) {
10972       RHS = ImpCastExprToType(RHS.get(), LHSType,
10973                               CK_BlockPointerToObjCPointerCast);
10974       return computeResultTy();
10975     }
10976   }
10977   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10978       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10979     unsigned DiagID = 0;
10980     bool isError = false;
10981     if (LangOpts.DebuggerSupport) {
10982       // Under a debugger, allow the comparison of pointers to integers,
10983       // since users tend to want to compare addresses.
10984     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10985                (RHSIsNull && RHSType->isIntegerType())) {
10986       if (IsRelational) {
10987         isError = getLangOpts().CPlusPlus;
10988         DiagID =
10989           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10990                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10991       }
10992     } else if (getLangOpts().CPlusPlus) {
10993       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10994       isError = true;
10995     } else if (IsRelational)
10996       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10997     else
10998       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10999 
11000     if (DiagID) {
11001       Diag(Loc, DiagID)
11002         << LHSType << RHSType << LHS.get()->getSourceRange()
11003         << RHS.get()->getSourceRange();
11004       if (isError)
11005         return QualType();
11006     }
11007 
11008     if (LHSType->isIntegerType())
11009       LHS = ImpCastExprToType(LHS.get(), RHSType,
11010                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11011     else
11012       RHS = ImpCastExprToType(RHS.get(), LHSType,
11013                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11014     return computeResultTy();
11015   }
11016 
11017   // Handle block pointers.
11018   if (!IsRelational && RHSIsNull
11019       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11020     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11021     return computeResultTy();
11022   }
11023   if (!IsRelational && LHSIsNull
11024       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11025     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11026     return computeResultTy();
11027   }
11028 
11029   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11030     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11031       return computeResultTy();
11032     }
11033 
11034     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11035       return computeResultTy();
11036     }
11037 
11038     if (LHSIsNull && RHSType->isQueueT()) {
11039       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11040       return computeResultTy();
11041     }
11042 
11043     if (LHSType->isQueueT() && RHSIsNull) {
11044       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11045       return computeResultTy();
11046     }
11047   }
11048 
11049   return InvalidOperands(Loc, LHS, RHS);
11050 }
11051 
11052 // Return a signed ext_vector_type that is of identical size and number of
11053 // elements. For floating point vectors, return an integer type of identical
11054 // size and number of elements. In the non ext_vector_type case, search from
11055 // the largest type to the smallest type to avoid cases where long long == long,
11056 // where long gets picked over long long.
11057 QualType Sema::GetSignedVectorType(QualType V) {
11058   const VectorType *VTy = V->castAs<VectorType>();
11059   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11060 
11061   if (isa<ExtVectorType>(VTy)) {
11062     if (TypeSize == Context.getTypeSize(Context.CharTy))
11063       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11064     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11065       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11066     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11067       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11068     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11069       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11070     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11071            "Unhandled vector element size in vector compare");
11072     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11073   }
11074 
11075   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11076     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11077                                  VectorType::GenericVector);
11078   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11079     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11080                                  VectorType::GenericVector);
11081   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11082     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11083                                  VectorType::GenericVector);
11084   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11085     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11086                                  VectorType::GenericVector);
11087   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11088          "Unhandled vector element size in vector compare");
11089   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11090                                VectorType::GenericVector);
11091 }
11092 
11093 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11094 /// operates on extended vector types.  Instead of producing an IntTy result,
11095 /// like a scalar comparison, a vector comparison produces a vector of integer
11096 /// types.
11097 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11098                                           SourceLocation Loc,
11099                                           BinaryOperatorKind Opc) {
11100   // Check to make sure we're operating on vectors of the same type and width,
11101   // Allowing one side to be a scalar of element type.
11102   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11103                               /*AllowBothBool*/true,
11104                               /*AllowBoolConversions*/getLangOpts().ZVector);
11105   if (vType.isNull())
11106     return vType;
11107 
11108   QualType LHSType = LHS.get()->getType();
11109 
11110   // If AltiVec, the comparison results in a numeric type, i.e.
11111   // bool for C++, int for C
11112   if (getLangOpts().AltiVec &&
11113       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11114     return Context.getLogicalOperationType();
11115 
11116   // For non-floating point types, check for self-comparisons of the form
11117   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11118   // often indicate logic errors in the program.
11119   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11120 
11121   // Check for comparisons of floating point operands using != and ==.
11122   if (BinaryOperator::isEqualityOp(Opc) &&
11123       LHSType->hasFloatingRepresentation()) {
11124     assert(RHS.get()->getType()->hasFloatingRepresentation());
11125     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11126   }
11127 
11128   // Return a signed type for the vector.
11129   return GetSignedVectorType(vType);
11130 }
11131 
11132 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11133                                     const ExprResult &XorRHS,
11134                                     const SourceLocation Loc) {
11135   // Do not diagnose macros.
11136   if (Loc.isMacroID())
11137     return;
11138 
11139   bool Negative = false;
11140   bool ExplicitPlus = false;
11141   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11142   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11143 
11144   if (!LHSInt)
11145     return;
11146   if (!RHSInt) {
11147     // Check negative literals.
11148     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11149       UnaryOperatorKind Opc = UO->getOpcode();
11150       if (Opc != UO_Minus && Opc != UO_Plus)
11151         return;
11152       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11153       if (!RHSInt)
11154         return;
11155       Negative = (Opc == UO_Minus);
11156       ExplicitPlus = !Negative;
11157     } else {
11158       return;
11159     }
11160   }
11161 
11162   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11163   llvm::APInt RightSideValue = RHSInt->getValue();
11164   if (LeftSideValue != 2 && LeftSideValue != 10)
11165     return;
11166 
11167   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11168     return;
11169 
11170   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11171       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11172   llvm::StringRef ExprStr =
11173       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11174 
11175   CharSourceRange XorRange =
11176       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11177   llvm::StringRef XorStr =
11178       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11179   // Do not diagnose if xor keyword/macro is used.
11180   if (XorStr == "xor")
11181     return;
11182 
11183   std::string LHSStr = Lexer::getSourceText(
11184       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11185       S.getSourceManager(), S.getLangOpts());
11186   std::string RHSStr = Lexer::getSourceText(
11187       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11188       S.getSourceManager(), S.getLangOpts());
11189 
11190   if (Negative) {
11191     RightSideValue = -RightSideValue;
11192     RHSStr = "-" + RHSStr;
11193   } else if (ExplicitPlus) {
11194     RHSStr = "+" + RHSStr;
11195   }
11196 
11197   StringRef LHSStrRef = LHSStr;
11198   StringRef RHSStrRef = RHSStr;
11199   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11200   // literals.
11201   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11202       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11203       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11204       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11205       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11206       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11207       LHSStrRef.find('\'') != StringRef::npos ||
11208       RHSStrRef.find('\'') != StringRef::npos)
11209     return;
11210 
11211   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11212   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11213   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11214   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11215     std::string SuggestedExpr = "1 << " + RHSStr;
11216     bool Overflow = false;
11217     llvm::APInt One = (LeftSideValue - 1);
11218     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11219     if (Overflow) {
11220       if (RightSideIntValue < 64)
11221         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11222             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11223             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11224       else if (RightSideIntValue == 64)
11225         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11226       else
11227         return;
11228     } else {
11229       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11230           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11231           << PowValue.toString(10, true)
11232           << FixItHint::CreateReplacement(
11233                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11234     }
11235 
11236     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11237   } else if (LeftSideValue == 10) {
11238     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11239     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11240         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11241         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11242     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11243   }
11244 }
11245 
11246 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11247                                           SourceLocation Loc) {
11248   // Ensure that either both operands are of the same vector type, or
11249   // one operand is of a vector type and the other is of its element type.
11250   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11251                                        /*AllowBothBool*/true,
11252                                        /*AllowBoolConversions*/false);
11253   if (vType.isNull())
11254     return InvalidOperands(Loc, LHS, RHS);
11255   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11256       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11257     return InvalidOperands(Loc, LHS, RHS);
11258   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11259   //        usage of the logical operators && and || with vectors in C. This
11260   //        check could be notionally dropped.
11261   if (!getLangOpts().CPlusPlus &&
11262       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11263     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11264 
11265   return GetSignedVectorType(LHS.get()->getType());
11266 }
11267 
11268 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11269                                            SourceLocation Loc,
11270                                            BinaryOperatorKind Opc) {
11271   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11272 
11273   bool IsCompAssign =
11274       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11275 
11276   if (LHS.get()->getType()->isVectorType() ||
11277       RHS.get()->getType()->isVectorType()) {
11278     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11279         RHS.get()->getType()->hasIntegerRepresentation())
11280       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11281                         /*AllowBothBool*/true,
11282                         /*AllowBoolConversions*/getLangOpts().ZVector);
11283     return InvalidOperands(Loc, LHS, RHS);
11284   }
11285 
11286   if (Opc == BO_And)
11287     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11288 
11289   ExprResult LHSResult = LHS, RHSResult = RHS;
11290   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11291                                                  IsCompAssign);
11292   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11293     return QualType();
11294   LHS = LHSResult.get();
11295   RHS = RHSResult.get();
11296 
11297   if (Opc == BO_Xor)
11298     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11299 
11300   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11301     return compType;
11302   return InvalidOperands(Loc, LHS, RHS);
11303 }
11304 
11305 // C99 6.5.[13,14]
11306 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11307                                            SourceLocation Loc,
11308                                            BinaryOperatorKind Opc) {
11309   // Check vector operands differently.
11310   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11311     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11312 
11313   bool EnumConstantInBoolContext = false;
11314   for (const ExprResult &HS : {LHS, RHS}) {
11315     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11316       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11317       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11318         EnumConstantInBoolContext = true;
11319     }
11320   }
11321 
11322   if (EnumConstantInBoolContext)
11323     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11324 
11325   // Diagnose cases where the user write a logical and/or but probably meant a
11326   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11327   // is a constant.
11328   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11329       !LHS.get()->getType()->isBooleanType() &&
11330       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11331       // Don't warn in macros or template instantiations.
11332       !Loc.isMacroID() && !inTemplateInstantiation()) {
11333     // If the RHS can be constant folded, and if it constant folds to something
11334     // that isn't 0 or 1 (which indicate a potential logical operation that
11335     // happened to fold to true/false) then warn.
11336     // Parens on the RHS are ignored.
11337     Expr::EvalResult EVResult;
11338     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11339       llvm::APSInt Result = EVResult.Val.getInt();
11340       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11341            !RHS.get()->getExprLoc().isMacroID()) ||
11342           (Result != 0 && Result != 1)) {
11343         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11344           << RHS.get()->getSourceRange()
11345           << (Opc == BO_LAnd ? "&&" : "||");
11346         // Suggest replacing the logical operator with the bitwise version
11347         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11348             << (Opc == BO_LAnd ? "&" : "|")
11349             << FixItHint::CreateReplacement(SourceRange(
11350                                                  Loc, getLocForEndOfToken(Loc)),
11351                                             Opc == BO_LAnd ? "&" : "|");
11352         if (Opc == BO_LAnd)
11353           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11354           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11355               << FixItHint::CreateRemoval(
11356                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11357                                  RHS.get()->getEndLoc()));
11358       }
11359     }
11360   }
11361 
11362   if (!Context.getLangOpts().CPlusPlus) {
11363     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11364     // not operate on the built-in scalar and vector float types.
11365     if (Context.getLangOpts().OpenCL &&
11366         Context.getLangOpts().OpenCLVersion < 120) {
11367       if (LHS.get()->getType()->isFloatingType() ||
11368           RHS.get()->getType()->isFloatingType())
11369         return InvalidOperands(Loc, LHS, RHS);
11370     }
11371 
11372     LHS = UsualUnaryConversions(LHS.get());
11373     if (LHS.isInvalid())
11374       return QualType();
11375 
11376     RHS = UsualUnaryConversions(RHS.get());
11377     if (RHS.isInvalid())
11378       return QualType();
11379 
11380     if (!LHS.get()->getType()->isScalarType() ||
11381         !RHS.get()->getType()->isScalarType())
11382       return InvalidOperands(Loc, LHS, RHS);
11383 
11384     return Context.IntTy;
11385   }
11386 
11387   // The following is safe because we only use this method for
11388   // non-overloadable operands.
11389 
11390   // C++ [expr.log.and]p1
11391   // C++ [expr.log.or]p1
11392   // The operands are both contextually converted to type bool.
11393   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11394   if (LHSRes.isInvalid())
11395     return InvalidOperands(Loc, LHS, RHS);
11396   LHS = LHSRes;
11397 
11398   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11399   if (RHSRes.isInvalid())
11400     return InvalidOperands(Loc, LHS, RHS);
11401   RHS = RHSRes;
11402 
11403   // C++ [expr.log.and]p2
11404   // C++ [expr.log.or]p2
11405   // The result is a bool.
11406   return Context.BoolTy;
11407 }
11408 
11409 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11410   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11411   if (!ME) return false;
11412   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11413   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11414       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11415   if (!Base) return false;
11416   return Base->getMethodDecl() != nullptr;
11417 }
11418 
11419 /// Is the given expression (which must be 'const') a reference to a
11420 /// variable which was originally non-const, but which has become
11421 /// 'const' due to being captured within a block?
11422 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11423 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11424   assert(E->isLValue() && E->getType().isConstQualified());
11425   E = E->IgnoreParens();
11426 
11427   // Must be a reference to a declaration from an enclosing scope.
11428   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11429   if (!DRE) return NCCK_None;
11430   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11431 
11432   // The declaration must be a variable which is not declared 'const'.
11433   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11434   if (!var) return NCCK_None;
11435   if (var->getType().isConstQualified()) return NCCK_None;
11436   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11437 
11438   // Decide whether the first capture was for a block or a lambda.
11439   DeclContext *DC = S.CurContext, *Prev = nullptr;
11440   // Decide whether the first capture was for a block or a lambda.
11441   while (DC) {
11442     // For init-capture, it is possible that the variable belongs to the
11443     // template pattern of the current context.
11444     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11445       if (var->isInitCapture() &&
11446           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11447         break;
11448     if (DC == var->getDeclContext())
11449       break;
11450     Prev = DC;
11451     DC = DC->getParent();
11452   }
11453   // Unless we have an init-capture, we've gone one step too far.
11454   if (!var->isInitCapture())
11455     DC = Prev;
11456   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11457 }
11458 
11459 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11460   Ty = Ty.getNonReferenceType();
11461   if (IsDereference && Ty->isPointerType())
11462     Ty = Ty->getPointeeType();
11463   return !Ty.isConstQualified();
11464 }
11465 
11466 // Update err_typecheck_assign_const and note_typecheck_assign_const
11467 // when this enum is changed.
11468 enum {
11469   ConstFunction,
11470   ConstVariable,
11471   ConstMember,
11472   ConstMethod,
11473   NestedConstMember,
11474   ConstUnknown,  // Keep as last element
11475 };
11476 
11477 /// Emit the "read-only variable not assignable" error and print notes to give
11478 /// more information about why the variable is not assignable, such as pointing
11479 /// to the declaration of a const variable, showing that a method is const, or
11480 /// that the function is returning a const reference.
11481 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11482                                     SourceLocation Loc) {
11483   SourceRange ExprRange = E->getSourceRange();
11484 
11485   // Only emit one error on the first const found.  All other consts will emit
11486   // a note to the error.
11487   bool DiagnosticEmitted = false;
11488 
11489   // Track if the current expression is the result of a dereference, and if the
11490   // next checked expression is the result of a dereference.
11491   bool IsDereference = false;
11492   bool NextIsDereference = false;
11493 
11494   // Loop to process MemberExpr chains.
11495   while (true) {
11496     IsDereference = NextIsDereference;
11497 
11498     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11499     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11500       NextIsDereference = ME->isArrow();
11501       const ValueDecl *VD = ME->getMemberDecl();
11502       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11503         // Mutable fields can be modified even if the class is const.
11504         if (Field->isMutable()) {
11505           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11506           break;
11507         }
11508 
11509         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11510           if (!DiagnosticEmitted) {
11511             S.Diag(Loc, diag::err_typecheck_assign_const)
11512                 << ExprRange << ConstMember << false /*static*/ << Field
11513                 << Field->getType();
11514             DiagnosticEmitted = true;
11515           }
11516           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11517               << ConstMember << false /*static*/ << Field << Field->getType()
11518               << Field->getSourceRange();
11519         }
11520         E = ME->getBase();
11521         continue;
11522       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11523         if (VDecl->getType().isConstQualified()) {
11524           if (!DiagnosticEmitted) {
11525             S.Diag(Loc, diag::err_typecheck_assign_const)
11526                 << ExprRange << ConstMember << true /*static*/ << VDecl
11527                 << VDecl->getType();
11528             DiagnosticEmitted = true;
11529           }
11530           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11531               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11532               << VDecl->getSourceRange();
11533         }
11534         // Static fields do not inherit constness from parents.
11535         break;
11536       }
11537       break; // End MemberExpr
11538     } else if (const ArraySubscriptExpr *ASE =
11539                    dyn_cast<ArraySubscriptExpr>(E)) {
11540       E = ASE->getBase()->IgnoreParenImpCasts();
11541       continue;
11542     } else if (const ExtVectorElementExpr *EVE =
11543                    dyn_cast<ExtVectorElementExpr>(E)) {
11544       E = EVE->getBase()->IgnoreParenImpCasts();
11545       continue;
11546     }
11547     break;
11548   }
11549 
11550   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11551     // Function calls
11552     const FunctionDecl *FD = CE->getDirectCallee();
11553     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11554       if (!DiagnosticEmitted) {
11555         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11556                                                       << ConstFunction << FD;
11557         DiagnosticEmitted = true;
11558       }
11559       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11560              diag::note_typecheck_assign_const)
11561           << ConstFunction << FD << FD->getReturnType()
11562           << FD->getReturnTypeSourceRange();
11563     }
11564   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11565     // Point to variable declaration.
11566     if (const ValueDecl *VD = DRE->getDecl()) {
11567       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11568         if (!DiagnosticEmitted) {
11569           S.Diag(Loc, diag::err_typecheck_assign_const)
11570               << ExprRange << ConstVariable << VD << VD->getType();
11571           DiagnosticEmitted = true;
11572         }
11573         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11574             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11575       }
11576     }
11577   } else if (isa<CXXThisExpr>(E)) {
11578     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11579       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11580         if (MD->isConst()) {
11581           if (!DiagnosticEmitted) {
11582             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11583                                                           << ConstMethod << MD;
11584             DiagnosticEmitted = true;
11585           }
11586           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11587               << ConstMethod << MD << MD->getSourceRange();
11588         }
11589       }
11590     }
11591   }
11592 
11593   if (DiagnosticEmitted)
11594     return;
11595 
11596   // Can't determine a more specific message, so display the generic error.
11597   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11598 }
11599 
11600 enum OriginalExprKind {
11601   OEK_Variable,
11602   OEK_Member,
11603   OEK_LValue
11604 };
11605 
11606 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11607                                          const RecordType *Ty,
11608                                          SourceLocation Loc, SourceRange Range,
11609                                          OriginalExprKind OEK,
11610                                          bool &DiagnosticEmitted) {
11611   std::vector<const RecordType *> RecordTypeList;
11612   RecordTypeList.push_back(Ty);
11613   unsigned NextToCheckIndex = 0;
11614   // We walk the record hierarchy breadth-first to ensure that we print
11615   // diagnostics in field nesting order.
11616   while (RecordTypeList.size() > NextToCheckIndex) {
11617     bool IsNested = NextToCheckIndex > 0;
11618     for (const FieldDecl *Field :
11619          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11620       // First, check every field for constness.
11621       QualType FieldTy = Field->getType();
11622       if (FieldTy.isConstQualified()) {
11623         if (!DiagnosticEmitted) {
11624           S.Diag(Loc, diag::err_typecheck_assign_const)
11625               << Range << NestedConstMember << OEK << VD
11626               << IsNested << Field;
11627           DiagnosticEmitted = true;
11628         }
11629         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11630             << NestedConstMember << IsNested << Field
11631             << FieldTy << Field->getSourceRange();
11632       }
11633 
11634       // Then we append it to the list to check next in order.
11635       FieldTy = FieldTy.getCanonicalType();
11636       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11637         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11638           RecordTypeList.push_back(FieldRecTy);
11639       }
11640     }
11641     ++NextToCheckIndex;
11642   }
11643 }
11644 
11645 /// Emit an error for the case where a record we are trying to assign to has a
11646 /// const-qualified field somewhere in its hierarchy.
11647 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11648                                          SourceLocation Loc) {
11649   QualType Ty = E->getType();
11650   assert(Ty->isRecordType() && "lvalue was not record?");
11651   SourceRange Range = E->getSourceRange();
11652   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11653   bool DiagEmitted = false;
11654 
11655   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11656     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11657             Range, OEK_Member, DiagEmitted);
11658   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11659     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11660             Range, OEK_Variable, DiagEmitted);
11661   else
11662     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11663             Range, OEK_LValue, DiagEmitted);
11664   if (!DiagEmitted)
11665     DiagnoseConstAssignment(S, E, Loc);
11666 }
11667 
11668 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11669 /// emit an error and return true.  If so, return false.
11670 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11671   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11672 
11673   S.CheckShadowingDeclModification(E, Loc);
11674 
11675   SourceLocation OrigLoc = Loc;
11676   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11677                                                               &Loc);
11678   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11679     IsLV = Expr::MLV_InvalidMessageExpression;
11680   if (IsLV == Expr::MLV_Valid)
11681     return false;
11682 
11683   unsigned DiagID = 0;
11684   bool NeedType = false;
11685   switch (IsLV) { // C99 6.5.16p2
11686   case Expr::MLV_ConstQualified:
11687     // Use a specialized diagnostic when we're assigning to an object
11688     // from an enclosing function or block.
11689     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11690       if (NCCK == NCCK_Block)
11691         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11692       else
11693         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11694       break;
11695     }
11696 
11697     // In ARC, use some specialized diagnostics for occasions where we
11698     // infer 'const'.  These are always pseudo-strong variables.
11699     if (S.getLangOpts().ObjCAutoRefCount) {
11700       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11701       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11702         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11703 
11704         // Use the normal diagnostic if it's pseudo-__strong but the
11705         // user actually wrote 'const'.
11706         if (var->isARCPseudoStrong() &&
11707             (!var->getTypeSourceInfo() ||
11708              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11709           // There are three pseudo-strong cases:
11710           //  - self
11711           ObjCMethodDecl *method = S.getCurMethodDecl();
11712           if (method && var == method->getSelfDecl()) {
11713             DiagID = method->isClassMethod()
11714               ? diag::err_typecheck_arc_assign_self_class_method
11715               : diag::err_typecheck_arc_assign_self;
11716 
11717           //  - Objective-C externally_retained attribute.
11718           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11719                      isa<ParmVarDecl>(var)) {
11720             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11721 
11722           //  - fast enumeration variables
11723           } else {
11724             DiagID = diag::err_typecheck_arr_assign_enumeration;
11725           }
11726 
11727           SourceRange Assign;
11728           if (Loc != OrigLoc)
11729             Assign = SourceRange(OrigLoc, OrigLoc);
11730           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11731           // We need to preserve the AST regardless, so migration tool
11732           // can do its job.
11733           return false;
11734         }
11735       }
11736     }
11737 
11738     // If none of the special cases above are triggered, then this is a
11739     // simple const assignment.
11740     if (DiagID == 0) {
11741       DiagnoseConstAssignment(S, E, Loc);
11742       return true;
11743     }
11744 
11745     break;
11746   case Expr::MLV_ConstAddrSpace:
11747     DiagnoseConstAssignment(S, E, Loc);
11748     return true;
11749   case Expr::MLV_ConstQualifiedField:
11750     DiagnoseRecursiveConstFields(S, E, Loc);
11751     return true;
11752   case Expr::MLV_ArrayType:
11753   case Expr::MLV_ArrayTemporary:
11754     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11755     NeedType = true;
11756     break;
11757   case Expr::MLV_NotObjectType:
11758     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11759     NeedType = true;
11760     break;
11761   case Expr::MLV_LValueCast:
11762     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11763     break;
11764   case Expr::MLV_Valid:
11765     llvm_unreachable("did not take early return for MLV_Valid");
11766   case Expr::MLV_InvalidExpression:
11767   case Expr::MLV_MemberFunction:
11768   case Expr::MLV_ClassTemporary:
11769     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11770     break;
11771   case Expr::MLV_IncompleteType:
11772   case Expr::MLV_IncompleteVoidType:
11773     return S.RequireCompleteType(Loc, E->getType(),
11774              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11775   case Expr::MLV_DuplicateVectorComponents:
11776     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11777     break;
11778   case Expr::MLV_NoSetterProperty:
11779     llvm_unreachable("readonly properties should be processed differently");
11780   case Expr::MLV_InvalidMessageExpression:
11781     DiagID = diag::err_readonly_message_assignment;
11782     break;
11783   case Expr::MLV_SubObjCPropertySetting:
11784     DiagID = diag::err_no_subobject_property_setting;
11785     break;
11786   }
11787 
11788   SourceRange Assign;
11789   if (Loc != OrigLoc)
11790     Assign = SourceRange(OrigLoc, OrigLoc);
11791   if (NeedType)
11792     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11793   else
11794     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11795   return true;
11796 }
11797 
11798 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11799                                          SourceLocation Loc,
11800                                          Sema &Sema) {
11801   if (Sema.inTemplateInstantiation())
11802     return;
11803   if (Sema.isUnevaluatedContext())
11804     return;
11805   if (Loc.isInvalid() || Loc.isMacroID())
11806     return;
11807   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11808     return;
11809 
11810   // C / C++ fields
11811   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11812   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11813   if (ML && MR) {
11814     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11815       return;
11816     const ValueDecl *LHSDecl =
11817         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11818     const ValueDecl *RHSDecl =
11819         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11820     if (LHSDecl != RHSDecl)
11821       return;
11822     if (LHSDecl->getType().isVolatileQualified())
11823       return;
11824     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11825       if (RefTy->getPointeeType().isVolatileQualified())
11826         return;
11827 
11828     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11829   }
11830 
11831   // Objective-C instance variables
11832   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11833   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11834   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11835     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11836     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11837     if (RL && RR && RL->getDecl() == RR->getDecl())
11838       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11839   }
11840 }
11841 
11842 // C99 6.5.16.1
11843 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11844                                        SourceLocation Loc,
11845                                        QualType CompoundType) {
11846   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11847 
11848   // Verify that LHS is a modifiable lvalue, and emit error if not.
11849   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11850     return QualType();
11851 
11852   QualType LHSType = LHSExpr->getType();
11853   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11854                                              CompoundType;
11855   // OpenCL v1.2 s6.1.1.1 p2:
11856   // The half data type can only be used to declare a pointer to a buffer that
11857   // contains half values
11858   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11859     LHSType->isHalfType()) {
11860     Diag(Loc, diag::err_opencl_half_load_store) << 1
11861         << LHSType.getUnqualifiedType();
11862     return QualType();
11863   }
11864 
11865   AssignConvertType ConvTy;
11866   if (CompoundType.isNull()) {
11867     Expr *RHSCheck = RHS.get();
11868 
11869     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11870 
11871     QualType LHSTy(LHSType);
11872     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11873     if (RHS.isInvalid())
11874       return QualType();
11875     // Special case of NSObject attributes on c-style pointer types.
11876     if (ConvTy == IncompatiblePointer &&
11877         ((Context.isObjCNSObjectType(LHSType) &&
11878           RHSType->isObjCObjectPointerType()) ||
11879          (Context.isObjCNSObjectType(RHSType) &&
11880           LHSType->isObjCObjectPointerType())))
11881       ConvTy = Compatible;
11882 
11883     if (ConvTy == Compatible &&
11884         LHSType->isObjCObjectType())
11885         Diag(Loc, diag::err_objc_object_assignment)
11886           << LHSType;
11887 
11888     // If the RHS is a unary plus or minus, check to see if they = and + are
11889     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11890     // instead of "x += 4".
11891     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11892       RHSCheck = ICE->getSubExpr();
11893     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11894       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11895           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11896           // Only if the two operators are exactly adjacent.
11897           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11898           // And there is a space or other character before the subexpr of the
11899           // unary +/-.  We don't want to warn on "x=-1".
11900           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11901           UO->getSubExpr()->getBeginLoc().isFileID()) {
11902         Diag(Loc, diag::warn_not_compound_assign)
11903           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11904           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11905       }
11906     }
11907 
11908     if (ConvTy == Compatible) {
11909       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11910         // Warn about retain cycles where a block captures the LHS, but
11911         // not if the LHS is a simple variable into which the block is
11912         // being stored...unless that variable can be captured by reference!
11913         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11914         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11915         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11916           checkRetainCycles(LHSExpr, RHS.get());
11917       }
11918 
11919       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11920           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11921         // It is safe to assign a weak reference into a strong variable.
11922         // Although this code can still have problems:
11923         //   id x = self.weakProp;
11924         //   id y = self.weakProp;
11925         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11926         // paths through the function. This should be revisited if
11927         // -Wrepeated-use-of-weak is made flow-sensitive.
11928         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11929         // variable, which will be valid for the current autorelease scope.
11930         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11931                              RHS.get()->getBeginLoc()))
11932           getCurFunction()->markSafeWeakUse(RHS.get());
11933 
11934       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11935         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11936       }
11937     }
11938   } else {
11939     // Compound assignment "x += y"
11940     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11941   }
11942 
11943   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11944                                RHS.get(), AA_Assigning))
11945     return QualType();
11946 
11947   CheckForNullPointerDereference(*this, LHSExpr);
11948 
11949   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
11950     if (CompoundType.isNull()) {
11951       // C++2a [expr.ass]p5:
11952       //   A simple-assignment whose left operand is of a volatile-qualified
11953       //   type is deprecated unless the assignment is either a discarded-value
11954       //   expression or an unevaluated operand
11955       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
11956     } else {
11957       // C++2a [expr.ass]p6:
11958       //   [Compound-assignment] expressions are deprecated if E1 has
11959       //   volatile-qualified type
11960       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
11961     }
11962   }
11963 
11964   // C99 6.5.16p3: The type of an assignment expression is the type of the
11965   // left operand unless the left operand has qualified type, in which case
11966   // it is the unqualified version of the type of the left operand.
11967   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11968   // is converted to the type of the assignment expression (above).
11969   // C++ 5.17p1: the type of the assignment expression is that of its left
11970   // operand.
11971   return (getLangOpts().CPlusPlus
11972           ? LHSType : LHSType.getUnqualifiedType());
11973 }
11974 
11975 // Only ignore explicit casts to void.
11976 static bool IgnoreCommaOperand(const Expr *E) {
11977   E = E->IgnoreParens();
11978 
11979   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11980     if (CE->getCastKind() == CK_ToVoid) {
11981       return true;
11982     }
11983 
11984     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11985     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11986         CE->getSubExpr()->getType()->isDependentType()) {
11987       return true;
11988     }
11989   }
11990 
11991   return false;
11992 }
11993 
11994 // Look for instances where it is likely the comma operator is confused with
11995 // another operator.  There is a whitelist of acceptable expressions for the
11996 // left hand side of the comma operator, otherwise emit a warning.
11997 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11998   // No warnings in macros
11999   if (Loc.isMacroID())
12000     return;
12001 
12002   // Don't warn in template instantiations.
12003   if (inTemplateInstantiation())
12004     return;
12005 
12006   // Scope isn't fine-grained enough to whitelist the specific cases, so
12007   // instead, skip more than needed, then call back into here with the
12008   // CommaVisitor in SemaStmt.cpp.
12009   // The whitelisted locations are the initialization and increment portions
12010   // of a for loop.  The additional checks are on the condition of
12011   // if statements, do/while loops, and for loops.
12012   // Differences in scope flags for C89 mode requires the extra logic.
12013   const unsigned ForIncrementFlags =
12014       getLangOpts().C99 || getLangOpts().CPlusPlus
12015           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12016           : Scope::ContinueScope | Scope::BreakScope;
12017   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12018   const unsigned ScopeFlags = getCurScope()->getFlags();
12019   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12020       (ScopeFlags & ForInitFlags) == ForInitFlags)
12021     return;
12022 
12023   // If there are multiple comma operators used together, get the RHS of the
12024   // of the comma operator as the LHS.
12025   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12026     if (BO->getOpcode() != BO_Comma)
12027       break;
12028     LHS = BO->getRHS();
12029   }
12030 
12031   // Only allow some expressions on LHS to not warn.
12032   if (IgnoreCommaOperand(LHS))
12033     return;
12034 
12035   Diag(Loc, diag::warn_comma_operator);
12036   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12037       << LHS->getSourceRange()
12038       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12039                                     LangOpts.CPlusPlus ? "static_cast<void>("
12040                                                        : "(void)(")
12041       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12042                                     ")");
12043 }
12044 
12045 // C99 6.5.17
12046 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12047                                    SourceLocation Loc) {
12048   LHS = S.CheckPlaceholderExpr(LHS.get());
12049   RHS = S.CheckPlaceholderExpr(RHS.get());
12050   if (LHS.isInvalid() || RHS.isInvalid())
12051     return QualType();
12052 
12053   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12054   // operands, but not unary promotions.
12055   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12056 
12057   // So we treat the LHS as a ignored value, and in C++ we allow the
12058   // containing site to determine what should be done with the RHS.
12059   LHS = S.IgnoredValueConversions(LHS.get());
12060   if (LHS.isInvalid())
12061     return QualType();
12062 
12063   S.DiagnoseUnusedExprResult(LHS.get());
12064 
12065   if (!S.getLangOpts().CPlusPlus) {
12066     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12067     if (RHS.isInvalid())
12068       return QualType();
12069     if (!RHS.get()->getType()->isVoidType())
12070       S.RequireCompleteType(Loc, RHS.get()->getType(),
12071                             diag::err_incomplete_type);
12072   }
12073 
12074   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12075     S.DiagnoseCommaOperator(LHS.get(), Loc);
12076 
12077   return RHS.get()->getType();
12078 }
12079 
12080 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12081 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12082 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12083                                                ExprValueKind &VK,
12084                                                ExprObjectKind &OK,
12085                                                SourceLocation OpLoc,
12086                                                bool IsInc, bool IsPrefix) {
12087   if (Op->isTypeDependent())
12088     return S.Context.DependentTy;
12089 
12090   QualType ResType = Op->getType();
12091   // Atomic types can be used for increment / decrement where the non-atomic
12092   // versions can, so ignore the _Atomic() specifier for the purpose of
12093   // checking.
12094   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12095     ResType = ResAtomicType->getValueType();
12096 
12097   assert(!ResType.isNull() && "no type for increment/decrement expression");
12098 
12099   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12100     // Decrement of bool is not allowed.
12101     if (!IsInc) {
12102       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12103       return QualType();
12104     }
12105     // Increment of bool sets it to true, but is deprecated.
12106     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12107                                               : diag::warn_increment_bool)
12108       << Op->getSourceRange();
12109   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12110     // Error on enum increments and decrements in C++ mode
12111     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12112     return QualType();
12113   } else if (ResType->isRealType()) {
12114     // OK!
12115   } else if (ResType->isPointerType()) {
12116     // C99 6.5.2.4p2, 6.5.6p2
12117     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12118       return QualType();
12119   } else if (ResType->isObjCObjectPointerType()) {
12120     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12121     // Otherwise, we just need a complete type.
12122     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12123         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12124       return QualType();
12125   } else if (ResType->isAnyComplexType()) {
12126     // C99 does not support ++/-- on complex types, we allow as an extension.
12127     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12128       << ResType << Op->getSourceRange();
12129   } else if (ResType->isPlaceholderType()) {
12130     ExprResult PR = S.CheckPlaceholderExpr(Op);
12131     if (PR.isInvalid()) return QualType();
12132     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12133                                           IsInc, IsPrefix);
12134   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12135     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12136   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12137              (ResType->castAs<VectorType>()->getVectorKind() !=
12138               VectorType::AltiVecBool)) {
12139     // The z vector extensions allow ++ and -- for non-bool vectors.
12140   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12141             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12142     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12143   } else {
12144     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12145       << ResType << int(IsInc) << Op->getSourceRange();
12146     return QualType();
12147   }
12148   // At this point, we know we have a real, complex or pointer type.
12149   // Now make sure the operand is a modifiable lvalue.
12150   if (CheckForModifiableLvalue(Op, OpLoc, S))
12151     return QualType();
12152   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12153     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12154     //   An operand with volatile-qualified type is deprecated
12155     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12156         << IsInc << ResType;
12157   }
12158   // In C++, a prefix increment is the same type as the operand. Otherwise
12159   // (in C or with postfix), the increment is the unqualified type of the
12160   // operand.
12161   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12162     VK = VK_LValue;
12163     OK = Op->getObjectKind();
12164     return ResType;
12165   } else {
12166     VK = VK_RValue;
12167     return ResType.getUnqualifiedType();
12168   }
12169 }
12170 
12171 
12172 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12173 /// This routine allows us to typecheck complex/recursive expressions
12174 /// where the declaration is needed for type checking. We only need to
12175 /// handle cases when the expression references a function designator
12176 /// or is an lvalue. Here are some examples:
12177 ///  - &(x) => x
12178 ///  - &*****f => f for f a function designator.
12179 ///  - &s.xx => s
12180 ///  - &s.zz[1].yy -> s, if zz is an array
12181 ///  - *(x + 1) -> x, if x is an array
12182 ///  - &"123"[2] -> 0
12183 ///  - & __real__ x -> x
12184 static ValueDecl *getPrimaryDecl(Expr *E) {
12185   switch (E->getStmtClass()) {
12186   case Stmt::DeclRefExprClass:
12187     return cast<DeclRefExpr>(E)->getDecl();
12188   case Stmt::MemberExprClass:
12189     // If this is an arrow operator, the address is an offset from
12190     // the base's value, so the object the base refers to is
12191     // irrelevant.
12192     if (cast<MemberExpr>(E)->isArrow())
12193       return nullptr;
12194     // Otherwise, the expression refers to a part of the base
12195     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12196   case Stmt::ArraySubscriptExprClass: {
12197     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12198     // promotion of register arrays earlier.
12199     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12200     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12201       if (ICE->getSubExpr()->getType()->isArrayType())
12202         return getPrimaryDecl(ICE->getSubExpr());
12203     }
12204     return nullptr;
12205   }
12206   case Stmt::UnaryOperatorClass: {
12207     UnaryOperator *UO = cast<UnaryOperator>(E);
12208 
12209     switch(UO->getOpcode()) {
12210     case UO_Real:
12211     case UO_Imag:
12212     case UO_Extension:
12213       return getPrimaryDecl(UO->getSubExpr());
12214     default:
12215       return nullptr;
12216     }
12217   }
12218   case Stmt::ParenExprClass:
12219     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12220   case Stmt::ImplicitCastExprClass:
12221     // If the result of an implicit cast is an l-value, we care about
12222     // the sub-expression; otherwise, the result here doesn't matter.
12223     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12224   default:
12225     return nullptr;
12226   }
12227 }
12228 
12229 namespace {
12230   enum {
12231     AO_Bit_Field = 0,
12232     AO_Vector_Element = 1,
12233     AO_Property_Expansion = 2,
12234     AO_Register_Variable = 3,
12235     AO_No_Error = 4
12236   };
12237 }
12238 /// Diagnose invalid operand for address of operations.
12239 ///
12240 /// \param Type The type of operand which cannot have its address taken.
12241 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12242                                          Expr *E, unsigned Type) {
12243   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12244 }
12245 
12246 /// CheckAddressOfOperand - The operand of & must be either a function
12247 /// designator or an lvalue designating an object. If it is an lvalue, the
12248 /// object cannot be declared with storage class register or be a bit field.
12249 /// Note: The usual conversions are *not* applied to the operand of the &
12250 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12251 /// In C++, the operand might be an overloaded function name, in which case
12252 /// we allow the '&' but retain the overloaded-function type.
12253 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12254   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12255     if (PTy->getKind() == BuiltinType::Overload) {
12256       Expr *E = OrigOp.get()->IgnoreParens();
12257       if (!isa<OverloadExpr>(E)) {
12258         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12259         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12260           << OrigOp.get()->getSourceRange();
12261         return QualType();
12262       }
12263 
12264       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12265       if (isa<UnresolvedMemberExpr>(Ovl))
12266         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12267           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12268             << OrigOp.get()->getSourceRange();
12269           return QualType();
12270         }
12271 
12272       return Context.OverloadTy;
12273     }
12274 
12275     if (PTy->getKind() == BuiltinType::UnknownAny)
12276       return Context.UnknownAnyTy;
12277 
12278     if (PTy->getKind() == BuiltinType::BoundMember) {
12279       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12280         << OrigOp.get()->getSourceRange();
12281       return QualType();
12282     }
12283 
12284     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12285     if (OrigOp.isInvalid()) return QualType();
12286   }
12287 
12288   if (OrigOp.get()->isTypeDependent())
12289     return Context.DependentTy;
12290 
12291   assert(!OrigOp.get()->getType()->isPlaceholderType());
12292 
12293   // Make sure to ignore parentheses in subsequent checks
12294   Expr *op = OrigOp.get()->IgnoreParens();
12295 
12296   // In OpenCL captures for blocks called as lambda functions
12297   // are located in the private address space. Blocks used in
12298   // enqueue_kernel can be located in a different address space
12299   // depending on a vendor implementation. Thus preventing
12300   // taking an address of the capture to avoid invalid AS casts.
12301   if (LangOpts.OpenCL) {
12302     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12303     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12304       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12305       return QualType();
12306     }
12307   }
12308 
12309   if (getLangOpts().C99) {
12310     // Implement C99-only parts of addressof rules.
12311     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12312       if (uOp->getOpcode() == UO_Deref)
12313         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12314         // (assuming the deref expression is valid).
12315         return uOp->getSubExpr()->getType();
12316     }
12317     // Technically, there should be a check for array subscript
12318     // expressions here, but the result of one is always an lvalue anyway.
12319   }
12320   ValueDecl *dcl = getPrimaryDecl(op);
12321 
12322   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12323     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12324                                            op->getBeginLoc()))
12325       return QualType();
12326 
12327   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12328   unsigned AddressOfError = AO_No_Error;
12329 
12330   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12331     bool sfinae = (bool)isSFINAEContext();
12332     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12333                                   : diag::ext_typecheck_addrof_temporary)
12334       << op->getType() << op->getSourceRange();
12335     if (sfinae)
12336       return QualType();
12337     // Materialize the temporary as an lvalue so that we can take its address.
12338     OrigOp = op =
12339         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12340   } else if (isa<ObjCSelectorExpr>(op)) {
12341     return Context.getPointerType(op->getType());
12342   } else if (lval == Expr::LV_MemberFunction) {
12343     // If it's an instance method, make a member pointer.
12344     // The expression must have exactly the form &A::foo.
12345 
12346     // If the underlying expression isn't a decl ref, give up.
12347     if (!isa<DeclRefExpr>(op)) {
12348       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12349         << OrigOp.get()->getSourceRange();
12350       return QualType();
12351     }
12352     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12353     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12354 
12355     // The id-expression was parenthesized.
12356     if (OrigOp.get() != DRE) {
12357       Diag(OpLoc, diag::err_parens_pointer_member_function)
12358         << OrigOp.get()->getSourceRange();
12359 
12360     // The method was named without a qualifier.
12361     } else if (!DRE->getQualifier()) {
12362       if (MD->getParent()->getName().empty())
12363         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12364           << op->getSourceRange();
12365       else {
12366         SmallString<32> Str;
12367         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12368         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12369           << op->getSourceRange()
12370           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12371       }
12372     }
12373 
12374     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12375     if (isa<CXXDestructorDecl>(MD))
12376       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12377 
12378     QualType MPTy = Context.getMemberPointerType(
12379         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12380     // Under the MS ABI, lock down the inheritance model now.
12381     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12382       (void)isCompleteType(OpLoc, MPTy);
12383     return MPTy;
12384   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12385     // C99 6.5.3.2p1
12386     // The operand must be either an l-value or a function designator
12387     if (!op->getType()->isFunctionType()) {
12388       // Use a special diagnostic for loads from property references.
12389       if (isa<PseudoObjectExpr>(op)) {
12390         AddressOfError = AO_Property_Expansion;
12391       } else {
12392         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12393           << op->getType() << op->getSourceRange();
12394         return QualType();
12395       }
12396     }
12397   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12398     // The operand cannot be a bit-field
12399     AddressOfError = AO_Bit_Field;
12400   } else if (op->getObjectKind() == OK_VectorComponent) {
12401     // The operand cannot be an element of a vector
12402     AddressOfError = AO_Vector_Element;
12403   } else if (dcl) { // C99 6.5.3.2p1
12404     // We have an lvalue with a decl. Make sure the decl is not declared
12405     // with the register storage-class specifier.
12406     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12407       // in C++ it is not error to take address of a register
12408       // variable (c++03 7.1.1P3)
12409       if (vd->getStorageClass() == SC_Register &&
12410           !getLangOpts().CPlusPlus) {
12411         AddressOfError = AO_Register_Variable;
12412       }
12413     } else if (isa<MSPropertyDecl>(dcl)) {
12414       AddressOfError = AO_Property_Expansion;
12415     } else if (isa<FunctionTemplateDecl>(dcl)) {
12416       return Context.OverloadTy;
12417     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12418       // Okay: we can take the address of a field.
12419       // Could be a pointer to member, though, if there is an explicit
12420       // scope qualifier for the class.
12421       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12422         DeclContext *Ctx = dcl->getDeclContext();
12423         if (Ctx && Ctx->isRecord()) {
12424           if (dcl->getType()->isReferenceType()) {
12425             Diag(OpLoc,
12426                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12427               << dcl->getDeclName() << dcl->getType();
12428             return QualType();
12429           }
12430 
12431           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12432             Ctx = Ctx->getParent();
12433 
12434           QualType MPTy = Context.getMemberPointerType(
12435               op->getType(),
12436               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12437           // Under the MS ABI, lock down the inheritance model now.
12438           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12439             (void)isCompleteType(OpLoc, MPTy);
12440           return MPTy;
12441         }
12442       }
12443     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12444                !isa<BindingDecl>(dcl))
12445       llvm_unreachable("Unknown/unexpected decl type");
12446   }
12447 
12448   if (AddressOfError != AO_No_Error) {
12449     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12450     return QualType();
12451   }
12452 
12453   if (lval == Expr::LV_IncompleteVoidType) {
12454     // Taking the address of a void variable is technically illegal, but we
12455     // allow it in cases which are otherwise valid.
12456     // Example: "extern void x; void* y = &x;".
12457     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12458   }
12459 
12460   // If the operand has type "type", the result has type "pointer to type".
12461   if (op->getType()->isObjCObjectType())
12462     return Context.getObjCObjectPointerType(op->getType());
12463 
12464   CheckAddressOfPackedMember(op);
12465 
12466   return Context.getPointerType(op->getType());
12467 }
12468 
12469 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12470   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12471   if (!DRE)
12472     return;
12473   const Decl *D = DRE->getDecl();
12474   if (!D)
12475     return;
12476   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12477   if (!Param)
12478     return;
12479   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12480     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12481       return;
12482   if (FunctionScopeInfo *FD = S.getCurFunction())
12483     if (!FD->ModifiedNonNullParams.count(Param))
12484       FD->ModifiedNonNullParams.insert(Param);
12485 }
12486 
12487 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12488 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12489                                         SourceLocation OpLoc) {
12490   if (Op->isTypeDependent())
12491     return S.Context.DependentTy;
12492 
12493   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12494   if (ConvResult.isInvalid())
12495     return QualType();
12496   Op = ConvResult.get();
12497   QualType OpTy = Op->getType();
12498   QualType Result;
12499 
12500   if (isa<CXXReinterpretCastExpr>(Op)) {
12501     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12502     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12503                                      Op->getSourceRange());
12504   }
12505 
12506   if (const PointerType *PT = OpTy->getAs<PointerType>())
12507   {
12508     Result = PT->getPointeeType();
12509   }
12510   else if (const ObjCObjectPointerType *OPT =
12511              OpTy->getAs<ObjCObjectPointerType>())
12512     Result = OPT->getPointeeType();
12513   else {
12514     ExprResult PR = S.CheckPlaceholderExpr(Op);
12515     if (PR.isInvalid()) return QualType();
12516     if (PR.get() != Op)
12517       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12518   }
12519 
12520   if (Result.isNull()) {
12521     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12522       << OpTy << Op->getSourceRange();
12523     return QualType();
12524   }
12525 
12526   // Note that per both C89 and C99, indirection is always legal, even if Result
12527   // is an incomplete type or void.  It would be possible to warn about
12528   // dereferencing a void pointer, but it's completely well-defined, and such a
12529   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12530   // for pointers to 'void' but is fine for any other pointer type:
12531   //
12532   // C++ [expr.unary.op]p1:
12533   //   [...] the expression to which [the unary * operator] is applied shall
12534   //   be a pointer to an object type, or a pointer to a function type
12535   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12536     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12537       << OpTy << Op->getSourceRange();
12538 
12539   // Dereferences are usually l-values...
12540   VK = VK_LValue;
12541 
12542   // ...except that certain expressions are never l-values in C.
12543   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12544     VK = VK_RValue;
12545 
12546   return Result;
12547 }
12548 
12549 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12550   BinaryOperatorKind Opc;
12551   switch (Kind) {
12552   default: llvm_unreachable("Unknown binop!");
12553   case tok::periodstar:           Opc = BO_PtrMemD; break;
12554   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12555   case tok::star:                 Opc = BO_Mul; break;
12556   case tok::slash:                Opc = BO_Div; break;
12557   case tok::percent:              Opc = BO_Rem; break;
12558   case tok::plus:                 Opc = BO_Add; break;
12559   case tok::minus:                Opc = BO_Sub; break;
12560   case tok::lessless:             Opc = BO_Shl; break;
12561   case tok::greatergreater:       Opc = BO_Shr; break;
12562   case tok::lessequal:            Opc = BO_LE; break;
12563   case tok::less:                 Opc = BO_LT; break;
12564   case tok::greaterequal:         Opc = BO_GE; break;
12565   case tok::greater:              Opc = BO_GT; break;
12566   case tok::exclaimequal:         Opc = BO_NE; break;
12567   case tok::equalequal:           Opc = BO_EQ; break;
12568   case tok::spaceship:            Opc = BO_Cmp; break;
12569   case tok::amp:                  Opc = BO_And; break;
12570   case tok::caret:                Opc = BO_Xor; break;
12571   case tok::pipe:                 Opc = BO_Or; break;
12572   case tok::ampamp:               Opc = BO_LAnd; break;
12573   case tok::pipepipe:             Opc = BO_LOr; break;
12574   case tok::equal:                Opc = BO_Assign; break;
12575   case tok::starequal:            Opc = BO_MulAssign; break;
12576   case tok::slashequal:           Opc = BO_DivAssign; break;
12577   case tok::percentequal:         Opc = BO_RemAssign; break;
12578   case tok::plusequal:            Opc = BO_AddAssign; break;
12579   case tok::minusequal:           Opc = BO_SubAssign; break;
12580   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12581   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12582   case tok::ampequal:             Opc = BO_AndAssign; break;
12583   case tok::caretequal:           Opc = BO_XorAssign; break;
12584   case tok::pipeequal:            Opc = BO_OrAssign; break;
12585   case tok::comma:                Opc = BO_Comma; break;
12586   }
12587   return Opc;
12588 }
12589 
12590 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12591   tok::TokenKind Kind) {
12592   UnaryOperatorKind Opc;
12593   switch (Kind) {
12594   default: llvm_unreachable("Unknown unary op!");
12595   case tok::plusplus:     Opc = UO_PreInc; break;
12596   case tok::minusminus:   Opc = UO_PreDec; break;
12597   case tok::amp:          Opc = UO_AddrOf; break;
12598   case tok::star:         Opc = UO_Deref; break;
12599   case tok::plus:         Opc = UO_Plus; break;
12600   case tok::minus:        Opc = UO_Minus; break;
12601   case tok::tilde:        Opc = UO_Not; break;
12602   case tok::exclaim:      Opc = UO_LNot; break;
12603   case tok::kw___real:    Opc = UO_Real; break;
12604   case tok::kw___imag:    Opc = UO_Imag; break;
12605   case tok::kw___extension__: Opc = UO_Extension; break;
12606   }
12607   return Opc;
12608 }
12609 
12610 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12611 /// This warning suppressed in the event of macro expansions.
12612 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12613                                    SourceLocation OpLoc, bool IsBuiltin) {
12614   if (S.inTemplateInstantiation())
12615     return;
12616   if (S.isUnevaluatedContext())
12617     return;
12618   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12619     return;
12620   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12621   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12622   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12623   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12624   if (!LHSDeclRef || !RHSDeclRef ||
12625       LHSDeclRef->getLocation().isMacroID() ||
12626       RHSDeclRef->getLocation().isMacroID())
12627     return;
12628   const ValueDecl *LHSDecl =
12629     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12630   const ValueDecl *RHSDecl =
12631     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12632   if (LHSDecl != RHSDecl)
12633     return;
12634   if (LHSDecl->getType().isVolatileQualified())
12635     return;
12636   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12637     if (RefTy->getPointeeType().isVolatileQualified())
12638       return;
12639 
12640   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12641                           : diag::warn_self_assignment_overloaded)
12642       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12643       << RHSExpr->getSourceRange();
12644 }
12645 
12646 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12647 /// is usually indicative of introspection within the Objective-C pointer.
12648 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12649                                           SourceLocation OpLoc) {
12650   if (!S.getLangOpts().ObjC)
12651     return;
12652 
12653   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12654   const Expr *LHS = L.get();
12655   const Expr *RHS = R.get();
12656 
12657   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12658     ObjCPointerExpr = LHS;
12659     OtherExpr = RHS;
12660   }
12661   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12662     ObjCPointerExpr = RHS;
12663     OtherExpr = LHS;
12664   }
12665 
12666   // This warning is deliberately made very specific to reduce false
12667   // positives with logic that uses '&' for hashing.  This logic mainly
12668   // looks for code trying to introspect into tagged pointers, which
12669   // code should generally never do.
12670   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12671     unsigned Diag = diag::warn_objc_pointer_masking;
12672     // Determine if we are introspecting the result of performSelectorXXX.
12673     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12674     // Special case messages to -performSelector and friends, which
12675     // can return non-pointer values boxed in a pointer value.
12676     // Some clients may wish to silence warnings in this subcase.
12677     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12678       Selector S = ME->getSelector();
12679       StringRef SelArg0 = S.getNameForSlot(0);
12680       if (SelArg0.startswith("performSelector"))
12681         Diag = diag::warn_objc_pointer_masking_performSelector;
12682     }
12683 
12684     S.Diag(OpLoc, Diag)
12685       << ObjCPointerExpr->getSourceRange();
12686   }
12687 }
12688 
12689 static NamedDecl *getDeclFromExpr(Expr *E) {
12690   if (!E)
12691     return nullptr;
12692   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12693     return DRE->getDecl();
12694   if (auto *ME = dyn_cast<MemberExpr>(E))
12695     return ME->getMemberDecl();
12696   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12697     return IRE->getDecl();
12698   return nullptr;
12699 }
12700 
12701 // This helper function promotes a binary operator's operands (which are of a
12702 // half vector type) to a vector of floats and then truncates the result to
12703 // a vector of either half or short.
12704 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12705                                       BinaryOperatorKind Opc, QualType ResultTy,
12706                                       ExprValueKind VK, ExprObjectKind OK,
12707                                       bool IsCompAssign, SourceLocation OpLoc,
12708                                       FPOptions FPFeatures) {
12709   auto &Context = S.getASTContext();
12710   assert((isVector(ResultTy, Context.HalfTy) ||
12711           isVector(ResultTy, Context.ShortTy)) &&
12712          "Result must be a vector of half or short");
12713   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12714          isVector(RHS.get()->getType(), Context.HalfTy) &&
12715          "both operands expected to be a half vector");
12716 
12717   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12718   QualType BinOpResTy = RHS.get()->getType();
12719 
12720   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12721   // change BinOpResTy to a vector of ints.
12722   if (isVector(ResultTy, Context.ShortTy))
12723     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12724 
12725   if (IsCompAssign)
12726     return new (Context) CompoundAssignOperator(
12727         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12728         OpLoc, FPFeatures);
12729 
12730   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12731   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12732                                           VK, OK, OpLoc, FPFeatures);
12733   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12734 }
12735 
12736 static std::pair<ExprResult, ExprResult>
12737 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12738                            Expr *RHSExpr) {
12739   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12740   if (!S.getLangOpts().CPlusPlus) {
12741     // C cannot handle TypoExpr nodes on either side of a binop because it
12742     // doesn't handle dependent types properly, so make sure any TypoExprs have
12743     // been dealt with before checking the operands.
12744     LHS = S.CorrectDelayedTyposInExpr(LHS);
12745     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12746       if (Opc != BO_Assign)
12747         return ExprResult(E);
12748       // Avoid correcting the RHS to the same Expr as the LHS.
12749       Decl *D = getDeclFromExpr(E);
12750       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12751     });
12752   }
12753   return std::make_pair(LHS, RHS);
12754 }
12755 
12756 /// Returns true if conversion between vectors of halfs and vectors of floats
12757 /// is needed.
12758 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12759                                      QualType SrcType) {
12760   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12761          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12762          isVector(SrcType, Ctx.HalfTy);
12763 }
12764 
12765 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12766 /// operator @p Opc at location @c TokLoc. This routine only supports
12767 /// built-in operations; ActOnBinOp handles overloaded operators.
12768 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12769                                     BinaryOperatorKind Opc,
12770                                     Expr *LHSExpr, Expr *RHSExpr) {
12771   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12772     // The syntax only allows initializer lists on the RHS of assignment,
12773     // so we don't need to worry about accepting invalid code for
12774     // non-assignment operators.
12775     // C++11 5.17p9:
12776     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12777     //   of x = {} is x = T().
12778     InitializationKind Kind = InitializationKind::CreateDirectList(
12779         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12780     InitializedEntity Entity =
12781         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12782     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12783     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12784     if (Init.isInvalid())
12785       return Init;
12786     RHSExpr = Init.get();
12787   }
12788 
12789   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12790   QualType ResultTy;     // Result type of the binary operator.
12791   // The following two variables are used for compound assignment operators
12792   QualType CompLHSTy;    // Type of LHS after promotions for computation
12793   QualType CompResultTy; // Type of computation result
12794   ExprValueKind VK = VK_RValue;
12795   ExprObjectKind OK = OK_Ordinary;
12796   bool ConvertHalfVec = false;
12797 
12798   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12799   if (!LHS.isUsable() || !RHS.isUsable())
12800     return ExprError();
12801 
12802   if (getLangOpts().OpenCL) {
12803     QualType LHSTy = LHSExpr->getType();
12804     QualType RHSTy = RHSExpr->getType();
12805     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12806     // the ATOMIC_VAR_INIT macro.
12807     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12808       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12809       if (BO_Assign == Opc)
12810         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12811       else
12812         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12813       return ExprError();
12814     }
12815 
12816     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12817     // only with a builtin functions and therefore should be disallowed here.
12818     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12819         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12820         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12821         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12822       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12823       return ExprError();
12824     }
12825   }
12826 
12827   // Diagnose operations on the unsupported types for OpenMP device compilation.
12828   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12829     if (Opc != BO_Assign && Opc != BO_Comma) {
12830       checkOpenMPDeviceExpr(LHSExpr);
12831       checkOpenMPDeviceExpr(RHSExpr);
12832     }
12833   }
12834 
12835   switch (Opc) {
12836   case BO_Assign:
12837     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12838     if (getLangOpts().CPlusPlus &&
12839         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12840       VK = LHS.get()->getValueKind();
12841       OK = LHS.get()->getObjectKind();
12842     }
12843     if (!ResultTy.isNull()) {
12844       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12845       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12846 
12847       // Avoid copying a block to the heap if the block is assigned to a local
12848       // auto variable that is declared in the same scope as the block. This
12849       // optimization is unsafe if the local variable is declared in an outer
12850       // scope. For example:
12851       //
12852       // BlockTy b;
12853       // {
12854       //   b = ^{...};
12855       // }
12856       // // It is unsafe to invoke the block here if it wasn't copied to the
12857       // // heap.
12858       // b();
12859 
12860       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12861         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12862           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12863             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12864               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12865 
12866       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12867         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12868                               NTCUC_Assignment, NTCUK_Copy);
12869     }
12870     RecordModifiableNonNullParam(*this, LHS.get());
12871     break;
12872   case BO_PtrMemD:
12873   case BO_PtrMemI:
12874     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12875                                             Opc == BO_PtrMemI);
12876     break;
12877   case BO_Mul:
12878   case BO_Div:
12879     ConvertHalfVec = true;
12880     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12881                                            Opc == BO_Div);
12882     break;
12883   case BO_Rem:
12884     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12885     break;
12886   case BO_Add:
12887     ConvertHalfVec = true;
12888     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12889     break;
12890   case BO_Sub:
12891     ConvertHalfVec = true;
12892     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12893     break;
12894   case BO_Shl:
12895   case BO_Shr:
12896     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12897     break;
12898   case BO_LE:
12899   case BO_LT:
12900   case BO_GE:
12901   case BO_GT:
12902     ConvertHalfVec = true;
12903     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12904     break;
12905   case BO_EQ:
12906   case BO_NE:
12907     ConvertHalfVec = true;
12908     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12909     break;
12910   case BO_Cmp:
12911     ConvertHalfVec = true;
12912     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12913     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12914     break;
12915   case BO_And:
12916     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12917     LLVM_FALLTHROUGH;
12918   case BO_Xor:
12919   case BO_Or:
12920     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12921     break;
12922   case BO_LAnd:
12923   case BO_LOr:
12924     ConvertHalfVec = true;
12925     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12926     break;
12927   case BO_MulAssign:
12928   case BO_DivAssign:
12929     ConvertHalfVec = true;
12930     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12931                                                Opc == BO_DivAssign);
12932     CompLHSTy = CompResultTy;
12933     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12934       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12935     break;
12936   case BO_RemAssign:
12937     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12938     CompLHSTy = CompResultTy;
12939     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12940       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12941     break;
12942   case BO_AddAssign:
12943     ConvertHalfVec = true;
12944     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12945     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12946       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12947     break;
12948   case BO_SubAssign:
12949     ConvertHalfVec = true;
12950     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12951     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12952       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12953     break;
12954   case BO_ShlAssign:
12955   case BO_ShrAssign:
12956     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12957     CompLHSTy = CompResultTy;
12958     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12959       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12960     break;
12961   case BO_AndAssign:
12962   case BO_OrAssign: // fallthrough
12963     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12964     LLVM_FALLTHROUGH;
12965   case BO_XorAssign:
12966     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12967     CompLHSTy = CompResultTy;
12968     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12969       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12970     break;
12971   case BO_Comma:
12972     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12973     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12974       VK = RHS.get()->getValueKind();
12975       OK = RHS.get()->getObjectKind();
12976     }
12977     break;
12978   }
12979   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12980     return ExprError();
12981 
12982   // Some of the binary operations require promoting operands of half vector to
12983   // float vectors and truncating the result back to half vector. For now, we do
12984   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12985   // arm64).
12986   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12987          isVector(LHS.get()->getType(), Context.HalfTy) &&
12988          "both sides are half vectors or neither sides are");
12989   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12990                                             LHS.get()->getType());
12991 
12992   // Check for array bounds violations for both sides of the BinaryOperator
12993   CheckArrayAccess(LHS.get());
12994   CheckArrayAccess(RHS.get());
12995 
12996   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12997     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12998                                                  &Context.Idents.get("object_setClass"),
12999                                                  SourceLocation(), LookupOrdinaryName);
13000     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13001       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13002       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13003           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13004                                         "object_setClass(")
13005           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13006                                           ",")
13007           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13008     }
13009     else
13010       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13011   }
13012   else if (const ObjCIvarRefExpr *OIRE =
13013            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13014     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13015 
13016   // Opc is not a compound assignment if CompResultTy is null.
13017   if (CompResultTy.isNull()) {
13018     if (ConvertHalfVec)
13019       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13020                                  OpLoc, FPFeatures);
13021     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13022                                         OK, OpLoc, FPFeatures);
13023   }
13024 
13025   // Handle compound assignments.
13026   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13027       OK_ObjCProperty) {
13028     VK = VK_LValue;
13029     OK = LHS.get()->getObjectKind();
13030   }
13031 
13032   if (ConvertHalfVec)
13033     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13034                                OpLoc, FPFeatures);
13035 
13036   return new (Context) CompoundAssignOperator(
13037       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13038       OpLoc, FPFeatures);
13039 }
13040 
13041 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13042 /// operators are mixed in a way that suggests that the programmer forgot that
13043 /// comparison operators have higher precedence. The most typical example of
13044 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13045 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13046                                       SourceLocation OpLoc, Expr *LHSExpr,
13047                                       Expr *RHSExpr) {
13048   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13049   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13050 
13051   // Check that one of the sides is a comparison operator and the other isn't.
13052   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13053   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13054   if (isLeftComp == isRightComp)
13055     return;
13056 
13057   // Bitwise operations are sometimes used as eager logical ops.
13058   // Don't diagnose this.
13059   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13060   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13061   if (isLeftBitwise || isRightBitwise)
13062     return;
13063 
13064   SourceRange DiagRange = isLeftComp
13065                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13066                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13067   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13068   SourceRange ParensRange =
13069       isLeftComp
13070           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13071           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13072 
13073   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13074     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13075   SuggestParentheses(Self, OpLoc,
13076     Self.PDiag(diag::note_precedence_silence) << OpStr,
13077     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13078   SuggestParentheses(Self, OpLoc,
13079     Self.PDiag(diag::note_precedence_bitwise_first)
13080       << BinaryOperator::getOpcodeStr(Opc),
13081     ParensRange);
13082 }
13083 
13084 /// It accepts a '&&' expr that is inside a '||' one.
13085 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13086 /// in parentheses.
13087 static void
13088 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13089                                        BinaryOperator *Bop) {
13090   assert(Bop->getOpcode() == BO_LAnd);
13091   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13092       << Bop->getSourceRange() << OpLoc;
13093   SuggestParentheses(Self, Bop->getOperatorLoc(),
13094     Self.PDiag(diag::note_precedence_silence)
13095       << Bop->getOpcodeStr(),
13096     Bop->getSourceRange());
13097 }
13098 
13099 /// Returns true if the given expression can be evaluated as a constant
13100 /// 'true'.
13101 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13102   bool Res;
13103   return !E->isValueDependent() &&
13104          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13105 }
13106 
13107 /// Returns true if the given expression can be evaluated as a constant
13108 /// 'false'.
13109 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13110   bool Res;
13111   return !E->isValueDependent() &&
13112          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13113 }
13114 
13115 /// Look for '&&' in the left hand of a '||' expr.
13116 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13117                                              Expr *LHSExpr, Expr *RHSExpr) {
13118   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13119     if (Bop->getOpcode() == BO_LAnd) {
13120       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13121       if (EvaluatesAsFalse(S, RHSExpr))
13122         return;
13123       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13124       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13125         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13126     } else if (Bop->getOpcode() == BO_LOr) {
13127       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13128         // If it's "a || b && 1 || c" we didn't warn earlier for
13129         // "a || b && 1", but warn now.
13130         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13131           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13132       }
13133     }
13134   }
13135 }
13136 
13137 /// Look for '&&' in the right hand of a '||' expr.
13138 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13139                                              Expr *LHSExpr, Expr *RHSExpr) {
13140   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13141     if (Bop->getOpcode() == BO_LAnd) {
13142       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13143       if (EvaluatesAsFalse(S, LHSExpr))
13144         return;
13145       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13146       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13147         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13148     }
13149   }
13150 }
13151 
13152 /// Look for bitwise op in the left or right hand of a bitwise op with
13153 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13154 /// the '&' expression in parentheses.
13155 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13156                                          SourceLocation OpLoc, Expr *SubExpr) {
13157   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13158     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13159       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13160         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13161         << Bop->getSourceRange() << OpLoc;
13162       SuggestParentheses(S, Bop->getOperatorLoc(),
13163         S.PDiag(diag::note_precedence_silence)
13164           << Bop->getOpcodeStr(),
13165         Bop->getSourceRange());
13166     }
13167   }
13168 }
13169 
13170 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13171                                     Expr *SubExpr, StringRef Shift) {
13172   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13173     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13174       StringRef Op = Bop->getOpcodeStr();
13175       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13176           << Bop->getSourceRange() << OpLoc << Shift << Op;
13177       SuggestParentheses(S, Bop->getOperatorLoc(),
13178           S.PDiag(diag::note_precedence_silence) << Op,
13179           Bop->getSourceRange());
13180     }
13181   }
13182 }
13183 
13184 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13185                                  Expr *LHSExpr, Expr *RHSExpr) {
13186   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13187   if (!OCE)
13188     return;
13189 
13190   FunctionDecl *FD = OCE->getDirectCallee();
13191   if (!FD || !FD->isOverloadedOperator())
13192     return;
13193 
13194   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13195   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13196     return;
13197 
13198   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13199       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13200       << (Kind == OO_LessLess);
13201   SuggestParentheses(S, OCE->getOperatorLoc(),
13202                      S.PDiag(diag::note_precedence_silence)
13203                          << (Kind == OO_LessLess ? "<<" : ">>"),
13204                      OCE->getSourceRange());
13205   SuggestParentheses(
13206       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13207       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13208 }
13209 
13210 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13211 /// precedence.
13212 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13213                                     SourceLocation OpLoc, Expr *LHSExpr,
13214                                     Expr *RHSExpr){
13215   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13216   if (BinaryOperator::isBitwiseOp(Opc))
13217     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13218 
13219   // Diagnose "arg1 & arg2 | arg3"
13220   if ((Opc == BO_Or || Opc == BO_Xor) &&
13221       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13222     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13223     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13224   }
13225 
13226   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13227   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13228   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13229     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13230     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13231   }
13232 
13233   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13234       || Opc == BO_Shr) {
13235     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13236     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13237     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13238   }
13239 
13240   // Warn on overloaded shift operators and comparisons, such as:
13241   // cout << 5 == 4;
13242   if (BinaryOperator::isComparisonOp(Opc))
13243     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13244 }
13245 
13246 // Binary Operators.  'Tok' is the token for the operator.
13247 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13248                             tok::TokenKind Kind,
13249                             Expr *LHSExpr, Expr *RHSExpr) {
13250   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13251   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13252   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13253 
13254   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13255   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13256 
13257   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13258 }
13259 
13260 /// Build an overloaded binary operator expression in the given scope.
13261 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13262                                        BinaryOperatorKind Opc,
13263                                        Expr *LHS, Expr *RHS) {
13264   switch (Opc) {
13265   case BO_Assign:
13266   case BO_DivAssign:
13267   case BO_RemAssign:
13268   case BO_SubAssign:
13269   case BO_AndAssign:
13270   case BO_OrAssign:
13271   case BO_XorAssign:
13272     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13273     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13274     break;
13275   default:
13276     break;
13277   }
13278 
13279   // Find all of the overloaded operators visible from this
13280   // point. We perform both an operator-name lookup from the local
13281   // scope and an argument-dependent lookup based on the types of
13282   // the arguments.
13283   UnresolvedSet<16> Functions;
13284   OverloadedOperatorKind OverOp
13285     = BinaryOperator::getOverloadedOperator(Opc);
13286   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13287     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13288                                    RHS->getType(), Functions);
13289 
13290   // Build the (potentially-overloaded, potentially-dependent)
13291   // binary operation.
13292   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13293 }
13294 
13295 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13296                             BinaryOperatorKind Opc,
13297                             Expr *LHSExpr, Expr *RHSExpr) {
13298   ExprResult LHS, RHS;
13299   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13300   if (!LHS.isUsable() || !RHS.isUsable())
13301     return ExprError();
13302   LHSExpr = LHS.get();
13303   RHSExpr = RHS.get();
13304 
13305   // We want to end up calling one of checkPseudoObjectAssignment
13306   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13307   // both expressions are overloadable or either is type-dependent),
13308   // or CreateBuiltinBinOp (in any other case).  We also want to get
13309   // any placeholder types out of the way.
13310 
13311   // Handle pseudo-objects in the LHS.
13312   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13313     // Assignments with a pseudo-object l-value need special analysis.
13314     if (pty->getKind() == BuiltinType::PseudoObject &&
13315         BinaryOperator::isAssignmentOp(Opc))
13316       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13317 
13318     // Don't resolve overloads if the other type is overloadable.
13319     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13320       // We can't actually test that if we still have a placeholder,
13321       // though.  Fortunately, none of the exceptions we see in that
13322       // code below are valid when the LHS is an overload set.  Note
13323       // that an overload set can be dependently-typed, but it never
13324       // instantiates to having an overloadable type.
13325       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13326       if (resolvedRHS.isInvalid()) return ExprError();
13327       RHSExpr = resolvedRHS.get();
13328 
13329       if (RHSExpr->isTypeDependent() ||
13330           RHSExpr->getType()->isOverloadableType())
13331         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13332     }
13333 
13334     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13335     // template, diagnose the missing 'template' keyword instead of diagnosing
13336     // an invalid use of a bound member function.
13337     //
13338     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13339     // to C++1z [over.over]/1.4, but we already checked for that case above.
13340     if (Opc == BO_LT && inTemplateInstantiation() &&
13341         (pty->getKind() == BuiltinType::BoundMember ||
13342          pty->getKind() == BuiltinType::Overload)) {
13343       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13344       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13345           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13346             return isa<FunctionTemplateDecl>(ND);
13347           })) {
13348         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13349                                 : OE->getNameLoc(),
13350              diag::err_template_kw_missing)
13351           << OE->getName().getAsString() << "";
13352         return ExprError();
13353       }
13354     }
13355 
13356     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13357     if (LHS.isInvalid()) return ExprError();
13358     LHSExpr = LHS.get();
13359   }
13360 
13361   // Handle pseudo-objects in the RHS.
13362   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13363     // An overload in the RHS can potentially be resolved by the type
13364     // being assigned to.
13365     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13366       if (getLangOpts().CPlusPlus &&
13367           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13368            LHSExpr->getType()->isOverloadableType()))
13369         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13370 
13371       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13372     }
13373 
13374     // Don't resolve overloads if the other type is overloadable.
13375     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13376         LHSExpr->getType()->isOverloadableType())
13377       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13378 
13379     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13380     if (!resolvedRHS.isUsable()) return ExprError();
13381     RHSExpr = resolvedRHS.get();
13382   }
13383 
13384   if (getLangOpts().CPlusPlus) {
13385     // If either expression is type-dependent, always build an
13386     // overloaded op.
13387     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13388       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13389 
13390     // Otherwise, build an overloaded op if either expression has an
13391     // overloadable type.
13392     if (LHSExpr->getType()->isOverloadableType() ||
13393         RHSExpr->getType()->isOverloadableType())
13394       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13395   }
13396 
13397   // Build a built-in binary operation.
13398   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13399 }
13400 
13401 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13402   if (T.isNull() || T->isDependentType())
13403     return false;
13404 
13405   if (!T->isPromotableIntegerType())
13406     return true;
13407 
13408   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13409 }
13410 
13411 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13412                                       UnaryOperatorKind Opc,
13413                                       Expr *InputExpr) {
13414   ExprResult Input = InputExpr;
13415   ExprValueKind VK = VK_RValue;
13416   ExprObjectKind OK = OK_Ordinary;
13417   QualType resultType;
13418   bool CanOverflow = false;
13419 
13420   bool ConvertHalfVec = false;
13421   if (getLangOpts().OpenCL) {
13422     QualType Ty = InputExpr->getType();
13423     // The only legal unary operation for atomics is '&'.
13424     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13425     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13426     // only with a builtin functions and therefore should be disallowed here.
13427         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13428         || Ty->isBlockPointerType())) {
13429       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13430                        << InputExpr->getType()
13431                        << Input.get()->getSourceRange());
13432     }
13433   }
13434   // Diagnose operations on the unsupported types for OpenMP device compilation.
13435   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13436     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13437         UnaryOperator::isArithmeticOp(Opc))
13438       checkOpenMPDeviceExpr(InputExpr);
13439   }
13440 
13441   switch (Opc) {
13442   case UO_PreInc:
13443   case UO_PreDec:
13444   case UO_PostInc:
13445   case UO_PostDec:
13446     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13447                                                 OpLoc,
13448                                                 Opc == UO_PreInc ||
13449                                                 Opc == UO_PostInc,
13450                                                 Opc == UO_PreInc ||
13451                                                 Opc == UO_PreDec);
13452     CanOverflow = isOverflowingIntegerType(Context, resultType);
13453     break;
13454   case UO_AddrOf:
13455     resultType = CheckAddressOfOperand(Input, OpLoc);
13456     CheckAddressOfNoDeref(InputExpr);
13457     RecordModifiableNonNullParam(*this, InputExpr);
13458     break;
13459   case UO_Deref: {
13460     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13461     if (Input.isInvalid()) return ExprError();
13462     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13463     break;
13464   }
13465   case UO_Plus:
13466   case UO_Minus:
13467     CanOverflow = Opc == UO_Minus &&
13468                   isOverflowingIntegerType(Context, Input.get()->getType());
13469     Input = UsualUnaryConversions(Input.get());
13470     if (Input.isInvalid()) return ExprError();
13471     // Unary plus and minus require promoting an operand of half vector to a
13472     // float vector and truncating the result back to a half vector. For now, we
13473     // do this only when HalfArgsAndReturns is set (that is, when the target is
13474     // arm or arm64).
13475     ConvertHalfVec =
13476         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13477 
13478     // If the operand is a half vector, promote it to a float vector.
13479     if (ConvertHalfVec)
13480       Input = convertVector(Input.get(), Context.FloatTy, *this);
13481     resultType = Input.get()->getType();
13482     if (resultType->isDependentType())
13483       break;
13484     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13485       break;
13486     else if (resultType->isVectorType() &&
13487              // The z vector extensions don't allow + or - with bool vectors.
13488              (!Context.getLangOpts().ZVector ||
13489               resultType->castAs<VectorType>()->getVectorKind() !=
13490               VectorType::AltiVecBool))
13491       break;
13492     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13493              Opc == UO_Plus &&
13494              resultType->isPointerType())
13495       break;
13496 
13497     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13498       << resultType << Input.get()->getSourceRange());
13499 
13500   case UO_Not: // bitwise complement
13501     Input = UsualUnaryConversions(Input.get());
13502     if (Input.isInvalid())
13503       return ExprError();
13504     resultType = Input.get()->getType();
13505     if (resultType->isDependentType())
13506       break;
13507     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13508     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13509       // C99 does not support '~' for complex conjugation.
13510       Diag(OpLoc, diag::ext_integer_complement_complex)
13511           << resultType << Input.get()->getSourceRange();
13512     else if (resultType->hasIntegerRepresentation())
13513       break;
13514     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13515       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13516       // on vector float types.
13517       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13518       if (!T->isIntegerType())
13519         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13520                           << resultType << Input.get()->getSourceRange());
13521     } else {
13522       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13523                        << resultType << Input.get()->getSourceRange());
13524     }
13525     break;
13526 
13527   case UO_LNot: // logical negation
13528     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13529     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13530     if (Input.isInvalid()) return ExprError();
13531     resultType = Input.get()->getType();
13532 
13533     // Though we still have to promote half FP to float...
13534     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13535       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13536       resultType = Context.FloatTy;
13537     }
13538 
13539     if (resultType->isDependentType())
13540       break;
13541     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13542       // C99 6.5.3.3p1: ok, fallthrough;
13543       if (Context.getLangOpts().CPlusPlus) {
13544         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13545         // operand contextually converted to bool.
13546         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13547                                   ScalarTypeToBooleanCastKind(resultType));
13548       } else if (Context.getLangOpts().OpenCL &&
13549                  Context.getLangOpts().OpenCLVersion < 120) {
13550         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13551         // operate on scalar float types.
13552         if (!resultType->isIntegerType() && !resultType->isPointerType())
13553           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13554                            << resultType << Input.get()->getSourceRange());
13555       }
13556     } else if (resultType->isExtVectorType()) {
13557       if (Context.getLangOpts().OpenCL &&
13558           Context.getLangOpts().OpenCLVersion < 120 &&
13559           !Context.getLangOpts().OpenCLCPlusPlus) {
13560         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13561         // operate on vector float types.
13562         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13563         if (!T->isIntegerType())
13564           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13565                            << resultType << Input.get()->getSourceRange());
13566       }
13567       // Vector logical not returns the signed variant of the operand type.
13568       resultType = GetSignedVectorType(resultType);
13569       break;
13570     } else {
13571       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13572       //        type in C++. We should allow that here too.
13573       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13574         << resultType << Input.get()->getSourceRange());
13575     }
13576 
13577     // LNot always has type int. C99 6.5.3.3p5.
13578     // In C++, it's bool. C++ 5.3.1p8
13579     resultType = Context.getLogicalOperationType();
13580     break;
13581   case UO_Real:
13582   case UO_Imag:
13583     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13584     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13585     // complex l-values to ordinary l-values and all other values to r-values.
13586     if (Input.isInvalid()) return ExprError();
13587     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13588       if (Input.get()->getValueKind() != VK_RValue &&
13589           Input.get()->getObjectKind() == OK_Ordinary)
13590         VK = Input.get()->getValueKind();
13591     } else if (!getLangOpts().CPlusPlus) {
13592       // In C, a volatile scalar is read by __imag. In C++, it is not.
13593       Input = DefaultLvalueConversion(Input.get());
13594     }
13595     break;
13596   case UO_Extension:
13597     resultType = Input.get()->getType();
13598     VK = Input.get()->getValueKind();
13599     OK = Input.get()->getObjectKind();
13600     break;
13601   case UO_Coawait:
13602     // It's unnecessary to represent the pass-through operator co_await in the
13603     // AST; just return the input expression instead.
13604     assert(!Input.get()->getType()->isDependentType() &&
13605                    "the co_await expression must be non-dependant before "
13606                    "building operator co_await");
13607     return Input;
13608   }
13609   if (resultType.isNull() || Input.isInvalid())
13610     return ExprError();
13611 
13612   // Check for array bounds violations in the operand of the UnaryOperator,
13613   // except for the '*' and '&' operators that have to be handled specially
13614   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13615   // that are explicitly defined as valid by the standard).
13616   if (Opc != UO_AddrOf && Opc != UO_Deref)
13617     CheckArrayAccess(Input.get());
13618 
13619   auto *UO = new (Context)
13620       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13621 
13622   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13623       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13624     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13625 
13626   // Convert the result back to a half vector.
13627   if (ConvertHalfVec)
13628     return convertVector(UO, Context.HalfTy, *this);
13629   return UO;
13630 }
13631 
13632 /// Determine whether the given expression is a qualified member
13633 /// access expression, of a form that could be turned into a pointer to member
13634 /// with the address-of operator.
13635 bool Sema::isQualifiedMemberAccess(Expr *E) {
13636   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13637     if (!DRE->getQualifier())
13638       return false;
13639 
13640     ValueDecl *VD = DRE->getDecl();
13641     if (!VD->isCXXClassMember())
13642       return false;
13643 
13644     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13645       return true;
13646     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13647       return Method->isInstance();
13648 
13649     return false;
13650   }
13651 
13652   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13653     if (!ULE->getQualifier())
13654       return false;
13655 
13656     for (NamedDecl *D : ULE->decls()) {
13657       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13658         if (Method->isInstance())
13659           return true;
13660       } else {
13661         // Overload set does not contain methods.
13662         break;
13663       }
13664     }
13665 
13666     return false;
13667   }
13668 
13669   return false;
13670 }
13671 
13672 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13673                               UnaryOperatorKind Opc, Expr *Input) {
13674   // First things first: handle placeholders so that the
13675   // overloaded-operator check considers the right type.
13676   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13677     // Increment and decrement of pseudo-object references.
13678     if (pty->getKind() == BuiltinType::PseudoObject &&
13679         UnaryOperator::isIncrementDecrementOp(Opc))
13680       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13681 
13682     // extension is always a builtin operator.
13683     if (Opc == UO_Extension)
13684       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13685 
13686     // & gets special logic for several kinds of placeholder.
13687     // The builtin code knows what to do.
13688     if (Opc == UO_AddrOf &&
13689         (pty->getKind() == BuiltinType::Overload ||
13690          pty->getKind() == BuiltinType::UnknownAny ||
13691          pty->getKind() == BuiltinType::BoundMember))
13692       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13693 
13694     // Anything else needs to be handled now.
13695     ExprResult Result = CheckPlaceholderExpr(Input);
13696     if (Result.isInvalid()) return ExprError();
13697     Input = Result.get();
13698   }
13699 
13700   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13701       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13702       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13703     // Find all of the overloaded operators visible from this
13704     // point. We perform both an operator-name lookup from the local
13705     // scope and an argument-dependent lookup based on the types of
13706     // the arguments.
13707     UnresolvedSet<16> Functions;
13708     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13709     if (S && OverOp != OO_None)
13710       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13711                                    Functions);
13712 
13713     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13714   }
13715 
13716   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13717 }
13718 
13719 // Unary Operators.  'Tok' is the token for the operator.
13720 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13721                               tok::TokenKind Op, Expr *Input) {
13722   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13723 }
13724 
13725 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13726 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13727                                 LabelDecl *TheDecl) {
13728   TheDecl->markUsed(Context);
13729   // Create the AST node.  The address of a label always has type 'void*'.
13730   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13731                                      Context.getPointerType(Context.VoidTy));
13732 }
13733 
13734 void Sema::ActOnStartStmtExpr() {
13735   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13736 }
13737 
13738 void Sema::ActOnStmtExprError() {
13739   // Note that function is also called by TreeTransform when leaving a
13740   // StmtExpr scope without rebuilding anything.
13741 
13742   DiscardCleanupsInEvaluationContext();
13743   PopExpressionEvaluationContext();
13744 }
13745 
13746 ExprResult
13747 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13748                     SourceLocation RPLoc) { // "({..})"
13749   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13750   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13751 
13752   if (hasAnyUnrecoverableErrorsInThisFunction())
13753     DiscardCleanupsInEvaluationContext();
13754   assert(!Cleanup.exprNeedsCleanups() &&
13755          "cleanups within StmtExpr not correctly bound!");
13756   PopExpressionEvaluationContext();
13757 
13758   // FIXME: there are a variety of strange constraints to enforce here, for
13759   // example, it is not possible to goto into a stmt expression apparently.
13760   // More semantic analysis is needed.
13761 
13762   // If there are sub-stmts in the compound stmt, take the type of the last one
13763   // as the type of the stmtexpr.
13764   QualType Ty = Context.VoidTy;
13765   bool StmtExprMayBindToTemp = false;
13766   if (!Compound->body_empty()) {
13767     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13768     if (const auto *LastStmt =
13769             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13770       if (const Expr *Value = LastStmt->getExprStmt()) {
13771         StmtExprMayBindToTemp = true;
13772         Ty = Value->getType();
13773       }
13774     }
13775   }
13776 
13777   // FIXME: Check that expression type is complete/non-abstract; statement
13778   // expressions are not lvalues.
13779   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13780   if (StmtExprMayBindToTemp)
13781     return MaybeBindToTemporary(ResStmtExpr);
13782   return ResStmtExpr;
13783 }
13784 
13785 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13786   if (ER.isInvalid())
13787     return ExprError();
13788 
13789   // Do function/array conversion on the last expression, but not
13790   // lvalue-to-rvalue.  However, initialize an unqualified type.
13791   ER = DefaultFunctionArrayConversion(ER.get());
13792   if (ER.isInvalid())
13793     return ExprError();
13794   Expr *E = ER.get();
13795 
13796   if (E->isTypeDependent())
13797     return E;
13798 
13799   // In ARC, if the final expression ends in a consume, splice
13800   // the consume out and bind it later.  In the alternate case
13801   // (when dealing with a retainable type), the result
13802   // initialization will create a produce.  In both cases the
13803   // result will be +1, and we'll need to balance that out with
13804   // a bind.
13805   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13806   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13807     return Cast->getSubExpr();
13808 
13809   // FIXME: Provide a better location for the initialization.
13810   return PerformCopyInitialization(
13811       InitializedEntity::InitializeStmtExprResult(
13812           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13813       SourceLocation(), E);
13814 }
13815 
13816 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13817                                       TypeSourceInfo *TInfo,
13818                                       ArrayRef<OffsetOfComponent> Components,
13819                                       SourceLocation RParenLoc) {
13820   QualType ArgTy = TInfo->getType();
13821   bool Dependent = ArgTy->isDependentType();
13822   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13823 
13824   // We must have at least one component that refers to the type, and the first
13825   // one is known to be a field designator.  Verify that the ArgTy represents
13826   // a struct/union/class.
13827   if (!Dependent && !ArgTy->isRecordType())
13828     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13829                        << ArgTy << TypeRange);
13830 
13831   // Type must be complete per C99 7.17p3 because a declaring a variable
13832   // with an incomplete type would be ill-formed.
13833   if (!Dependent
13834       && RequireCompleteType(BuiltinLoc, ArgTy,
13835                              diag::err_offsetof_incomplete_type, TypeRange))
13836     return ExprError();
13837 
13838   bool DidWarnAboutNonPOD = false;
13839   QualType CurrentType = ArgTy;
13840   SmallVector<OffsetOfNode, 4> Comps;
13841   SmallVector<Expr*, 4> Exprs;
13842   for (const OffsetOfComponent &OC : Components) {
13843     if (OC.isBrackets) {
13844       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13845       if (!CurrentType->isDependentType()) {
13846         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13847         if(!AT)
13848           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13849                            << CurrentType);
13850         CurrentType = AT->getElementType();
13851       } else
13852         CurrentType = Context.DependentTy;
13853 
13854       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13855       if (IdxRval.isInvalid())
13856         return ExprError();
13857       Expr *Idx = IdxRval.get();
13858 
13859       // The expression must be an integral expression.
13860       // FIXME: An integral constant expression?
13861       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13862           !Idx->getType()->isIntegerType())
13863         return ExprError(
13864             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13865             << Idx->getSourceRange());
13866 
13867       // Record this array index.
13868       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13869       Exprs.push_back(Idx);
13870       continue;
13871     }
13872 
13873     // Offset of a field.
13874     if (CurrentType->isDependentType()) {
13875       // We have the offset of a field, but we can't look into the dependent
13876       // type. Just record the identifier of the field.
13877       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13878       CurrentType = Context.DependentTy;
13879       continue;
13880     }
13881 
13882     // We need to have a complete type to look into.
13883     if (RequireCompleteType(OC.LocStart, CurrentType,
13884                             diag::err_offsetof_incomplete_type))
13885       return ExprError();
13886 
13887     // Look for the designated field.
13888     const RecordType *RC = CurrentType->getAs<RecordType>();
13889     if (!RC)
13890       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13891                        << CurrentType);
13892     RecordDecl *RD = RC->getDecl();
13893 
13894     // C++ [lib.support.types]p5:
13895     //   The macro offsetof accepts a restricted set of type arguments in this
13896     //   International Standard. type shall be a POD structure or a POD union
13897     //   (clause 9).
13898     // C++11 [support.types]p4:
13899     //   If type is not a standard-layout class (Clause 9), the results are
13900     //   undefined.
13901     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13902       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13903       unsigned DiagID =
13904         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13905                             : diag::ext_offsetof_non_pod_type;
13906 
13907       if (!IsSafe && !DidWarnAboutNonPOD &&
13908           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13909                               PDiag(DiagID)
13910                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13911                               << CurrentType))
13912         DidWarnAboutNonPOD = true;
13913     }
13914 
13915     // Look for the field.
13916     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13917     LookupQualifiedName(R, RD);
13918     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13919     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13920     if (!MemberDecl) {
13921       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13922         MemberDecl = IndirectMemberDecl->getAnonField();
13923     }
13924 
13925     if (!MemberDecl)
13926       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13927                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13928                                                               OC.LocEnd));
13929 
13930     // C99 7.17p3:
13931     //   (If the specified member is a bit-field, the behavior is undefined.)
13932     //
13933     // We diagnose this as an error.
13934     if (MemberDecl->isBitField()) {
13935       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13936         << MemberDecl->getDeclName()
13937         << SourceRange(BuiltinLoc, RParenLoc);
13938       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13939       return ExprError();
13940     }
13941 
13942     RecordDecl *Parent = MemberDecl->getParent();
13943     if (IndirectMemberDecl)
13944       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13945 
13946     // If the member was found in a base class, introduce OffsetOfNodes for
13947     // the base class indirections.
13948     CXXBasePaths Paths;
13949     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13950                       Paths)) {
13951       if (Paths.getDetectedVirtual()) {
13952         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13953           << MemberDecl->getDeclName()
13954           << SourceRange(BuiltinLoc, RParenLoc);
13955         return ExprError();
13956       }
13957 
13958       CXXBasePath &Path = Paths.front();
13959       for (const CXXBasePathElement &B : Path)
13960         Comps.push_back(OffsetOfNode(B.Base));
13961     }
13962 
13963     if (IndirectMemberDecl) {
13964       for (auto *FI : IndirectMemberDecl->chain()) {
13965         assert(isa<FieldDecl>(FI));
13966         Comps.push_back(OffsetOfNode(OC.LocStart,
13967                                      cast<FieldDecl>(FI), OC.LocEnd));
13968       }
13969     } else
13970       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13971 
13972     CurrentType = MemberDecl->getType().getNonReferenceType();
13973   }
13974 
13975   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13976                               Comps, Exprs, RParenLoc);
13977 }
13978 
13979 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13980                                       SourceLocation BuiltinLoc,
13981                                       SourceLocation TypeLoc,
13982                                       ParsedType ParsedArgTy,
13983                                       ArrayRef<OffsetOfComponent> Components,
13984                                       SourceLocation RParenLoc) {
13985 
13986   TypeSourceInfo *ArgTInfo;
13987   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13988   if (ArgTy.isNull())
13989     return ExprError();
13990 
13991   if (!ArgTInfo)
13992     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13993 
13994   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13995 }
13996 
13997 
13998 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13999                                  Expr *CondExpr,
14000                                  Expr *LHSExpr, Expr *RHSExpr,
14001                                  SourceLocation RPLoc) {
14002   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14003 
14004   ExprValueKind VK = VK_RValue;
14005   ExprObjectKind OK = OK_Ordinary;
14006   QualType resType;
14007   bool ValueDependent = false;
14008   bool CondIsTrue = false;
14009   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14010     resType = Context.DependentTy;
14011     ValueDependent = true;
14012   } else {
14013     // The conditional expression is required to be a constant expression.
14014     llvm::APSInt condEval(32);
14015     ExprResult CondICE
14016       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14017           diag::err_typecheck_choose_expr_requires_constant, false);
14018     if (CondICE.isInvalid())
14019       return ExprError();
14020     CondExpr = CondICE.get();
14021     CondIsTrue = condEval.getZExtValue();
14022 
14023     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14024     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14025 
14026     resType = ActiveExpr->getType();
14027     ValueDependent = ActiveExpr->isValueDependent();
14028     VK = ActiveExpr->getValueKind();
14029     OK = ActiveExpr->getObjectKind();
14030   }
14031 
14032   return new (Context)
14033       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14034                  CondIsTrue, resType->isDependentType(), ValueDependent);
14035 }
14036 
14037 //===----------------------------------------------------------------------===//
14038 // Clang Extensions.
14039 //===----------------------------------------------------------------------===//
14040 
14041 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14042 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14043   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14044 
14045   if (LangOpts.CPlusPlus) {
14046     MangleNumberingContext *MCtx;
14047     Decl *ManglingContextDecl;
14048     std::tie(MCtx, ManglingContextDecl) =
14049         getCurrentMangleNumberContext(Block->getDeclContext());
14050     if (MCtx) {
14051       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14052       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14053     }
14054   }
14055 
14056   PushBlockScope(CurScope, Block);
14057   CurContext->addDecl(Block);
14058   if (CurScope)
14059     PushDeclContext(CurScope, Block);
14060   else
14061     CurContext = Block;
14062 
14063   getCurBlock()->HasImplicitReturnType = true;
14064 
14065   // Enter a new evaluation context to insulate the block from any
14066   // cleanups from the enclosing full-expression.
14067   PushExpressionEvaluationContext(
14068       ExpressionEvaluationContext::PotentiallyEvaluated);
14069 }
14070 
14071 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14072                                Scope *CurScope) {
14073   assert(ParamInfo.getIdentifier() == nullptr &&
14074          "block-id should have no identifier!");
14075   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14076   BlockScopeInfo *CurBlock = getCurBlock();
14077 
14078   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14079   QualType T = Sig->getType();
14080 
14081   // FIXME: We should allow unexpanded parameter packs here, but that would,
14082   // in turn, make the block expression contain unexpanded parameter packs.
14083   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14084     // Drop the parameters.
14085     FunctionProtoType::ExtProtoInfo EPI;
14086     EPI.HasTrailingReturn = false;
14087     EPI.TypeQuals.addConst();
14088     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14089     Sig = Context.getTrivialTypeSourceInfo(T);
14090   }
14091 
14092   // GetTypeForDeclarator always produces a function type for a block
14093   // literal signature.  Furthermore, it is always a FunctionProtoType
14094   // unless the function was written with a typedef.
14095   assert(T->isFunctionType() &&
14096          "GetTypeForDeclarator made a non-function block signature");
14097 
14098   // Look for an explicit signature in that function type.
14099   FunctionProtoTypeLoc ExplicitSignature;
14100 
14101   if ((ExplicitSignature = Sig->getTypeLoc()
14102                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14103 
14104     // Check whether that explicit signature was synthesized by
14105     // GetTypeForDeclarator.  If so, don't save that as part of the
14106     // written signature.
14107     if (ExplicitSignature.getLocalRangeBegin() ==
14108         ExplicitSignature.getLocalRangeEnd()) {
14109       // This would be much cheaper if we stored TypeLocs instead of
14110       // TypeSourceInfos.
14111       TypeLoc Result = ExplicitSignature.getReturnLoc();
14112       unsigned Size = Result.getFullDataSize();
14113       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14114       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14115 
14116       ExplicitSignature = FunctionProtoTypeLoc();
14117     }
14118   }
14119 
14120   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14121   CurBlock->FunctionType = T;
14122 
14123   const FunctionType *Fn = T->getAs<FunctionType>();
14124   QualType RetTy = Fn->getReturnType();
14125   bool isVariadic =
14126     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14127 
14128   CurBlock->TheDecl->setIsVariadic(isVariadic);
14129 
14130   // Context.DependentTy is used as a placeholder for a missing block
14131   // return type.  TODO:  what should we do with declarators like:
14132   //   ^ * { ... }
14133   // If the answer is "apply template argument deduction"....
14134   if (RetTy != Context.DependentTy) {
14135     CurBlock->ReturnType = RetTy;
14136     CurBlock->TheDecl->setBlockMissingReturnType(false);
14137     CurBlock->HasImplicitReturnType = false;
14138   }
14139 
14140   // Push block parameters from the declarator if we had them.
14141   SmallVector<ParmVarDecl*, 8> Params;
14142   if (ExplicitSignature) {
14143     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14144       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14145       if (Param->getIdentifier() == nullptr &&
14146           !Param->isImplicit() &&
14147           !Param->isInvalidDecl() &&
14148           !getLangOpts().CPlusPlus)
14149         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14150       Params.push_back(Param);
14151     }
14152 
14153   // Fake up parameter variables if we have a typedef, like
14154   //   ^ fntype { ... }
14155   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14156     for (const auto &I : Fn->param_types()) {
14157       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14158           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14159       Params.push_back(Param);
14160     }
14161   }
14162 
14163   // Set the parameters on the block decl.
14164   if (!Params.empty()) {
14165     CurBlock->TheDecl->setParams(Params);
14166     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14167                              /*CheckParameterNames=*/false);
14168   }
14169 
14170   // Finally we can process decl attributes.
14171   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14172 
14173   // Put the parameter variables in scope.
14174   for (auto AI : CurBlock->TheDecl->parameters()) {
14175     AI->setOwningFunction(CurBlock->TheDecl);
14176 
14177     // If this has an identifier, add it to the scope stack.
14178     if (AI->getIdentifier()) {
14179       CheckShadow(CurBlock->TheScope, AI);
14180 
14181       PushOnScopeChains(AI, CurBlock->TheScope);
14182     }
14183   }
14184 }
14185 
14186 /// ActOnBlockError - If there is an error parsing a block, this callback
14187 /// is invoked to pop the information about the block from the action impl.
14188 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14189   // Leave the expression-evaluation context.
14190   DiscardCleanupsInEvaluationContext();
14191   PopExpressionEvaluationContext();
14192 
14193   // Pop off CurBlock, handle nested blocks.
14194   PopDeclContext();
14195   PopFunctionScopeInfo();
14196 }
14197 
14198 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14199 /// literal was successfully completed.  ^(int x){...}
14200 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14201                                     Stmt *Body, Scope *CurScope) {
14202   // If blocks are disabled, emit an error.
14203   if (!LangOpts.Blocks)
14204     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14205 
14206   // Leave the expression-evaluation context.
14207   if (hasAnyUnrecoverableErrorsInThisFunction())
14208     DiscardCleanupsInEvaluationContext();
14209   assert(!Cleanup.exprNeedsCleanups() &&
14210          "cleanups within block not correctly bound!");
14211   PopExpressionEvaluationContext();
14212 
14213   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14214   BlockDecl *BD = BSI->TheDecl;
14215 
14216   if (BSI->HasImplicitReturnType)
14217     deduceClosureReturnType(*BSI);
14218 
14219   QualType RetTy = Context.VoidTy;
14220   if (!BSI->ReturnType.isNull())
14221     RetTy = BSI->ReturnType;
14222 
14223   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14224   QualType BlockTy;
14225 
14226   // If the user wrote a function type in some form, try to use that.
14227   if (!BSI->FunctionType.isNull()) {
14228     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14229 
14230     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14231     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14232 
14233     // Turn protoless block types into nullary block types.
14234     if (isa<FunctionNoProtoType>(FTy)) {
14235       FunctionProtoType::ExtProtoInfo EPI;
14236       EPI.ExtInfo = Ext;
14237       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14238 
14239     // Otherwise, if we don't need to change anything about the function type,
14240     // preserve its sugar structure.
14241     } else if (FTy->getReturnType() == RetTy &&
14242                (!NoReturn || FTy->getNoReturnAttr())) {
14243       BlockTy = BSI->FunctionType;
14244 
14245     // Otherwise, make the minimal modifications to the function type.
14246     } else {
14247       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14248       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14249       EPI.TypeQuals = Qualifiers();
14250       EPI.ExtInfo = Ext;
14251       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14252     }
14253 
14254   // If we don't have a function type, just build one from nothing.
14255   } else {
14256     FunctionProtoType::ExtProtoInfo EPI;
14257     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14258     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14259   }
14260 
14261   DiagnoseUnusedParameters(BD->parameters());
14262   BlockTy = Context.getBlockPointerType(BlockTy);
14263 
14264   // If needed, diagnose invalid gotos and switches in the block.
14265   if (getCurFunction()->NeedsScopeChecking() &&
14266       !PP.isCodeCompletionEnabled())
14267     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14268 
14269   BD->setBody(cast<CompoundStmt>(Body));
14270 
14271   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14272     DiagnoseUnguardedAvailabilityViolations(BD);
14273 
14274   // Try to apply the named return value optimization. We have to check again
14275   // if we can do this, though, because blocks keep return statements around
14276   // to deduce an implicit return type.
14277   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14278       !BD->isDependentContext())
14279     computeNRVO(Body, BSI);
14280 
14281   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14282       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14283     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14284                           NTCUK_Destruct|NTCUK_Copy);
14285 
14286   PopDeclContext();
14287 
14288   // Pop the block scope now but keep it alive to the end of this function.
14289   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14290   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14291 
14292   // Set the captured variables on the block.
14293   SmallVector<BlockDecl::Capture, 4> Captures;
14294   for (Capture &Cap : BSI->Captures) {
14295     if (Cap.isInvalid() || Cap.isThisCapture())
14296       continue;
14297 
14298     VarDecl *Var = Cap.getVariable();
14299     Expr *CopyExpr = nullptr;
14300     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14301       if (const RecordType *Record =
14302               Cap.getCaptureType()->getAs<RecordType>()) {
14303         // The capture logic needs the destructor, so make sure we mark it.
14304         // Usually this is unnecessary because most local variables have
14305         // their destructors marked at declaration time, but parameters are
14306         // an exception because it's technically only the call site that
14307         // actually requires the destructor.
14308         if (isa<ParmVarDecl>(Var))
14309           FinalizeVarWithDestructor(Var, Record);
14310 
14311         // Enter a separate potentially-evaluated context while building block
14312         // initializers to isolate their cleanups from those of the block
14313         // itself.
14314         // FIXME: Is this appropriate even when the block itself occurs in an
14315         // unevaluated operand?
14316         EnterExpressionEvaluationContext EvalContext(
14317             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14318 
14319         SourceLocation Loc = Cap.getLocation();
14320 
14321         ExprResult Result = BuildDeclarationNameExpr(
14322             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14323 
14324         // According to the blocks spec, the capture of a variable from
14325         // the stack requires a const copy constructor.  This is not true
14326         // of the copy/move done to move a __block variable to the heap.
14327         if (!Result.isInvalid() &&
14328             !Result.get()->getType().isConstQualified()) {
14329           Result = ImpCastExprToType(Result.get(),
14330                                      Result.get()->getType().withConst(),
14331                                      CK_NoOp, VK_LValue);
14332         }
14333 
14334         if (!Result.isInvalid()) {
14335           Result = PerformCopyInitialization(
14336               InitializedEntity::InitializeBlock(Var->getLocation(),
14337                                                  Cap.getCaptureType(), false),
14338               Loc, Result.get());
14339         }
14340 
14341         // Build a full-expression copy expression if initialization
14342         // succeeded and used a non-trivial constructor.  Recover from
14343         // errors by pretending that the copy isn't necessary.
14344         if (!Result.isInvalid() &&
14345             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14346                 ->isTrivial()) {
14347           Result = MaybeCreateExprWithCleanups(Result);
14348           CopyExpr = Result.get();
14349         }
14350       }
14351     }
14352 
14353     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14354                               CopyExpr);
14355     Captures.push_back(NewCap);
14356   }
14357   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14358 
14359   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14360 
14361   // If the block isn't obviously global, i.e. it captures anything at
14362   // all, then we need to do a few things in the surrounding context:
14363   if (Result->getBlockDecl()->hasCaptures()) {
14364     // First, this expression has a new cleanup object.
14365     ExprCleanupObjects.push_back(Result->getBlockDecl());
14366     Cleanup.setExprNeedsCleanups(true);
14367 
14368     // It also gets a branch-protected scope if any of the captured
14369     // variables needs destruction.
14370     for (const auto &CI : Result->getBlockDecl()->captures()) {
14371       const VarDecl *var = CI.getVariable();
14372       if (var->getType().isDestructedType() != QualType::DK_none) {
14373         setFunctionHasBranchProtectedScope();
14374         break;
14375       }
14376     }
14377   }
14378 
14379   if (getCurFunction())
14380     getCurFunction()->addBlock(BD);
14381 
14382   return Result;
14383 }
14384 
14385 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14386                             SourceLocation RPLoc) {
14387   TypeSourceInfo *TInfo;
14388   GetTypeFromParser(Ty, &TInfo);
14389   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14390 }
14391 
14392 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14393                                 Expr *E, TypeSourceInfo *TInfo,
14394                                 SourceLocation RPLoc) {
14395   Expr *OrigExpr = E;
14396   bool IsMS = false;
14397 
14398   // CUDA device code does not support varargs.
14399   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14400     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14401       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14402       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14403         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14404     }
14405   }
14406 
14407   // NVPTX does not support va_arg expression.
14408   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14409       Context.getTargetInfo().getTriple().isNVPTX())
14410     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14411 
14412   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14413   // as Microsoft ABI on an actual Microsoft platform, where
14414   // __builtin_ms_va_list and __builtin_va_list are the same.)
14415   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14416       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14417     QualType MSVaListType = Context.getBuiltinMSVaListType();
14418     if (Context.hasSameType(MSVaListType, E->getType())) {
14419       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14420         return ExprError();
14421       IsMS = true;
14422     }
14423   }
14424 
14425   // Get the va_list type
14426   QualType VaListType = Context.getBuiltinVaListType();
14427   if (!IsMS) {
14428     if (VaListType->isArrayType()) {
14429       // Deal with implicit array decay; for example, on x86-64,
14430       // va_list is an array, but it's supposed to decay to
14431       // a pointer for va_arg.
14432       VaListType = Context.getArrayDecayedType(VaListType);
14433       // Make sure the input expression also decays appropriately.
14434       ExprResult Result = UsualUnaryConversions(E);
14435       if (Result.isInvalid())
14436         return ExprError();
14437       E = Result.get();
14438     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14439       // If va_list is a record type and we are compiling in C++ mode,
14440       // check the argument using reference binding.
14441       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14442           Context, Context.getLValueReferenceType(VaListType), false);
14443       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14444       if (Init.isInvalid())
14445         return ExprError();
14446       E = Init.getAs<Expr>();
14447     } else {
14448       // Otherwise, the va_list argument must be an l-value because
14449       // it is modified by va_arg.
14450       if (!E->isTypeDependent() &&
14451           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14452         return ExprError();
14453     }
14454   }
14455 
14456   if (!IsMS && !E->isTypeDependent() &&
14457       !Context.hasSameType(VaListType, E->getType()))
14458     return ExprError(
14459         Diag(E->getBeginLoc(),
14460              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14461         << OrigExpr->getType() << E->getSourceRange());
14462 
14463   if (!TInfo->getType()->isDependentType()) {
14464     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14465                             diag::err_second_parameter_to_va_arg_incomplete,
14466                             TInfo->getTypeLoc()))
14467       return ExprError();
14468 
14469     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14470                                TInfo->getType(),
14471                                diag::err_second_parameter_to_va_arg_abstract,
14472                                TInfo->getTypeLoc()))
14473       return ExprError();
14474 
14475     if (!TInfo->getType().isPODType(Context)) {
14476       Diag(TInfo->getTypeLoc().getBeginLoc(),
14477            TInfo->getType()->isObjCLifetimeType()
14478              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14479              : diag::warn_second_parameter_to_va_arg_not_pod)
14480         << TInfo->getType()
14481         << TInfo->getTypeLoc().getSourceRange();
14482     }
14483 
14484     // Check for va_arg where arguments of the given type will be promoted
14485     // (i.e. this va_arg is guaranteed to have undefined behavior).
14486     QualType PromoteType;
14487     if (TInfo->getType()->isPromotableIntegerType()) {
14488       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14489       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14490         PromoteType = QualType();
14491     }
14492     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14493       PromoteType = Context.DoubleTy;
14494     if (!PromoteType.isNull())
14495       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14496                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14497                           << TInfo->getType()
14498                           << PromoteType
14499                           << TInfo->getTypeLoc().getSourceRange());
14500   }
14501 
14502   QualType T = TInfo->getType().getNonLValueExprType(Context);
14503   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14504 }
14505 
14506 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14507   // The type of __null will be int or long, depending on the size of
14508   // pointers on the target.
14509   QualType Ty;
14510   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14511   if (pw == Context.getTargetInfo().getIntWidth())
14512     Ty = Context.IntTy;
14513   else if (pw == Context.getTargetInfo().getLongWidth())
14514     Ty = Context.LongTy;
14515   else if (pw == Context.getTargetInfo().getLongLongWidth())
14516     Ty = Context.LongLongTy;
14517   else {
14518     llvm_unreachable("I don't know size of pointer!");
14519   }
14520 
14521   return new (Context) GNUNullExpr(Ty, TokenLoc);
14522 }
14523 
14524 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14525                                     SourceLocation BuiltinLoc,
14526                                     SourceLocation RPLoc) {
14527   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14528 }
14529 
14530 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14531                                     SourceLocation BuiltinLoc,
14532                                     SourceLocation RPLoc,
14533                                     DeclContext *ParentContext) {
14534   return new (Context)
14535       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14536 }
14537 
14538 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14539                                               bool Diagnose) {
14540   if (!getLangOpts().ObjC)
14541     return false;
14542 
14543   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14544   if (!PT)
14545     return false;
14546 
14547   if (!PT->isObjCIdType()) {
14548     // Check if the destination is the 'NSString' interface.
14549     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14550     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14551       return false;
14552   }
14553 
14554   // Ignore any parens, implicit casts (should only be
14555   // array-to-pointer decays), and not-so-opaque values.  The last is
14556   // important for making this trigger for property assignments.
14557   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14558   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14559     if (OV->getSourceExpr())
14560       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14561 
14562   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14563   if (!SL || !SL->isAscii())
14564     return false;
14565   if (Diagnose) {
14566     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14567         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14568     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14569   }
14570   return true;
14571 }
14572 
14573 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14574                                               const Expr *SrcExpr) {
14575   if (!DstType->isFunctionPointerType() ||
14576       !SrcExpr->getType()->isFunctionType())
14577     return false;
14578 
14579   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14580   if (!DRE)
14581     return false;
14582 
14583   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14584   if (!FD)
14585     return false;
14586 
14587   return !S.checkAddressOfFunctionIsAvailable(FD,
14588                                               /*Complain=*/true,
14589                                               SrcExpr->getBeginLoc());
14590 }
14591 
14592 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14593                                     SourceLocation Loc,
14594                                     QualType DstType, QualType SrcType,
14595                                     Expr *SrcExpr, AssignmentAction Action,
14596                                     bool *Complained) {
14597   if (Complained)
14598     *Complained = false;
14599 
14600   // Decode the result (notice that AST's are still created for extensions).
14601   bool CheckInferredResultType = false;
14602   bool isInvalid = false;
14603   unsigned DiagKind = 0;
14604   FixItHint Hint;
14605   ConversionFixItGenerator ConvHints;
14606   bool MayHaveConvFixit = false;
14607   bool MayHaveFunctionDiff = false;
14608   const ObjCInterfaceDecl *IFace = nullptr;
14609   const ObjCProtocolDecl *PDecl = nullptr;
14610 
14611   switch (ConvTy) {
14612   case Compatible:
14613       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14614       return false;
14615 
14616   case PointerToInt:
14617     DiagKind = diag::ext_typecheck_convert_pointer_int;
14618     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14619     MayHaveConvFixit = true;
14620     break;
14621   case IntToPointer:
14622     DiagKind = diag::ext_typecheck_convert_int_pointer;
14623     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14624     MayHaveConvFixit = true;
14625     break;
14626   case IncompatiblePointer:
14627     if (Action == AA_Passing_CFAudited)
14628       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14629     else if (SrcType->isFunctionPointerType() &&
14630              DstType->isFunctionPointerType())
14631       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14632     else
14633       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14634 
14635     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14636       SrcType->isObjCObjectPointerType();
14637     if (Hint.isNull() && !CheckInferredResultType) {
14638       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14639     }
14640     else if (CheckInferredResultType) {
14641       SrcType = SrcType.getUnqualifiedType();
14642       DstType = DstType.getUnqualifiedType();
14643     }
14644     MayHaveConvFixit = true;
14645     break;
14646   case IncompatiblePointerSign:
14647     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14648     break;
14649   case FunctionVoidPointer:
14650     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14651     break;
14652   case IncompatiblePointerDiscardsQualifiers: {
14653     // Perform array-to-pointer decay if necessary.
14654     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14655 
14656     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14657     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14658     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14659       DiagKind = diag::err_typecheck_incompatible_address_space;
14660       break;
14661 
14662     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14663       DiagKind = diag::err_typecheck_incompatible_ownership;
14664       break;
14665     }
14666 
14667     llvm_unreachable("unknown error case for discarding qualifiers!");
14668     // fallthrough
14669   }
14670   case CompatiblePointerDiscardsQualifiers:
14671     // If the qualifiers lost were because we were applying the
14672     // (deprecated) C++ conversion from a string literal to a char*
14673     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14674     // Ideally, this check would be performed in
14675     // checkPointerTypesForAssignment. However, that would require a
14676     // bit of refactoring (so that the second argument is an
14677     // expression, rather than a type), which should be done as part
14678     // of a larger effort to fix checkPointerTypesForAssignment for
14679     // C++ semantics.
14680     if (getLangOpts().CPlusPlus &&
14681         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14682       return false;
14683     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14684     break;
14685   case IncompatibleNestedPointerQualifiers:
14686     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14687     break;
14688   case IncompatibleNestedPointerAddressSpaceMismatch:
14689     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14690     break;
14691   case IntToBlockPointer:
14692     DiagKind = diag::err_int_to_block_pointer;
14693     break;
14694   case IncompatibleBlockPointer:
14695     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14696     break;
14697   case IncompatibleObjCQualifiedId: {
14698     if (SrcType->isObjCQualifiedIdType()) {
14699       const ObjCObjectPointerType *srcOPT =
14700                 SrcType->castAs<ObjCObjectPointerType>();
14701       for (auto *srcProto : srcOPT->quals()) {
14702         PDecl = srcProto;
14703         break;
14704       }
14705       if (const ObjCInterfaceType *IFaceT =
14706             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14707         IFace = IFaceT->getDecl();
14708     }
14709     else if (DstType->isObjCQualifiedIdType()) {
14710       const ObjCObjectPointerType *dstOPT =
14711         DstType->castAs<ObjCObjectPointerType>();
14712       for (auto *dstProto : dstOPT->quals()) {
14713         PDecl = dstProto;
14714         break;
14715       }
14716       if (const ObjCInterfaceType *IFaceT =
14717             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14718         IFace = IFaceT->getDecl();
14719     }
14720     DiagKind = diag::warn_incompatible_qualified_id;
14721     break;
14722   }
14723   case IncompatibleVectors:
14724     DiagKind = diag::warn_incompatible_vectors;
14725     break;
14726   case IncompatibleObjCWeakRef:
14727     DiagKind = diag::err_arc_weak_unavailable_assign;
14728     break;
14729   case Incompatible:
14730     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14731       if (Complained)
14732         *Complained = true;
14733       return true;
14734     }
14735 
14736     DiagKind = diag::err_typecheck_convert_incompatible;
14737     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14738     MayHaveConvFixit = true;
14739     isInvalid = true;
14740     MayHaveFunctionDiff = true;
14741     break;
14742   }
14743 
14744   QualType FirstType, SecondType;
14745   switch (Action) {
14746   case AA_Assigning:
14747   case AA_Initializing:
14748     // The destination type comes first.
14749     FirstType = DstType;
14750     SecondType = SrcType;
14751     break;
14752 
14753   case AA_Returning:
14754   case AA_Passing:
14755   case AA_Passing_CFAudited:
14756   case AA_Converting:
14757   case AA_Sending:
14758   case AA_Casting:
14759     // The source type comes first.
14760     FirstType = SrcType;
14761     SecondType = DstType;
14762     break;
14763   }
14764 
14765   PartialDiagnostic FDiag = PDiag(DiagKind);
14766   if (Action == AA_Passing_CFAudited)
14767     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14768   else
14769     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14770 
14771   // If we can fix the conversion, suggest the FixIts.
14772   assert(ConvHints.isNull() || Hint.isNull());
14773   if (!ConvHints.isNull()) {
14774     for (FixItHint &H : ConvHints.Hints)
14775       FDiag << H;
14776   } else {
14777     FDiag << Hint;
14778   }
14779   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14780 
14781   if (MayHaveFunctionDiff)
14782     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14783 
14784   Diag(Loc, FDiag);
14785   if (DiagKind == diag::warn_incompatible_qualified_id &&
14786       PDecl && IFace && !IFace->hasDefinition())
14787       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14788         << IFace << PDecl;
14789 
14790   if (SecondType == Context.OverloadTy)
14791     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14792                               FirstType, /*TakingAddress=*/true);
14793 
14794   if (CheckInferredResultType)
14795     EmitRelatedResultTypeNote(SrcExpr);
14796 
14797   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14798     EmitRelatedResultTypeNoteForReturn(DstType);
14799 
14800   if (Complained)
14801     *Complained = true;
14802   return isInvalid;
14803 }
14804 
14805 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14806                                                  llvm::APSInt *Result) {
14807   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14808   public:
14809     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14810       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14811     }
14812   } Diagnoser;
14813 
14814   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14815 }
14816 
14817 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14818                                                  llvm::APSInt *Result,
14819                                                  unsigned DiagID,
14820                                                  bool AllowFold) {
14821   class IDDiagnoser : public VerifyICEDiagnoser {
14822     unsigned DiagID;
14823 
14824   public:
14825     IDDiagnoser(unsigned DiagID)
14826       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14827 
14828     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14829       S.Diag(Loc, DiagID) << SR;
14830     }
14831   } Diagnoser(DiagID);
14832 
14833   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14834 }
14835 
14836 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14837                                             SourceRange SR) {
14838   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14839 }
14840 
14841 ExprResult
14842 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14843                                       VerifyICEDiagnoser &Diagnoser,
14844                                       bool AllowFold) {
14845   SourceLocation DiagLoc = E->getBeginLoc();
14846 
14847   if (getLangOpts().CPlusPlus11) {
14848     // C++11 [expr.const]p5:
14849     //   If an expression of literal class type is used in a context where an
14850     //   integral constant expression is required, then that class type shall
14851     //   have a single non-explicit conversion function to an integral or
14852     //   unscoped enumeration type
14853     ExprResult Converted;
14854     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14855     public:
14856       CXX11ConvertDiagnoser(bool Silent)
14857           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14858                                 Silent, true) {}
14859 
14860       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14861                                            QualType T) override {
14862         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14863       }
14864 
14865       SemaDiagnosticBuilder diagnoseIncomplete(
14866           Sema &S, SourceLocation Loc, QualType T) override {
14867         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14868       }
14869 
14870       SemaDiagnosticBuilder diagnoseExplicitConv(
14871           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14872         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14873       }
14874 
14875       SemaDiagnosticBuilder noteExplicitConv(
14876           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14877         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14878                  << ConvTy->isEnumeralType() << ConvTy;
14879       }
14880 
14881       SemaDiagnosticBuilder diagnoseAmbiguous(
14882           Sema &S, SourceLocation Loc, QualType T) override {
14883         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14884       }
14885 
14886       SemaDiagnosticBuilder noteAmbiguous(
14887           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14888         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14889                  << ConvTy->isEnumeralType() << ConvTy;
14890       }
14891 
14892       SemaDiagnosticBuilder diagnoseConversion(
14893           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14894         llvm_unreachable("conversion functions are permitted");
14895       }
14896     } ConvertDiagnoser(Diagnoser.Suppress);
14897 
14898     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14899                                                     ConvertDiagnoser);
14900     if (Converted.isInvalid())
14901       return Converted;
14902     E = Converted.get();
14903     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14904       return ExprError();
14905   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14906     // An ICE must be of integral or unscoped enumeration type.
14907     if (!Diagnoser.Suppress)
14908       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14909     return ExprError();
14910   }
14911 
14912   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14913   // in the non-ICE case.
14914   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14915     if (Result)
14916       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14917     if (!isa<ConstantExpr>(E))
14918       E = ConstantExpr::Create(Context, E);
14919     return E;
14920   }
14921 
14922   Expr::EvalResult EvalResult;
14923   SmallVector<PartialDiagnosticAt, 8> Notes;
14924   EvalResult.Diag = &Notes;
14925 
14926   // Try to evaluate the expression, and produce diagnostics explaining why it's
14927   // not a constant expression as a side-effect.
14928   bool Folded =
14929       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14930       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14931 
14932   if (!isa<ConstantExpr>(E))
14933     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14934 
14935   // In C++11, we can rely on diagnostics being produced for any expression
14936   // which is not a constant expression. If no diagnostics were produced, then
14937   // this is a constant expression.
14938   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14939     if (Result)
14940       *Result = EvalResult.Val.getInt();
14941     return E;
14942   }
14943 
14944   // If our only note is the usual "invalid subexpression" note, just point
14945   // the caret at its location rather than producing an essentially
14946   // redundant note.
14947   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14948         diag::note_invalid_subexpr_in_const_expr) {
14949     DiagLoc = Notes[0].first;
14950     Notes.clear();
14951   }
14952 
14953   if (!Folded || !AllowFold) {
14954     if (!Diagnoser.Suppress) {
14955       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14956       for (const PartialDiagnosticAt &Note : Notes)
14957         Diag(Note.first, Note.second);
14958     }
14959 
14960     return ExprError();
14961   }
14962 
14963   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14964   for (const PartialDiagnosticAt &Note : Notes)
14965     Diag(Note.first, Note.second);
14966 
14967   if (Result)
14968     *Result = EvalResult.Val.getInt();
14969   return E;
14970 }
14971 
14972 namespace {
14973   // Handle the case where we conclude a expression which we speculatively
14974   // considered to be unevaluated is actually evaluated.
14975   class TransformToPE : public TreeTransform<TransformToPE> {
14976     typedef TreeTransform<TransformToPE> BaseTransform;
14977 
14978   public:
14979     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14980 
14981     // Make sure we redo semantic analysis
14982     bool AlwaysRebuild() { return true; }
14983     bool ReplacingOriginal() { return true; }
14984 
14985     // We need to special-case DeclRefExprs referring to FieldDecls which
14986     // are not part of a member pointer formation; normal TreeTransforming
14987     // doesn't catch this case because of the way we represent them in the AST.
14988     // FIXME: This is a bit ugly; is it really the best way to handle this
14989     // case?
14990     //
14991     // Error on DeclRefExprs referring to FieldDecls.
14992     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14993       if (isa<FieldDecl>(E->getDecl()) &&
14994           !SemaRef.isUnevaluatedContext())
14995         return SemaRef.Diag(E->getLocation(),
14996                             diag::err_invalid_non_static_member_use)
14997             << E->getDecl() << E->getSourceRange();
14998 
14999       return BaseTransform::TransformDeclRefExpr(E);
15000     }
15001 
15002     // Exception: filter out member pointer formation
15003     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15004       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15005         return E;
15006 
15007       return BaseTransform::TransformUnaryOperator(E);
15008     }
15009 
15010     // The body of a lambda-expression is in a separate expression evaluation
15011     // context so never needs to be transformed.
15012     // FIXME: Ideally we wouldn't transform the closure type either, and would
15013     // just recreate the capture expressions and lambda expression.
15014     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15015       return SkipLambdaBody(E, Body);
15016     }
15017   };
15018 }
15019 
15020 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15021   assert(isUnevaluatedContext() &&
15022          "Should only transform unevaluated expressions");
15023   ExprEvalContexts.back().Context =
15024       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15025   if (isUnevaluatedContext())
15026     return E;
15027   return TransformToPE(*this).TransformExpr(E);
15028 }
15029 
15030 void
15031 Sema::PushExpressionEvaluationContext(
15032     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15033     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15034   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15035                                 LambdaContextDecl, ExprContext);
15036   Cleanup.reset();
15037   if (!MaybeODRUseExprs.empty())
15038     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15039 }
15040 
15041 void
15042 Sema::PushExpressionEvaluationContext(
15043     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15044     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15045   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15046   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15047 }
15048 
15049 namespace {
15050 
15051 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15052   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15053   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15054     if (E->getOpcode() == UO_Deref)
15055       return CheckPossibleDeref(S, E->getSubExpr());
15056   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15057     return CheckPossibleDeref(S, E->getBase());
15058   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15059     return CheckPossibleDeref(S, E->getBase());
15060   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15061     QualType Inner;
15062     QualType Ty = E->getType();
15063     if (const auto *Ptr = Ty->getAs<PointerType>())
15064       Inner = Ptr->getPointeeType();
15065     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15066       Inner = Arr->getElementType();
15067     else
15068       return nullptr;
15069 
15070     if (Inner->hasAttr(attr::NoDeref))
15071       return E;
15072   }
15073   return nullptr;
15074 }
15075 
15076 } // namespace
15077 
15078 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15079   for (const Expr *E : Rec.PossibleDerefs) {
15080     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15081     if (DeclRef) {
15082       const ValueDecl *Decl = DeclRef->getDecl();
15083       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15084           << Decl->getName() << E->getSourceRange();
15085       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15086     } else {
15087       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15088           << E->getSourceRange();
15089     }
15090   }
15091   Rec.PossibleDerefs.clear();
15092 }
15093 
15094 /// Check whether E, which is either a discarded-value expression or an
15095 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15096 /// and if so, remove it from the list of volatile-qualified assignments that
15097 /// we are going to warn are deprecated.
15098 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15099   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15100     return;
15101 
15102   // Note: ignoring parens here is not justified by the standard rules, but
15103   // ignoring parentheses seems like a more reasonable approach, and this only
15104   // drives a deprecation warning so doesn't affect conformance.
15105   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15106     if (BO->getOpcode() == BO_Assign) {
15107       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15108       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15109                  LHSs.end());
15110     }
15111   }
15112 }
15113 
15114 void Sema::PopExpressionEvaluationContext() {
15115   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15116   unsigned NumTypos = Rec.NumTypos;
15117 
15118   if (!Rec.Lambdas.empty()) {
15119     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15120     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15121         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15122       unsigned D;
15123       if (Rec.isUnevaluated()) {
15124         // C++11 [expr.prim.lambda]p2:
15125         //   A lambda-expression shall not appear in an unevaluated operand
15126         //   (Clause 5).
15127         D = diag::err_lambda_unevaluated_operand;
15128       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15129         // C++1y [expr.const]p2:
15130         //   A conditional-expression e is a core constant expression unless the
15131         //   evaluation of e, following the rules of the abstract machine, would
15132         //   evaluate [...] a lambda-expression.
15133         D = diag::err_lambda_in_constant_expression;
15134       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15135         // C++17 [expr.prim.lamda]p2:
15136         // A lambda-expression shall not appear [...] in a template-argument.
15137         D = diag::err_lambda_in_invalid_context;
15138       } else
15139         llvm_unreachable("Couldn't infer lambda error message.");
15140 
15141       for (const auto *L : Rec.Lambdas)
15142         Diag(L->getBeginLoc(), D);
15143     }
15144   }
15145 
15146   WarnOnPendingNoDerefs(Rec);
15147 
15148   // Warn on any volatile-qualified simple-assignments that are not discarded-
15149   // value expressions nor unevaluated operands (those cases get removed from
15150   // this list by CheckUnusedVolatileAssignment).
15151   for (auto *BO : Rec.VolatileAssignmentLHSs)
15152     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15153         << BO->getType();
15154 
15155   // When are coming out of an unevaluated context, clear out any
15156   // temporaries that we may have created as part of the evaluation of
15157   // the expression in that context: they aren't relevant because they
15158   // will never be constructed.
15159   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15160     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15161                              ExprCleanupObjects.end());
15162     Cleanup = Rec.ParentCleanup;
15163     CleanupVarDeclMarking();
15164     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15165   // Otherwise, merge the contexts together.
15166   } else {
15167     Cleanup.mergeFrom(Rec.ParentCleanup);
15168     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15169                             Rec.SavedMaybeODRUseExprs.end());
15170   }
15171 
15172   // Pop the current expression evaluation context off the stack.
15173   ExprEvalContexts.pop_back();
15174 
15175   // The global expression evaluation context record is never popped.
15176   ExprEvalContexts.back().NumTypos += NumTypos;
15177 }
15178 
15179 void Sema::DiscardCleanupsInEvaluationContext() {
15180   ExprCleanupObjects.erase(
15181          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15182          ExprCleanupObjects.end());
15183   Cleanup.reset();
15184   MaybeODRUseExprs.clear();
15185 }
15186 
15187 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15188   ExprResult Result = CheckPlaceholderExpr(E);
15189   if (Result.isInvalid())
15190     return ExprError();
15191   E = Result.get();
15192   if (!E->getType()->isVariablyModifiedType())
15193     return E;
15194   return TransformToPotentiallyEvaluated(E);
15195 }
15196 
15197 /// Are we in a context that is potentially constant evaluated per C++20
15198 /// [expr.const]p12?
15199 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15200   /// C++2a [expr.const]p12:
15201   //   An expression or conversion is potentially constant evaluated if it is
15202   switch (SemaRef.ExprEvalContexts.back().Context) {
15203     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15204       // -- a manifestly constant-evaluated expression,
15205     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15206     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15207     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15208       // -- a potentially-evaluated expression,
15209     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15210       // -- an immediate subexpression of a braced-init-list,
15211 
15212       // -- [FIXME] an expression of the form & cast-expression that occurs
15213       //    within a templated entity
15214       // -- a subexpression of one of the above that is not a subexpression of
15215       // a nested unevaluated operand.
15216       return true;
15217 
15218     case Sema::ExpressionEvaluationContext::Unevaluated:
15219     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15220       // Expressions in this context are never evaluated.
15221       return false;
15222   }
15223   llvm_unreachable("Invalid context");
15224 }
15225 
15226 /// Return true if this function has a calling convention that requires mangling
15227 /// in the size of the parameter pack.
15228 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15229   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15230   // we don't need parameter type sizes.
15231   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15232   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15233                             TT.getArch() != llvm::Triple::x86_64))
15234     return false;
15235 
15236   // If this is C++ and this isn't an extern "C" function, parameters do not
15237   // need to be complete. In this case, C++ mangling will apply, which doesn't
15238   // use the size of the parameters.
15239   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15240     return false;
15241 
15242   // Stdcall, fastcall, and vectorcall need this special treatment.
15243   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15244   switch (CC) {
15245   case CC_X86StdCall:
15246   case CC_X86FastCall:
15247   case CC_X86VectorCall:
15248     return true;
15249   default:
15250     break;
15251   }
15252   return false;
15253 }
15254 
15255 /// Require that all of the parameter types of function be complete. Normally,
15256 /// parameter types are only required to be complete when a function is called
15257 /// or defined, but to mangle functions with certain calling conventions, the
15258 /// mangler needs to know the size of the parameter list. In this situation,
15259 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15260 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15261 /// result in a linker error. Clang doesn't implement this behavior, and instead
15262 /// attempts to error at compile time.
15263 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15264                                                   SourceLocation Loc) {
15265   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15266     FunctionDecl *FD;
15267     ParmVarDecl *Param;
15268 
15269   public:
15270     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15271         : FD(FD), Param(Param) {}
15272 
15273     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15274       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15275       StringRef CCName;
15276       switch (CC) {
15277       case CC_X86StdCall:
15278         CCName = "stdcall";
15279         break;
15280       case CC_X86FastCall:
15281         CCName = "fastcall";
15282         break;
15283       case CC_X86VectorCall:
15284         CCName = "vectorcall";
15285         break;
15286       default:
15287         llvm_unreachable("CC does not need mangling");
15288       }
15289 
15290       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15291           << Param->getDeclName() << FD->getDeclName() << CCName;
15292     }
15293   };
15294 
15295   for (ParmVarDecl *Param : FD->parameters()) {
15296     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15297     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15298   }
15299 }
15300 
15301 namespace {
15302 enum class OdrUseContext {
15303   /// Declarations in this context are not odr-used.
15304   None,
15305   /// Declarations in this context are formally odr-used, but this is a
15306   /// dependent context.
15307   Dependent,
15308   /// Declarations in this context are odr-used but not actually used (yet).
15309   FormallyOdrUsed,
15310   /// Declarations in this context are used.
15311   Used
15312 };
15313 }
15314 
15315 /// Are we within a context in which references to resolved functions or to
15316 /// variables result in odr-use?
15317 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15318   OdrUseContext Result;
15319 
15320   switch (SemaRef.ExprEvalContexts.back().Context) {
15321     case Sema::ExpressionEvaluationContext::Unevaluated:
15322     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15323     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15324       return OdrUseContext::None;
15325 
15326     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15327     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15328       Result = OdrUseContext::Used;
15329       break;
15330 
15331     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15332       Result = OdrUseContext::FormallyOdrUsed;
15333       break;
15334 
15335     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15336       // A default argument formally results in odr-use, but doesn't actually
15337       // result in a use in any real sense until it itself is used.
15338       Result = OdrUseContext::FormallyOdrUsed;
15339       break;
15340   }
15341 
15342   if (SemaRef.CurContext->isDependentContext())
15343     return OdrUseContext::Dependent;
15344 
15345   return Result;
15346 }
15347 
15348 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15349   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15350   return Func->isConstexpr() &&
15351          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15352 }
15353 
15354 /// Mark a function referenced, and check whether it is odr-used
15355 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15356 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15357                                   bool MightBeOdrUse) {
15358   assert(Func && "No function?");
15359 
15360   Func->setReferenced();
15361 
15362   // Recursive functions aren't really used until they're used from some other
15363   // context.
15364   bool IsRecursiveCall = CurContext == Func;
15365 
15366   // C++11 [basic.def.odr]p3:
15367   //   A function whose name appears as a potentially-evaluated expression is
15368   //   odr-used if it is the unique lookup result or the selected member of a
15369   //   set of overloaded functions [...].
15370   //
15371   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15372   // can just check that here.
15373   OdrUseContext OdrUse =
15374       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15375   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15376     OdrUse = OdrUseContext::FormallyOdrUsed;
15377 
15378   // Trivial default constructors and destructors are never actually used.
15379   // FIXME: What about other special members?
15380   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15381       OdrUse == OdrUseContext::Used) {
15382     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15383       if (Constructor->isDefaultConstructor())
15384         OdrUse = OdrUseContext::FormallyOdrUsed;
15385     if (isa<CXXDestructorDecl>(Func))
15386       OdrUse = OdrUseContext::FormallyOdrUsed;
15387   }
15388 
15389   // C++20 [expr.const]p12:
15390   //   A function [...] is needed for constant evaluation if it is [...] a
15391   //   constexpr function that is named by an expression that is potentially
15392   //   constant evaluated
15393   bool NeededForConstantEvaluation =
15394       isPotentiallyConstantEvaluatedContext(*this) &&
15395       isImplicitlyDefinableConstexprFunction(Func);
15396 
15397   // Determine whether we require a function definition to exist, per
15398   // C++11 [temp.inst]p3:
15399   //   Unless a function template specialization has been explicitly
15400   //   instantiated or explicitly specialized, the function template
15401   //   specialization is implicitly instantiated when the specialization is
15402   //   referenced in a context that requires a function definition to exist.
15403   // C++20 [temp.inst]p7:
15404   //   The existence of a definition of a [...] function is considered to
15405   //   affect the semantics of the program if the [...] function is needed for
15406   //   constant evaluation by an expression
15407   // C++20 [basic.def.odr]p10:
15408   //   Every program shall contain exactly one definition of every non-inline
15409   //   function or variable that is odr-used in that program outside of a
15410   //   discarded statement
15411   // C++20 [special]p1:
15412   //   The implementation will implicitly define [defaulted special members]
15413   //   if they are odr-used or needed for constant evaluation.
15414   //
15415   // Note that we skip the implicit instantiation of templates that are only
15416   // used in unused default arguments or by recursive calls to themselves.
15417   // This is formally non-conforming, but seems reasonable in practice.
15418   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15419                                              NeededForConstantEvaluation);
15420 
15421   // C++14 [temp.expl.spec]p6:
15422   //   If a template [...] is explicitly specialized then that specialization
15423   //   shall be declared before the first use of that specialization that would
15424   //   cause an implicit instantiation to take place, in every translation unit
15425   //   in which such a use occurs
15426   if (NeedDefinition &&
15427       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15428        Func->getMemberSpecializationInfo()))
15429     checkSpecializationVisibility(Loc, Func);
15430 
15431   // C++14 [except.spec]p17:
15432   //   An exception-specification is considered to be needed when:
15433   //   - the function is odr-used or, if it appears in an unevaluated operand,
15434   //     would be odr-used if the expression were potentially-evaluated;
15435   //
15436   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15437   // function is a pure virtual function we're calling, and in that case the
15438   // function was selected by overload resolution and we need to resolve its
15439   // exception specification for a different reason.
15440   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15441   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15442     ResolveExceptionSpec(Loc, FPT);
15443 
15444   if (getLangOpts().CUDA)
15445     CheckCUDACall(Loc, Func);
15446 
15447   // If we need a definition, try to create one.
15448   if (NeedDefinition && !Func->getBody()) {
15449     runWithSufficientStackSpace(Loc, [&] {
15450       if (CXXConstructorDecl *Constructor =
15451               dyn_cast<CXXConstructorDecl>(Func)) {
15452         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15453         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15454           if (Constructor->isDefaultConstructor()) {
15455             if (Constructor->isTrivial() &&
15456                 !Constructor->hasAttr<DLLExportAttr>())
15457               return;
15458             DefineImplicitDefaultConstructor(Loc, Constructor);
15459           } else if (Constructor->isCopyConstructor()) {
15460             DefineImplicitCopyConstructor(Loc, Constructor);
15461           } else if (Constructor->isMoveConstructor()) {
15462             DefineImplicitMoveConstructor(Loc, Constructor);
15463           }
15464         } else if (Constructor->getInheritedConstructor()) {
15465           DefineInheritingConstructor(Loc, Constructor);
15466         }
15467       } else if (CXXDestructorDecl *Destructor =
15468                      dyn_cast<CXXDestructorDecl>(Func)) {
15469         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15470         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15471           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15472             return;
15473           DefineImplicitDestructor(Loc, Destructor);
15474         }
15475         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15476           MarkVTableUsed(Loc, Destructor->getParent());
15477       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15478         if (MethodDecl->isOverloadedOperator() &&
15479             MethodDecl->getOverloadedOperator() == OO_Equal) {
15480           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15481           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15482             if (MethodDecl->isCopyAssignmentOperator())
15483               DefineImplicitCopyAssignment(Loc, MethodDecl);
15484             else if (MethodDecl->isMoveAssignmentOperator())
15485               DefineImplicitMoveAssignment(Loc, MethodDecl);
15486           }
15487         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15488                    MethodDecl->getParent()->isLambda()) {
15489           CXXConversionDecl *Conversion =
15490               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15491           if (Conversion->isLambdaToBlockPointerConversion())
15492             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15493           else
15494             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15495         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15496           MarkVTableUsed(Loc, MethodDecl->getParent());
15497       }
15498 
15499       // Implicit instantiation of function templates and member functions of
15500       // class templates.
15501       if (Func->isImplicitlyInstantiable()) {
15502         TemplateSpecializationKind TSK =
15503             Func->getTemplateSpecializationKindForInstantiation();
15504         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15505         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15506         if (FirstInstantiation) {
15507           PointOfInstantiation = Loc;
15508           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15509         } else if (TSK != TSK_ImplicitInstantiation) {
15510           // Use the point of use as the point of instantiation, instead of the
15511           // point of explicit instantiation (which we track as the actual point
15512           // of instantiation). This gives better backtraces in diagnostics.
15513           PointOfInstantiation = Loc;
15514         }
15515 
15516         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15517             Func->isConstexpr()) {
15518           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15519               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15520               CodeSynthesisContexts.size())
15521             PendingLocalImplicitInstantiations.push_back(
15522                 std::make_pair(Func, PointOfInstantiation));
15523           else if (Func->isConstexpr())
15524             // Do not defer instantiations of constexpr functions, to avoid the
15525             // expression evaluator needing to call back into Sema if it sees a
15526             // call to such a function.
15527             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15528           else {
15529             Func->setInstantiationIsPending(true);
15530             PendingInstantiations.push_back(
15531                 std::make_pair(Func, PointOfInstantiation));
15532             // Notify the consumer that a function was implicitly instantiated.
15533             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15534           }
15535         }
15536       } else {
15537         // Walk redefinitions, as some of them may be instantiable.
15538         for (auto i : Func->redecls()) {
15539           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15540             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15541         }
15542       }
15543     });
15544   }
15545 
15546   // If this is the first "real" use, act on that.
15547   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15548     // Keep track of used but undefined functions.
15549     if (!Func->isDefined()) {
15550       if (mightHaveNonExternalLinkage(Func))
15551         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15552       else if (Func->getMostRecentDecl()->isInlined() &&
15553                !LangOpts.GNUInline &&
15554                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15555         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15556       else if (isExternalWithNoLinkageType(Func))
15557         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15558     }
15559 
15560     // Some x86 Windows calling conventions mangle the size of the parameter
15561     // pack into the name. Computing the size of the parameters requires the
15562     // parameter types to be complete. Check that now.
15563     if (funcHasParameterSizeMangling(*this, Func))
15564       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15565 
15566     Func->markUsed(Context);
15567   }
15568 
15569   if (LangOpts.OpenMP) {
15570     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15571     if (LangOpts.OpenMPIsDevice)
15572       checkOpenMPDeviceFunction(Loc, Func);
15573     else
15574       checkOpenMPHostFunction(Loc, Func);
15575   }
15576 }
15577 
15578 /// Directly mark a variable odr-used. Given a choice, prefer to use
15579 /// MarkVariableReferenced since it does additional checks and then
15580 /// calls MarkVarDeclODRUsed.
15581 /// If the variable must be captured:
15582 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15583 ///  - else capture it in the DeclContext that maps to the
15584 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15585 static void
15586 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15587                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15588   // Keep track of used but undefined variables.
15589   // FIXME: We shouldn't suppress this warning for static data members.
15590   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15591       (!Var->isExternallyVisible() || Var->isInline() ||
15592        SemaRef.isExternalWithNoLinkageType(Var)) &&
15593       !(Var->isStaticDataMember() && Var->hasInit())) {
15594     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15595     if (old.isInvalid())
15596       old = Loc;
15597   }
15598   QualType CaptureType, DeclRefType;
15599   if (SemaRef.LangOpts.OpenMP)
15600     SemaRef.tryCaptureOpenMPLambdas(Var);
15601   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15602     /*EllipsisLoc*/ SourceLocation(),
15603     /*BuildAndDiagnose*/ true,
15604     CaptureType, DeclRefType,
15605     FunctionScopeIndexToStopAt);
15606 
15607   Var->markUsed(SemaRef.Context);
15608 }
15609 
15610 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15611                                              SourceLocation Loc,
15612                                              unsigned CapturingScopeIndex) {
15613   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15614 }
15615 
15616 static void
15617 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15618                                    ValueDecl *var, DeclContext *DC) {
15619   DeclContext *VarDC = var->getDeclContext();
15620 
15621   //  If the parameter still belongs to the translation unit, then
15622   //  we're actually just using one parameter in the declaration of
15623   //  the next.
15624   if (isa<ParmVarDecl>(var) &&
15625       isa<TranslationUnitDecl>(VarDC))
15626     return;
15627 
15628   // For C code, don't diagnose about capture if we're not actually in code
15629   // right now; it's impossible to write a non-constant expression outside of
15630   // function context, so we'll get other (more useful) diagnostics later.
15631   //
15632   // For C++, things get a bit more nasty... it would be nice to suppress this
15633   // diagnostic for certain cases like using a local variable in an array bound
15634   // for a member of a local class, but the correct predicate is not obvious.
15635   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15636     return;
15637 
15638   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15639   unsigned ContextKind = 3; // unknown
15640   if (isa<CXXMethodDecl>(VarDC) &&
15641       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15642     ContextKind = 2;
15643   } else if (isa<FunctionDecl>(VarDC)) {
15644     ContextKind = 0;
15645   } else if (isa<BlockDecl>(VarDC)) {
15646     ContextKind = 1;
15647   }
15648 
15649   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15650     << var << ValueKind << ContextKind << VarDC;
15651   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15652       << var;
15653 
15654   // FIXME: Add additional diagnostic info about class etc. which prevents
15655   // capture.
15656 }
15657 
15658 
15659 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15660                                       bool &SubCapturesAreNested,
15661                                       QualType &CaptureType,
15662                                       QualType &DeclRefType) {
15663    // Check whether we've already captured it.
15664   if (CSI->CaptureMap.count(Var)) {
15665     // If we found a capture, any subcaptures are nested.
15666     SubCapturesAreNested = true;
15667 
15668     // Retrieve the capture type for this variable.
15669     CaptureType = CSI->getCapture(Var).getCaptureType();
15670 
15671     // Compute the type of an expression that refers to this variable.
15672     DeclRefType = CaptureType.getNonReferenceType();
15673 
15674     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15675     // are mutable in the sense that user can change their value - they are
15676     // private instances of the captured declarations.
15677     const Capture &Cap = CSI->getCapture(Var);
15678     if (Cap.isCopyCapture() &&
15679         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15680         !(isa<CapturedRegionScopeInfo>(CSI) &&
15681           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15682       DeclRefType.addConst();
15683     return true;
15684   }
15685   return false;
15686 }
15687 
15688 // Only block literals, captured statements, and lambda expressions can
15689 // capture; other scopes don't work.
15690 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15691                                  SourceLocation Loc,
15692                                  const bool Diagnose, Sema &S) {
15693   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15694     return getLambdaAwareParentOfDeclContext(DC);
15695   else if (Var->hasLocalStorage()) {
15696     if (Diagnose)
15697        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15698   }
15699   return nullptr;
15700 }
15701 
15702 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15703 // certain types of variables (unnamed, variably modified types etc.)
15704 // so check for eligibility.
15705 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15706                                  SourceLocation Loc,
15707                                  const bool Diagnose, Sema &S) {
15708 
15709   bool IsBlock = isa<BlockScopeInfo>(CSI);
15710   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15711 
15712   // Lambdas are not allowed to capture unnamed variables
15713   // (e.g. anonymous unions).
15714   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15715   // assuming that's the intent.
15716   if (IsLambda && !Var->getDeclName()) {
15717     if (Diagnose) {
15718       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15719       S.Diag(Var->getLocation(), diag::note_declared_at);
15720     }
15721     return false;
15722   }
15723 
15724   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15725   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15726     if (Diagnose) {
15727       S.Diag(Loc, diag::err_ref_vm_type);
15728       S.Diag(Var->getLocation(), diag::note_previous_decl)
15729         << Var->getDeclName();
15730     }
15731     return false;
15732   }
15733   // Prohibit structs with flexible array members too.
15734   // We cannot capture what is in the tail end of the struct.
15735   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15736     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15737       if (Diagnose) {
15738         if (IsBlock)
15739           S.Diag(Loc, diag::err_ref_flexarray_type);
15740         else
15741           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15742             << Var->getDeclName();
15743         S.Diag(Var->getLocation(), diag::note_previous_decl)
15744           << Var->getDeclName();
15745       }
15746       return false;
15747     }
15748   }
15749   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15750   // Lambdas and captured statements are not allowed to capture __block
15751   // variables; they don't support the expected semantics.
15752   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15753     if (Diagnose) {
15754       S.Diag(Loc, diag::err_capture_block_variable)
15755         << Var->getDeclName() << !IsLambda;
15756       S.Diag(Var->getLocation(), diag::note_previous_decl)
15757         << Var->getDeclName();
15758     }
15759     return false;
15760   }
15761   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15762   if (S.getLangOpts().OpenCL && IsBlock &&
15763       Var->getType()->isBlockPointerType()) {
15764     if (Diagnose)
15765       S.Diag(Loc, diag::err_opencl_block_ref_block);
15766     return false;
15767   }
15768 
15769   return true;
15770 }
15771 
15772 // Returns true if the capture by block was successful.
15773 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15774                                  SourceLocation Loc,
15775                                  const bool BuildAndDiagnose,
15776                                  QualType &CaptureType,
15777                                  QualType &DeclRefType,
15778                                  const bool Nested,
15779                                  Sema &S, bool Invalid) {
15780   bool ByRef = false;
15781 
15782   // Blocks are not allowed to capture arrays, excepting OpenCL.
15783   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15784   // (decayed to pointers).
15785   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15786     if (BuildAndDiagnose) {
15787       S.Diag(Loc, diag::err_ref_array_type);
15788       S.Diag(Var->getLocation(), diag::note_previous_decl)
15789       << Var->getDeclName();
15790       Invalid = true;
15791     } else {
15792       return false;
15793     }
15794   }
15795 
15796   // Forbid the block-capture of autoreleasing variables.
15797   if (!Invalid &&
15798       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15799     if (BuildAndDiagnose) {
15800       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15801         << /*block*/ 0;
15802       S.Diag(Var->getLocation(), diag::note_previous_decl)
15803         << Var->getDeclName();
15804       Invalid = true;
15805     } else {
15806       return false;
15807     }
15808   }
15809 
15810   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15811   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15812     QualType PointeeTy = PT->getPointeeType();
15813 
15814     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15815         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15816         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15817       if (BuildAndDiagnose) {
15818         SourceLocation VarLoc = Var->getLocation();
15819         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15820         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15821       }
15822     }
15823   }
15824 
15825   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15826   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15827       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15828     // Block capture by reference does not change the capture or
15829     // declaration reference types.
15830     ByRef = true;
15831   } else {
15832     // Block capture by copy introduces 'const'.
15833     CaptureType = CaptureType.getNonReferenceType().withConst();
15834     DeclRefType = CaptureType;
15835   }
15836 
15837   // Actually capture the variable.
15838   if (BuildAndDiagnose)
15839     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15840                     CaptureType, Invalid);
15841 
15842   return !Invalid;
15843 }
15844 
15845 
15846 /// Capture the given variable in the captured region.
15847 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15848                                     VarDecl *Var,
15849                                     SourceLocation Loc,
15850                                     const bool BuildAndDiagnose,
15851                                     QualType &CaptureType,
15852                                     QualType &DeclRefType,
15853                                     const bool RefersToCapturedVariable,
15854                                     Sema &S, bool Invalid) {
15855   // By default, capture variables by reference.
15856   bool ByRef = true;
15857   // Using an LValue reference type is consistent with Lambdas (see below).
15858   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15859     if (S.isOpenMPCapturedDecl(Var)) {
15860       bool HasConst = DeclRefType.isConstQualified();
15861       DeclRefType = DeclRefType.getUnqualifiedType();
15862       // Don't lose diagnostics about assignments to const.
15863       if (HasConst)
15864         DeclRefType.addConst();
15865     }
15866     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15867                                     RSI->OpenMPCaptureLevel);
15868   }
15869 
15870   if (ByRef)
15871     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15872   else
15873     CaptureType = DeclRefType;
15874 
15875   // Actually capture the variable.
15876   if (BuildAndDiagnose)
15877     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15878                     Loc, SourceLocation(), CaptureType, Invalid);
15879 
15880   return !Invalid;
15881 }
15882 
15883 /// Capture the given variable in the lambda.
15884 static bool captureInLambda(LambdaScopeInfo *LSI,
15885                             VarDecl *Var,
15886                             SourceLocation Loc,
15887                             const bool BuildAndDiagnose,
15888                             QualType &CaptureType,
15889                             QualType &DeclRefType,
15890                             const bool RefersToCapturedVariable,
15891                             const Sema::TryCaptureKind Kind,
15892                             SourceLocation EllipsisLoc,
15893                             const bool IsTopScope,
15894                             Sema &S, bool Invalid) {
15895   // Determine whether we are capturing by reference or by value.
15896   bool ByRef = false;
15897   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15898     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15899   } else {
15900     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15901   }
15902 
15903   // Compute the type of the field that will capture this variable.
15904   if (ByRef) {
15905     // C++11 [expr.prim.lambda]p15:
15906     //   An entity is captured by reference if it is implicitly or
15907     //   explicitly captured but not captured by copy. It is
15908     //   unspecified whether additional unnamed non-static data
15909     //   members are declared in the closure type for entities
15910     //   captured by reference.
15911     //
15912     // FIXME: It is not clear whether we want to build an lvalue reference
15913     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15914     // to do the former, while EDG does the latter. Core issue 1249 will
15915     // clarify, but for now we follow GCC because it's a more permissive and
15916     // easily defensible position.
15917     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15918   } else {
15919     // C++11 [expr.prim.lambda]p14:
15920     //   For each entity captured by copy, an unnamed non-static
15921     //   data member is declared in the closure type. The
15922     //   declaration order of these members is unspecified. The type
15923     //   of such a data member is the type of the corresponding
15924     //   captured entity if the entity is not a reference to an
15925     //   object, or the referenced type otherwise. [Note: If the
15926     //   captured entity is a reference to a function, the
15927     //   corresponding data member is also a reference to a
15928     //   function. - end note ]
15929     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15930       if (!RefType->getPointeeType()->isFunctionType())
15931         CaptureType = RefType->getPointeeType();
15932     }
15933 
15934     // Forbid the lambda copy-capture of autoreleasing variables.
15935     if (!Invalid &&
15936         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15937       if (BuildAndDiagnose) {
15938         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15939         S.Diag(Var->getLocation(), diag::note_previous_decl)
15940           << Var->getDeclName();
15941         Invalid = true;
15942       } else {
15943         return false;
15944       }
15945     }
15946 
15947     // Make sure that by-copy captures are of a complete and non-abstract type.
15948     if (!Invalid && BuildAndDiagnose) {
15949       if (!CaptureType->isDependentType() &&
15950           S.RequireCompleteType(Loc, CaptureType,
15951                                 diag::err_capture_of_incomplete_type,
15952                                 Var->getDeclName()))
15953         Invalid = true;
15954       else if (S.RequireNonAbstractType(Loc, CaptureType,
15955                                         diag::err_capture_of_abstract_type))
15956         Invalid = true;
15957     }
15958   }
15959 
15960   // Compute the type of a reference to this captured variable.
15961   if (ByRef)
15962     DeclRefType = CaptureType.getNonReferenceType();
15963   else {
15964     // C++ [expr.prim.lambda]p5:
15965     //   The closure type for a lambda-expression has a public inline
15966     //   function call operator [...]. This function call operator is
15967     //   declared const (9.3.1) if and only if the lambda-expression's
15968     //   parameter-declaration-clause is not followed by mutable.
15969     DeclRefType = CaptureType.getNonReferenceType();
15970     if (!LSI->Mutable && !CaptureType->isReferenceType())
15971       DeclRefType.addConst();
15972   }
15973 
15974   // Add the capture.
15975   if (BuildAndDiagnose)
15976     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15977                     Loc, EllipsisLoc, CaptureType, Invalid);
15978 
15979   return !Invalid;
15980 }
15981 
15982 bool Sema::tryCaptureVariable(
15983     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15984     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15985     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15986   // An init-capture is notionally from the context surrounding its
15987   // declaration, but its parent DC is the lambda class.
15988   DeclContext *VarDC = Var->getDeclContext();
15989   if (Var->isInitCapture())
15990     VarDC = VarDC->getParent();
15991 
15992   DeclContext *DC = CurContext;
15993   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15994       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15995   // We need to sync up the Declaration Context with the
15996   // FunctionScopeIndexToStopAt
15997   if (FunctionScopeIndexToStopAt) {
15998     unsigned FSIndex = FunctionScopes.size() - 1;
15999     while (FSIndex != MaxFunctionScopesIndex) {
16000       DC = getLambdaAwareParentOfDeclContext(DC);
16001       --FSIndex;
16002     }
16003   }
16004 
16005 
16006   // If the variable is declared in the current context, there is no need to
16007   // capture it.
16008   if (VarDC == DC) return true;
16009 
16010   // Capture global variables if it is required to use private copy of this
16011   // variable.
16012   bool IsGlobal = !Var->hasLocalStorage();
16013   if (IsGlobal &&
16014       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16015                                                 MaxFunctionScopesIndex)))
16016     return true;
16017   Var = Var->getCanonicalDecl();
16018 
16019   // Walk up the stack to determine whether we can capture the variable,
16020   // performing the "simple" checks that don't depend on type. We stop when
16021   // we've either hit the declared scope of the variable or find an existing
16022   // capture of that variable.  We start from the innermost capturing-entity
16023   // (the DC) and ensure that all intervening capturing-entities
16024   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16025   // declcontext can either capture the variable or have already captured
16026   // the variable.
16027   CaptureType = Var->getType();
16028   DeclRefType = CaptureType.getNonReferenceType();
16029   bool Nested = false;
16030   bool Explicit = (Kind != TryCapture_Implicit);
16031   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16032   do {
16033     // Only block literals, captured statements, and lambda expressions can
16034     // capture; other scopes don't work.
16035     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16036                                                               ExprLoc,
16037                                                               BuildAndDiagnose,
16038                                                               *this);
16039     // We need to check for the parent *first* because, if we *have*
16040     // private-captured a global variable, we need to recursively capture it in
16041     // intermediate blocks, lambdas, etc.
16042     if (!ParentDC) {
16043       if (IsGlobal) {
16044         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16045         break;
16046       }
16047       return true;
16048     }
16049 
16050     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16051     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16052 
16053 
16054     // Check whether we've already captured it.
16055     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16056                                              DeclRefType)) {
16057       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16058       break;
16059     }
16060     // If we are instantiating a generic lambda call operator body,
16061     // we do not want to capture new variables.  What was captured
16062     // during either a lambdas transformation or initial parsing
16063     // should be used.
16064     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16065       if (BuildAndDiagnose) {
16066         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16067         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16068           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16069           Diag(Var->getLocation(), diag::note_previous_decl)
16070              << Var->getDeclName();
16071           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16072         } else
16073           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16074       }
16075       return true;
16076     }
16077 
16078     // Try to capture variable-length arrays types.
16079     if (Var->getType()->isVariablyModifiedType()) {
16080       // We're going to walk down into the type and look for VLA
16081       // expressions.
16082       QualType QTy = Var->getType();
16083       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16084         QTy = PVD->getOriginalType();
16085       captureVariablyModifiedType(Context, QTy, CSI);
16086     }
16087 
16088     if (getLangOpts().OpenMP) {
16089       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16090         // OpenMP private variables should not be captured in outer scope, so
16091         // just break here. Similarly, global variables that are captured in a
16092         // target region should not be captured outside the scope of the region.
16093         if (RSI->CapRegionKind == CR_OpenMP) {
16094           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16095           auto IsTargetCap = !IsOpenMPPrivateDecl &&
16096                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16097           // When we detect target captures we are looking from inside the
16098           // target region, therefore we need to propagate the capture from the
16099           // enclosing region. Therefore, the capture is not initially nested.
16100           if (IsTargetCap)
16101             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16102 
16103           if (IsTargetCap || IsOpenMPPrivateDecl) {
16104             Nested = !IsTargetCap;
16105             DeclRefType = DeclRefType.getUnqualifiedType();
16106             CaptureType = Context.getLValueReferenceType(DeclRefType);
16107             break;
16108           }
16109         }
16110       }
16111     }
16112     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16113       // No capture-default, and this is not an explicit capture
16114       // so cannot capture this variable.
16115       if (BuildAndDiagnose) {
16116         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16117         Diag(Var->getLocation(), diag::note_previous_decl)
16118           << Var->getDeclName();
16119         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16120           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16121                diag::note_lambda_decl);
16122         // FIXME: If we error out because an outer lambda can not implicitly
16123         // capture a variable that an inner lambda explicitly captures, we
16124         // should have the inner lambda do the explicit capture - because
16125         // it makes for cleaner diagnostics later.  This would purely be done
16126         // so that the diagnostic does not misleadingly claim that a variable
16127         // can not be captured by a lambda implicitly even though it is captured
16128         // explicitly.  Suggestion:
16129         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16130         //    at the function head
16131         //  - cache the StartingDeclContext - this must be a lambda
16132         //  - captureInLambda in the innermost lambda the variable.
16133       }
16134       return true;
16135     }
16136 
16137     FunctionScopesIndex--;
16138     DC = ParentDC;
16139     Explicit = false;
16140   } while (!VarDC->Equals(DC));
16141 
16142   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16143   // computing the type of the capture at each step, checking type-specific
16144   // requirements, and adding captures if requested.
16145   // If the variable had already been captured previously, we start capturing
16146   // at the lambda nested within that one.
16147   bool Invalid = false;
16148   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16149        ++I) {
16150     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16151 
16152     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16153     // certain types of variables (unnamed, variably modified types etc.)
16154     // so check for eligibility.
16155     if (!Invalid)
16156       Invalid =
16157           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16158 
16159     // After encountering an error, if we're actually supposed to capture, keep
16160     // capturing in nested contexts to suppress any follow-on diagnostics.
16161     if (Invalid && !BuildAndDiagnose)
16162       return true;
16163 
16164     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16165       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16166                                DeclRefType, Nested, *this, Invalid);
16167       Nested = true;
16168     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16169       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16170                                          CaptureType, DeclRefType, Nested,
16171                                          *this, Invalid);
16172       Nested = true;
16173     } else {
16174       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16175       Invalid =
16176           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16177                            DeclRefType, Nested, Kind, EllipsisLoc,
16178                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16179       Nested = true;
16180     }
16181 
16182     if (Invalid && !BuildAndDiagnose)
16183       return true;
16184   }
16185   return Invalid;
16186 }
16187 
16188 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16189                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16190   QualType CaptureType;
16191   QualType DeclRefType;
16192   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16193                             /*BuildAndDiagnose=*/true, CaptureType,
16194                             DeclRefType, nullptr);
16195 }
16196 
16197 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16198   QualType CaptureType;
16199   QualType DeclRefType;
16200   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16201                              /*BuildAndDiagnose=*/false, CaptureType,
16202                              DeclRefType, nullptr);
16203 }
16204 
16205 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16206   QualType CaptureType;
16207   QualType DeclRefType;
16208 
16209   // Determine whether we can capture this variable.
16210   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16211                          /*BuildAndDiagnose=*/false, CaptureType,
16212                          DeclRefType, nullptr))
16213     return QualType();
16214 
16215   return DeclRefType;
16216 }
16217 
16218 namespace {
16219 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16220 // The produced TemplateArgumentListInfo* points to data stored within this
16221 // object, so should only be used in contexts where the pointer will not be
16222 // used after the CopiedTemplateArgs object is destroyed.
16223 class CopiedTemplateArgs {
16224   bool HasArgs;
16225   TemplateArgumentListInfo TemplateArgStorage;
16226 public:
16227   template<typename RefExpr>
16228   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16229     if (HasArgs)
16230       E->copyTemplateArgumentsInto(TemplateArgStorage);
16231   }
16232   operator TemplateArgumentListInfo*()
16233 #ifdef __has_cpp_attribute
16234 #if __has_cpp_attribute(clang::lifetimebound)
16235   [[clang::lifetimebound]]
16236 #endif
16237 #endif
16238   {
16239     return HasArgs ? &TemplateArgStorage : nullptr;
16240   }
16241 };
16242 }
16243 
16244 /// Walk the set of potential results of an expression and mark them all as
16245 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16246 ///
16247 /// \return A new expression if we found any potential results, ExprEmpty() if
16248 ///         not, and ExprError() if we diagnosed an error.
16249 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16250                                                       NonOdrUseReason NOUR) {
16251   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16252   // an object that satisfies the requirements for appearing in a
16253   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16254   // is immediately applied."  This function handles the lvalue-to-rvalue
16255   // conversion part.
16256   //
16257   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16258   // transform it into the relevant kind of non-odr-use node and rebuild the
16259   // tree of nodes leading to it.
16260   //
16261   // This is a mini-TreeTransform that only transforms a restricted subset of
16262   // nodes (and only certain operands of them).
16263 
16264   // Rebuild a subexpression.
16265   auto Rebuild = [&](Expr *Sub) {
16266     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16267   };
16268 
16269   // Check whether a potential result satisfies the requirements of NOUR.
16270   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16271     // Any entity other than a VarDecl is always odr-used whenever it's named
16272     // in a potentially-evaluated expression.
16273     auto *VD = dyn_cast<VarDecl>(D);
16274     if (!VD)
16275       return true;
16276 
16277     // C++2a [basic.def.odr]p4:
16278     //   A variable x whose name appears as a potentially-evalauted expression
16279     //   e is odr-used by e unless
16280     //   -- x is a reference that is usable in constant expressions, or
16281     //   -- x is a variable of non-reference type that is usable in constant
16282     //      expressions and has no mutable subobjects, and e is an element of
16283     //      the set of potential results of an expression of
16284     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16285     //      conversion is applied, or
16286     //   -- x is a variable of non-reference type, and e is an element of the
16287     //      set of potential results of a discarded-value expression to which
16288     //      the lvalue-to-rvalue conversion is not applied
16289     //
16290     // We check the first bullet and the "potentially-evaluated" condition in
16291     // BuildDeclRefExpr. We check the type requirements in the second bullet
16292     // in CheckLValueToRValueConversionOperand below.
16293     switch (NOUR) {
16294     case NOUR_None:
16295     case NOUR_Unevaluated:
16296       llvm_unreachable("unexpected non-odr-use-reason");
16297 
16298     case NOUR_Constant:
16299       // Constant references were handled when they were built.
16300       if (VD->getType()->isReferenceType())
16301         return true;
16302       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16303         if (RD->hasMutableFields())
16304           return true;
16305       if (!VD->isUsableInConstantExpressions(S.Context))
16306         return true;
16307       break;
16308 
16309     case NOUR_Discarded:
16310       if (VD->getType()->isReferenceType())
16311         return true;
16312       break;
16313     }
16314     return false;
16315   };
16316 
16317   // Mark that this expression does not constitute an odr-use.
16318   auto MarkNotOdrUsed = [&] {
16319     S.MaybeODRUseExprs.erase(E);
16320     if (LambdaScopeInfo *LSI = S.getCurLambda())
16321       LSI->markVariableExprAsNonODRUsed(E);
16322   };
16323 
16324   // C++2a [basic.def.odr]p2:
16325   //   The set of potential results of an expression e is defined as follows:
16326   switch (E->getStmtClass()) {
16327   //   -- If e is an id-expression, ...
16328   case Expr::DeclRefExprClass: {
16329     auto *DRE = cast<DeclRefExpr>(E);
16330     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16331       break;
16332 
16333     // Rebuild as a non-odr-use DeclRefExpr.
16334     MarkNotOdrUsed();
16335     return DeclRefExpr::Create(
16336         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16337         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16338         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16339         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16340   }
16341 
16342   case Expr::FunctionParmPackExprClass: {
16343     auto *FPPE = cast<FunctionParmPackExpr>(E);
16344     // If any of the declarations in the pack is odr-used, then the expression
16345     // as a whole constitutes an odr-use.
16346     for (VarDecl *D : *FPPE)
16347       if (IsPotentialResultOdrUsed(D))
16348         return ExprEmpty();
16349 
16350     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16351     // nothing cares about whether we marked this as an odr-use, but it might
16352     // be useful for non-compiler tools.
16353     MarkNotOdrUsed();
16354     break;
16355   }
16356 
16357   //   -- If e is a subscripting operation with an array operand...
16358   case Expr::ArraySubscriptExprClass: {
16359     auto *ASE = cast<ArraySubscriptExpr>(E);
16360     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16361     if (!OldBase->getType()->isArrayType())
16362       break;
16363     ExprResult Base = Rebuild(OldBase);
16364     if (!Base.isUsable())
16365       return Base;
16366     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16367     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16368     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16369     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16370                                      ASE->getRBracketLoc());
16371   }
16372 
16373   case Expr::MemberExprClass: {
16374     auto *ME = cast<MemberExpr>(E);
16375     // -- If e is a class member access expression [...] naming a non-static
16376     //    data member...
16377     if (isa<FieldDecl>(ME->getMemberDecl())) {
16378       ExprResult Base = Rebuild(ME->getBase());
16379       if (!Base.isUsable())
16380         return Base;
16381       return MemberExpr::Create(
16382           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16383           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16384           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16385           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16386           ME->getObjectKind(), ME->isNonOdrUse());
16387     }
16388 
16389     if (ME->getMemberDecl()->isCXXInstanceMember())
16390       break;
16391 
16392     // -- If e is a class member access expression naming a static data member,
16393     //    ...
16394     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16395       break;
16396 
16397     // Rebuild as a non-odr-use MemberExpr.
16398     MarkNotOdrUsed();
16399     return MemberExpr::Create(
16400         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16401         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16402         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16403         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16404     return ExprEmpty();
16405   }
16406 
16407   case Expr::BinaryOperatorClass: {
16408     auto *BO = cast<BinaryOperator>(E);
16409     Expr *LHS = BO->getLHS();
16410     Expr *RHS = BO->getRHS();
16411     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16412     if (BO->getOpcode() == BO_PtrMemD) {
16413       ExprResult Sub = Rebuild(LHS);
16414       if (!Sub.isUsable())
16415         return Sub;
16416       LHS = Sub.get();
16417     //   -- If e is a comma expression, ...
16418     } else if (BO->getOpcode() == BO_Comma) {
16419       ExprResult Sub = Rebuild(RHS);
16420       if (!Sub.isUsable())
16421         return Sub;
16422       RHS = Sub.get();
16423     } else {
16424       break;
16425     }
16426     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16427                         LHS, RHS);
16428   }
16429 
16430   //   -- If e has the form (e1)...
16431   case Expr::ParenExprClass: {
16432     auto *PE = cast<ParenExpr>(E);
16433     ExprResult Sub = Rebuild(PE->getSubExpr());
16434     if (!Sub.isUsable())
16435       return Sub;
16436     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16437   }
16438 
16439   //   -- If e is a glvalue conditional expression, ...
16440   // We don't apply this to a binary conditional operator. FIXME: Should we?
16441   case Expr::ConditionalOperatorClass: {
16442     auto *CO = cast<ConditionalOperator>(E);
16443     ExprResult LHS = Rebuild(CO->getLHS());
16444     if (LHS.isInvalid())
16445       return ExprError();
16446     ExprResult RHS = Rebuild(CO->getRHS());
16447     if (RHS.isInvalid())
16448       return ExprError();
16449     if (!LHS.isUsable() && !RHS.isUsable())
16450       return ExprEmpty();
16451     if (!LHS.isUsable())
16452       LHS = CO->getLHS();
16453     if (!RHS.isUsable())
16454       RHS = CO->getRHS();
16455     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16456                                 CO->getCond(), LHS.get(), RHS.get());
16457   }
16458 
16459   // [Clang extension]
16460   //   -- If e has the form __extension__ e1...
16461   case Expr::UnaryOperatorClass: {
16462     auto *UO = cast<UnaryOperator>(E);
16463     if (UO->getOpcode() != UO_Extension)
16464       break;
16465     ExprResult Sub = Rebuild(UO->getSubExpr());
16466     if (!Sub.isUsable())
16467       return Sub;
16468     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16469                           Sub.get());
16470   }
16471 
16472   // [Clang extension]
16473   //   -- If e has the form _Generic(...), the set of potential results is the
16474   //      union of the sets of potential results of the associated expressions.
16475   case Expr::GenericSelectionExprClass: {
16476     auto *GSE = cast<GenericSelectionExpr>(E);
16477 
16478     SmallVector<Expr *, 4> AssocExprs;
16479     bool AnyChanged = false;
16480     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16481       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16482       if (AssocExpr.isInvalid())
16483         return ExprError();
16484       if (AssocExpr.isUsable()) {
16485         AssocExprs.push_back(AssocExpr.get());
16486         AnyChanged = true;
16487       } else {
16488         AssocExprs.push_back(OrigAssocExpr);
16489       }
16490     }
16491 
16492     return AnyChanged ? S.CreateGenericSelectionExpr(
16493                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16494                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16495                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16496                       : ExprEmpty();
16497   }
16498 
16499   // [Clang extension]
16500   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16501   //      results is the union of the sets of potential results of the
16502   //      second and third subexpressions.
16503   case Expr::ChooseExprClass: {
16504     auto *CE = cast<ChooseExpr>(E);
16505 
16506     ExprResult LHS = Rebuild(CE->getLHS());
16507     if (LHS.isInvalid())
16508       return ExprError();
16509 
16510     ExprResult RHS = Rebuild(CE->getLHS());
16511     if (RHS.isInvalid())
16512       return ExprError();
16513 
16514     if (!LHS.get() && !RHS.get())
16515       return ExprEmpty();
16516     if (!LHS.isUsable())
16517       LHS = CE->getLHS();
16518     if (!RHS.isUsable())
16519       RHS = CE->getRHS();
16520 
16521     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16522                              RHS.get(), CE->getRParenLoc());
16523   }
16524 
16525   // Step through non-syntactic nodes.
16526   case Expr::ConstantExprClass: {
16527     auto *CE = cast<ConstantExpr>(E);
16528     ExprResult Sub = Rebuild(CE->getSubExpr());
16529     if (!Sub.isUsable())
16530       return Sub;
16531     return ConstantExpr::Create(S.Context, Sub.get());
16532   }
16533 
16534   // We could mostly rely on the recursive rebuilding to rebuild implicit
16535   // casts, but not at the top level, so rebuild them here.
16536   case Expr::ImplicitCastExprClass: {
16537     auto *ICE = cast<ImplicitCastExpr>(E);
16538     // Only step through the narrow set of cast kinds we expect to encounter.
16539     // Anything else suggests we've left the region in which potential results
16540     // can be found.
16541     switch (ICE->getCastKind()) {
16542     case CK_NoOp:
16543     case CK_DerivedToBase:
16544     case CK_UncheckedDerivedToBase: {
16545       ExprResult Sub = Rebuild(ICE->getSubExpr());
16546       if (!Sub.isUsable())
16547         return Sub;
16548       CXXCastPath Path(ICE->path());
16549       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16550                                  ICE->getValueKind(), &Path);
16551     }
16552 
16553     default:
16554       break;
16555     }
16556     break;
16557   }
16558 
16559   default:
16560     break;
16561   }
16562 
16563   // Can't traverse through this node. Nothing to do.
16564   return ExprEmpty();
16565 }
16566 
16567 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16568   // Check whether the operand is or contains an object of non-trivial C union
16569   // type.
16570   if (E->getType().isVolatileQualified() &&
16571       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16572        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16573     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16574                           Sema::NTCUC_LValueToRValueVolatile,
16575                           NTCUK_Destruct|NTCUK_Copy);
16576 
16577   // C++2a [basic.def.odr]p4:
16578   //   [...] an expression of non-volatile-qualified non-class type to which
16579   //   the lvalue-to-rvalue conversion is applied [...]
16580   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16581     return E;
16582 
16583   ExprResult Result =
16584       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16585   if (Result.isInvalid())
16586     return ExprError();
16587   return Result.get() ? Result : E;
16588 }
16589 
16590 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16591   Res = CorrectDelayedTyposInExpr(Res);
16592 
16593   if (!Res.isUsable())
16594     return Res;
16595 
16596   // If a constant-expression is a reference to a variable where we delay
16597   // deciding whether it is an odr-use, just assume we will apply the
16598   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16599   // (a non-type template argument), we have special handling anyway.
16600   return CheckLValueToRValueConversionOperand(Res.get());
16601 }
16602 
16603 void Sema::CleanupVarDeclMarking() {
16604   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16605   // call.
16606   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16607   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16608 
16609   for (Expr *E : LocalMaybeODRUseExprs) {
16610     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16611       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16612                          DRE->getLocation(), *this);
16613     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16614       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16615                          *this);
16616     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16617       for (VarDecl *VD : *FP)
16618         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16619     } else {
16620       llvm_unreachable("Unexpected expression");
16621     }
16622   }
16623 
16624   assert(MaybeODRUseExprs.empty() &&
16625          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16626 }
16627 
16628 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16629                                     VarDecl *Var, Expr *E) {
16630   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16631           isa<FunctionParmPackExpr>(E)) &&
16632          "Invalid Expr argument to DoMarkVarDeclReferenced");
16633   Var->setReferenced();
16634 
16635   if (Var->isInvalidDecl())
16636     return;
16637 
16638   auto *MSI = Var->getMemberSpecializationInfo();
16639   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16640                                        : Var->getTemplateSpecializationKind();
16641 
16642   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16643   bool UsableInConstantExpr =
16644       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16645 
16646   // C++20 [expr.const]p12:
16647   //   A variable [...] is needed for constant evaluation if it is [...] a
16648   //   variable whose name appears as a potentially constant evaluated
16649   //   expression that is either a contexpr variable or is of non-volatile
16650   //   const-qualified integral type or of reference type
16651   bool NeededForConstantEvaluation =
16652       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16653 
16654   bool NeedDefinition =
16655       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16656 
16657   VarTemplateSpecializationDecl *VarSpec =
16658       dyn_cast<VarTemplateSpecializationDecl>(Var);
16659   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16660          "Can't instantiate a partial template specialization.");
16661 
16662   // If this might be a member specialization of a static data member, check
16663   // the specialization is visible. We already did the checks for variable
16664   // template specializations when we created them.
16665   if (NeedDefinition && TSK != TSK_Undeclared &&
16666       !isa<VarTemplateSpecializationDecl>(Var))
16667     SemaRef.checkSpecializationVisibility(Loc, Var);
16668 
16669   // Perform implicit instantiation of static data members, static data member
16670   // templates of class templates, and variable template specializations. Delay
16671   // instantiations of variable templates, except for those that could be used
16672   // in a constant expression.
16673   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16674     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16675     // instantiation declaration if a variable is usable in a constant
16676     // expression (among other cases).
16677     bool TryInstantiating =
16678         TSK == TSK_ImplicitInstantiation ||
16679         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16680 
16681     if (TryInstantiating) {
16682       SourceLocation PointOfInstantiation =
16683           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16684       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16685       if (FirstInstantiation) {
16686         PointOfInstantiation = Loc;
16687         if (MSI)
16688           MSI->setPointOfInstantiation(PointOfInstantiation);
16689         else
16690           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16691       }
16692 
16693       bool InstantiationDependent = false;
16694       bool IsNonDependent =
16695           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16696                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16697                   : true;
16698 
16699       // Do not instantiate specializations that are still type-dependent.
16700       if (IsNonDependent) {
16701         if (UsableInConstantExpr) {
16702           // Do not defer instantiations of variables that could be used in a
16703           // constant expression.
16704           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16705             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16706           });
16707         } else if (FirstInstantiation ||
16708                    isa<VarTemplateSpecializationDecl>(Var)) {
16709           // FIXME: For a specialization of a variable template, we don't
16710           // distinguish between "declaration and type implicitly instantiated"
16711           // and "implicit instantiation of definition requested", so we have
16712           // no direct way to avoid enqueueing the pending instantiation
16713           // multiple times.
16714           SemaRef.PendingInstantiations
16715               .push_back(std::make_pair(Var, PointOfInstantiation));
16716         }
16717       }
16718     }
16719   }
16720 
16721   // C++2a [basic.def.odr]p4:
16722   //   A variable x whose name appears as a potentially-evaluated expression e
16723   //   is odr-used by e unless
16724   //   -- x is a reference that is usable in constant expressions
16725   //   -- x is a variable of non-reference type that is usable in constant
16726   //      expressions and has no mutable subobjects [FIXME], and e is an
16727   //      element of the set of potential results of an expression of
16728   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16729   //      conversion is applied
16730   //   -- x is a variable of non-reference type, and e is an element of the set
16731   //      of potential results of a discarded-value expression to which the
16732   //      lvalue-to-rvalue conversion is not applied [FIXME]
16733   //
16734   // We check the first part of the second bullet here, and
16735   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16736   // FIXME: To get the third bullet right, we need to delay this even for
16737   // variables that are not usable in constant expressions.
16738 
16739   // If we already know this isn't an odr-use, there's nothing more to do.
16740   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16741     if (DRE->isNonOdrUse())
16742       return;
16743   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16744     if (ME->isNonOdrUse())
16745       return;
16746 
16747   switch (OdrUse) {
16748   case OdrUseContext::None:
16749     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16750            "missing non-odr-use marking for unevaluated decl ref");
16751     break;
16752 
16753   case OdrUseContext::FormallyOdrUsed:
16754     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16755     // behavior.
16756     break;
16757 
16758   case OdrUseContext::Used:
16759     // If we might later find that this expression isn't actually an odr-use,
16760     // delay the marking.
16761     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16762       SemaRef.MaybeODRUseExprs.insert(E);
16763     else
16764       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16765     break;
16766 
16767   case OdrUseContext::Dependent:
16768     // If this is a dependent context, we don't need to mark variables as
16769     // odr-used, but we may still need to track them for lambda capture.
16770     // FIXME: Do we also need to do this inside dependent typeid expressions
16771     // (which are modeled as unevaluated at this point)?
16772     const bool RefersToEnclosingScope =
16773         (SemaRef.CurContext != Var->getDeclContext() &&
16774          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16775     if (RefersToEnclosingScope) {
16776       LambdaScopeInfo *const LSI =
16777           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16778       if (LSI && (!LSI->CallOperator ||
16779                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16780         // If a variable could potentially be odr-used, defer marking it so
16781         // until we finish analyzing the full expression for any
16782         // lvalue-to-rvalue
16783         // or discarded value conversions that would obviate odr-use.
16784         // Add it to the list of potential captures that will be analyzed
16785         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16786         // unless the variable is a reference that was initialized by a constant
16787         // expression (this will never need to be captured or odr-used).
16788         //
16789         // FIXME: We can simplify this a lot after implementing P0588R1.
16790         assert(E && "Capture variable should be used in an expression.");
16791         if (!Var->getType()->isReferenceType() ||
16792             !Var->isUsableInConstantExpressions(SemaRef.Context))
16793           LSI->addPotentialCapture(E->IgnoreParens());
16794       }
16795     }
16796     break;
16797   }
16798 }
16799 
16800 /// Mark a variable referenced, and check whether it is odr-used
16801 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16802 /// used directly for normal expressions referring to VarDecl.
16803 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16804   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16805 }
16806 
16807 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16808                                Decl *D, Expr *E, bool MightBeOdrUse) {
16809   if (SemaRef.isInOpenMPDeclareTargetContext())
16810     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16811 
16812   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16813     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16814     return;
16815   }
16816 
16817   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16818 
16819   // If this is a call to a method via a cast, also mark the method in the
16820   // derived class used in case codegen can devirtualize the call.
16821   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16822   if (!ME)
16823     return;
16824   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16825   if (!MD)
16826     return;
16827   // Only attempt to devirtualize if this is truly a virtual call.
16828   bool IsVirtualCall = MD->isVirtual() &&
16829                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16830   if (!IsVirtualCall)
16831     return;
16832 
16833   // If it's possible to devirtualize the call, mark the called function
16834   // referenced.
16835   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16836       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16837   if (DM)
16838     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16839 }
16840 
16841 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16842 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16843   // TODO: update this with DR# once a defect report is filed.
16844   // C++11 defect. The address of a pure member should not be an ODR use, even
16845   // if it's a qualified reference.
16846   bool OdrUse = true;
16847   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16848     if (Method->isVirtual() &&
16849         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16850       OdrUse = false;
16851   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16852 }
16853 
16854 /// Perform reference-marking and odr-use handling for a MemberExpr.
16855 void Sema::MarkMemberReferenced(MemberExpr *E) {
16856   // C++11 [basic.def.odr]p2:
16857   //   A non-overloaded function whose name appears as a potentially-evaluated
16858   //   expression or a member of a set of candidate functions, if selected by
16859   //   overload resolution when referred to from a potentially-evaluated
16860   //   expression, is odr-used, unless it is a pure virtual function and its
16861   //   name is not explicitly qualified.
16862   bool MightBeOdrUse = true;
16863   if (E->performsVirtualDispatch(getLangOpts())) {
16864     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16865       if (Method->isPure())
16866         MightBeOdrUse = false;
16867   }
16868   SourceLocation Loc =
16869       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16870   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16871 }
16872 
16873 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16874 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16875   for (VarDecl *VD : *E)
16876     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16877 }
16878 
16879 /// Perform marking for a reference to an arbitrary declaration.  It
16880 /// marks the declaration referenced, and performs odr-use checking for
16881 /// functions and variables. This method should not be used when building a
16882 /// normal expression which refers to a variable.
16883 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16884                                  bool MightBeOdrUse) {
16885   if (MightBeOdrUse) {
16886     if (auto *VD = dyn_cast<VarDecl>(D)) {
16887       MarkVariableReferenced(Loc, VD);
16888       return;
16889     }
16890   }
16891   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16892     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16893     return;
16894   }
16895   D->setReferenced();
16896 }
16897 
16898 namespace {
16899   // Mark all of the declarations used by a type as referenced.
16900   // FIXME: Not fully implemented yet! We need to have a better understanding
16901   // of when we're entering a context we should not recurse into.
16902   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16903   // TreeTransforms rebuilding the type in a new context. Rather than
16904   // duplicating the TreeTransform logic, we should consider reusing it here.
16905   // Currently that causes problems when rebuilding LambdaExprs.
16906   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16907     Sema &S;
16908     SourceLocation Loc;
16909 
16910   public:
16911     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16912 
16913     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16914 
16915     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16916   };
16917 }
16918 
16919 bool MarkReferencedDecls::TraverseTemplateArgument(
16920     const TemplateArgument &Arg) {
16921   {
16922     // A non-type template argument is a constant-evaluated context.
16923     EnterExpressionEvaluationContext Evaluated(
16924         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16925     if (Arg.getKind() == TemplateArgument::Declaration) {
16926       if (Decl *D = Arg.getAsDecl())
16927         S.MarkAnyDeclReferenced(Loc, D, true);
16928     } else if (Arg.getKind() == TemplateArgument::Expression) {
16929       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16930     }
16931   }
16932 
16933   return Inherited::TraverseTemplateArgument(Arg);
16934 }
16935 
16936 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16937   MarkReferencedDecls Marker(*this, Loc);
16938   Marker.TraverseType(T);
16939 }
16940 
16941 namespace {
16942   /// Helper class that marks all of the declarations referenced by
16943   /// potentially-evaluated subexpressions as "referenced".
16944   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16945     Sema &S;
16946     bool SkipLocalVariables;
16947 
16948   public:
16949     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16950 
16951     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16952       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16953 
16954     void VisitDeclRefExpr(DeclRefExpr *E) {
16955       // If we were asked not to visit local variables, don't.
16956       if (SkipLocalVariables) {
16957         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16958           if (VD->hasLocalStorage())
16959             return;
16960       }
16961 
16962       S.MarkDeclRefReferenced(E);
16963     }
16964 
16965     void VisitMemberExpr(MemberExpr *E) {
16966       S.MarkMemberReferenced(E);
16967       Inherited::VisitMemberExpr(E);
16968     }
16969 
16970     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16971       S.MarkFunctionReferenced(
16972           E->getBeginLoc(),
16973           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16974       Visit(E->getSubExpr());
16975     }
16976 
16977     void VisitCXXNewExpr(CXXNewExpr *E) {
16978       if (E->getOperatorNew())
16979         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16980       if (E->getOperatorDelete())
16981         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16982       Inherited::VisitCXXNewExpr(E);
16983     }
16984 
16985     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16986       if (E->getOperatorDelete())
16987         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16988       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16989       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16990         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16991         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16992       }
16993 
16994       Inherited::VisitCXXDeleteExpr(E);
16995     }
16996 
16997     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16998       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16999       Inherited::VisitCXXConstructExpr(E);
17000     }
17001 
17002     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17003       Visit(E->getExpr());
17004     }
17005   };
17006 }
17007 
17008 /// Mark any declarations that appear within this expression or any
17009 /// potentially-evaluated subexpressions as "referenced".
17010 ///
17011 /// \param SkipLocalVariables If true, don't mark local variables as
17012 /// 'referenced'.
17013 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17014                                             bool SkipLocalVariables) {
17015   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17016 }
17017 
17018 /// Emit a diagnostic that describes an effect on the run-time behavior
17019 /// of the program being compiled.
17020 ///
17021 /// This routine emits the given diagnostic when the code currently being
17022 /// type-checked is "potentially evaluated", meaning that there is a
17023 /// possibility that the code will actually be executable. Code in sizeof()
17024 /// expressions, code used only during overload resolution, etc., are not
17025 /// potentially evaluated. This routine will suppress such diagnostics or,
17026 /// in the absolutely nutty case of potentially potentially evaluated
17027 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17028 /// later.
17029 ///
17030 /// This routine should be used for all diagnostics that describe the run-time
17031 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17032 /// Failure to do so will likely result in spurious diagnostics or failures
17033 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17034 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17035                                const PartialDiagnostic &PD) {
17036   switch (ExprEvalContexts.back().Context) {
17037   case ExpressionEvaluationContext::Unevaluated:
17038   case ExpressionEvaluationContext::UnevaluatedList:
17039   case ExpressionEvaluationContext::UnevaluatedAbstract:
17040   case ExpressionEvaluationContext::DiscardedStatement:
17041     // The argument will never be evaluated, so don't complain.
17042     break;
17043 
17044   case ExpressionEvaluationContext::ConstantEvaluated:
17045     // Relevant diagnostics should be produced by constant evaluation.
17046     break;
17047 
17048   case ExpressionEvaluationContext::PotentiallyEvaluated:
17049   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17050     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17051       FunctionScopes.back()->PossiblyUnreachableDiags.
17052         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17053       return true;
17054     }
17055 
17056     // The initializer of a constexpr variable or of the first declaration of a
17057     // static data member is not syntactically a constant evaluated constant,
17058     // but nonetheless is always required to be a constant expression, so we
17059     // can skip diagnosing.
17060     // FIXME: Using the mangling context here is a hack.
17061     if (auto *VD = dyn_cast_or_null<VarDecl>(
17062             ExprEvalContexts.back().ManglingContextDecl)) {
17063       if (VD->isConstexpr() ||
17064           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17065         break;
17066       // FIXME: For any other kind of variable, we should build a CFG for its
17067       // initializer and check whether the context in question is reachable.
17068     }
17069 
17070     Diag(Loc, PD);
17071     return true;
17072   }
17073 
17074   return false;
17075 }
17076 
17077 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17078                                const PartialDiagnostic &PD) {
17079   return DiagRuntimeBehavior(
17080       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17081 }
17082 
17083 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17084                                CallExpr *CE, FunctionDecl *FD) {
17085   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17086     return false;
17087 
17088   // If we're inside a decltype's expression, don't check for a valid return
17089   // type or construct temporaries until we know whether this is the last call.
17090   if (ExprEvalContexts.back().ExprContext ==
17091       ExpressionEvaluationContextRecord::EK_Decltype) {
17092     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17093     return false;
17094   }
17095 
17096   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17097     FunctionDecl *FD;
17098     CallExpr *CE;
17099 
17100   public:
17101     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17102       : FD(FD), CE(CE) { }
17103 
17104     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17105       if (!FD) {
17106         S.Diag(Loc, diag::err_call_incomplete_return)
17107           << T << CE->getSourceRange();
17108         return;
17109       }
17110 
17111       S.Diag(Loc, diag::err_call_function_incomplete_return)
17112         << CE->getSourceRange() << FD->getDeclName() << T;
17113       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17114           << FD->getDeclName();
17115     }
17116   } Diagnoser(FD, CE);
17117 
17118   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17119     return true;
17120 
17121   return false;
17122 }
17123 
17124 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17125 // will prevent this condition from triggering, which is what we want.
17126 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17127   SourceLocation Loc;
17128 
17129   unsigned diagnostic = diag::warn_condition_is_assignment;
17130   bool IsOrAssign = false;
17131 
17132   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17133     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17134       return;
17135 
17136     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17137 
17138     // Greylist some idioms by putting them into a warning subcategory.
17139     if (ObjCMessageExpr *ME
17140           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17141       Selector Sel = ME->getSelector();
17142 
17143       // self = [<foo> init...]
17144       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17145         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17146 
17147       // <foo> = [<bar> nextObject]
17148       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17149         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17150     }
17151 
17152     Loc = Op->getOperatorLoc();
17153   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17154     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17155       return;
17156 
17157     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17158     Loc = Op->getOperatorLoc();
17159   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17160     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17161   else {
17162     // Not an assignment.
17163     return;
17164   }
17165 
17166   Diag(Loc, diagnostic) << E->getSourceRange();
17167 
17168   SourceLocation Open = E->getBeginLoc();
17169   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17170   Diag(Loc, diag::note_condition_assign_silence)
17171         << FixItHint::CreateInsertion(Open, "(")
17172         << FixItHint::CreateInsertion(Close, ")");
17173 
17174   if (IsOrAssign)
17175     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17176       << FixItHint::CreateReplacement(Loc, "!=");
17177   else
17178     Diag(Loc, diag::note_condition_assign_to_comparison)
17179       << FixItHint::CreateReplacement(Loc, "==");
17180 }
17181 
17182 /// Redundant parentheses over an equality comparison can indicate
17183 /// that the user intended an assignment used as condition.
17184 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17185   // Don't warn if the parens came from a macro.
17186   SourceLocation parenLoc = ParenE->getBeginLoc();
17187   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17188     return;
17189   // Don't warn for dependent expressions.
17190   if (ParenE->isTypeDependent())
17191     return;
17192 
17193   Expr *E = ParenE->IgnoreParens();
17194 
17195   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17196     if (opE->getOpcode() == BO_EQ &&
17197         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17198                                                            == Expr::MLV_Valid) {
17199       SourceLocation Loc = opE->getOperatorLoc();
17200 
17201       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17202       SourceRange ParenERange = ParenE->getSourceRange();
17203       Diag(Loc, diag::note_equality_comparison_silence)
17204         << FixItHint::CreateRemoval(ParenERange.getBegin())
17205         << FixItHint::CreateRemoval(ParenERange.getEnd());
17206       Diag(Loc, diag::note_equality_comparison_to_assign)
17207         << FixItHint::CreateReplacement(Loc, "=");
17208     }
17209 }
17210 
17211 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17212                                        bool IsConstexpr) {
17213   DiagnoseAssignmentAsCondition(E);
17214   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17215     DiagnoseEqualityWithExtraParens(parenE);
17216 
17217   ExprResult result = CheckPlaceholderExpr(E);
17218   if (result.isInvalid()) return ExprError();
17219   E = result.get();
17220 
17221   if (!E->isTypeDependent()) {
17222     if (getLangOpts().CPlusPlus)
17223       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17224 
17225     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17226     if (ERes.isInvalid())
17227       return ExprError();
17228     E = ERes.get();
17229 
17230     QualType T = E->getType();
17231     if (!T->isScalarType()) { // C99 6.8.4.1p1
17232       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17233         << T << E->getSourceRange();
17234       return ExprError();
17235     }
17236     CheckBoolLikeConversion(E, Loc);
17237   }
17238 
17239   return E;
17240 }
17241 
17242 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17243                                            Expr *SubExpr, ConditionKind CK) {
17244   // Empty conditions are valid in for-statements.
17245   if (!SubExpr)
17246     return ConditionResult();
17247 
17248   ExprResult Cond;
17249   switch (CK) {
17250   case ConditionKind::Boolean:
17251     Cond = CheckBooleanCondition(Loc, SubExpr);
17252     break;
17253 
17254   case ConditionKind::ConstexprIf:
17255     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17256     break;
17257 
17258   case ConditionKind::Switch:
17259     Cond = CheckSwitchCondition(Loc, SubExpr);
17260     break;
17261   }
17262   if (Cond.isInvalid())
17263     return ConditionError();
17264 
17265   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17266   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17267   if (!FullExpr.get())
17268     return ConditionError();
17269 
17270   return ConditionResult(*this, nullptr, FullExpr,
17271                          CK == ConditionKind::ConstexprIf);
17272 }
17273 
17274 namespace {
17275   /// A visitor for rebuilding a call to an __unknown_any expression
17276   /// to have an appropriate type.
17277   struct RebuildUnknownAnyFunction
17278     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17279 
17280     Sema &S;
17281 
17282     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17283 
17284     ExprResult VisitStmt(Stmt *S) {
17285       llvm_unreachable("unexpected statement!");
17286     }
17287 
17288     ExprResult VisitExpr(Expr *E) {
17289       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17290         << E->getSourceRange();
17291       return ExprError();
17292     }
17293 
17294     /// Rebuild an expression which simply semantically wraps another
17295     /// expression which it shares the type and value kind of.
17296     template <class T> ExprResult rebuildSugarExpr(T *E) {
17297       ExprResult SubResult = Visit(E->getSubExpr());
17298       if (SubResult.isInvalid()) return ExprError();
17299 
17300       Expr *SubExpr = SubResult.get();
17301       E->setSubExpr(SubExpr);
17302       E->setType(SubExpr->getType());
17303       E->setValueKind(SubExpr->getValueKind());
17304       assert(E->getObjectKind() == OK_Ordinary);
17305       return E;
17306     }
17307 
17308     ExprResult VisitParenExpr(ParenExpr *E) {
17309       return rebuildSugarExpr(E);
17310     }
17311 
17312     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17313       return rebuildSugarExpr(E);
17314     }
17315 
17316     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17317       ExprResult SubResult = Visit(E->getSubExpr());
17318       if (SubResult.isInvalid()) return ExprError();
17319 
17320       Expr *SubExpr = SubResult.get();
17321       E->setSubExpr(SubExpr);
17322       E->setType(S.Context.getPointerType(SubExpr->getType()));
17323       assert(E->getValueKind() == VK_RValue);
17324       assert(E->getObjectKind() == OK_Ordinary);
17325       return E;
17326     }
17327 
17328     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17329       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17330 
17331       E->setType(VD->getType());
17332 
17333       assert(E->getValueKind() == VK_RValue);
17334       if (S.getLangOpts().CPlusPlus &&
17335           !(isa<CXXMethodDecl>(VD) &&
17336             cast<CXXMethodDecl>(VD)->isInstance()))
17337         E->setValueKind(VK_LValue);
17338 
17339       return E;
17340     }
17341 
17342     ExprResult VisitMemberExpr(MemberExpr *E) {
17343       return resolveDecl(E, E->getMemberDecl());
17344     }
17345 
17346     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17347       return resolveDecl(E, E->getDecl());
17348     }
17349   };
17350 }
17351 
17352 /// Given a function expression of unknown-any type, try to rebuild it
17353 /// to have a function type.
17354 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17355   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17356   if (Result.isInvalid()) return ExprError();
17357   return S.DefaultFunctionArrayConversion(Result.get());
17358 }
17359 
17360 namespace {
17361   /// A visitor for rebuilding an expression of type __unknown_anytype
17362   /// into one which resolves the type directly on the referring
17363   /// expression.  Strict preservation of the original source
17364   /// structure is not a goal.
17365   struct RebuildUnknownAnyExpr
17366     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17367 
17368     Sema &S;
17369 
17370     /// The current destination type.
17371     QualType DestType;
17372 
17373     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17374       : S(S), DestType(CastType) {}
17375 
17376     ExprResult VisitStmt(Stmt *S) {
17377       llvm_unreachable("unexpected statement!");
17378     }
17379 
17380     ExprResult VisitExpr(Expr *E) {
17381       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17382         << E->getSourceRange();
17383       return ExprError();
17384     }
17385 
17386     ExprResult VisitCallExpr(CallExpr *E);
17387     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17388 
17389     /// Rebuild an expression which simply semantically wraps another
17390     /// expression which it shares the type and value kind of.
17391     template <class T> ExprResult rebuildSugarExpr(T *E) {
17392       ExprResult SubResult = Visit(E->getSubExpr());
17393       if (SubResult.isInvalid()) return ExprError();
17394       Expr *SubExpr = SubResult.get();
17395       E->setSubExpr(SubExpr);
17396       E->setType(SubExpr->getType());
17397       E->setValueKind(SubExpr->getValueKind());
17398       assert(E->getObjectKind() == OK_Ordinary);
17399       return E;
17400     }
17401 
17402     ExprResult VisitParenExpr(ParenExpr *E) {
17403       return rebuildSugarExpr(E);
17404     }
17405 
17406     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17407       return rebuildSugarExpr(E);
17408     }
17409 
17410     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17411       const PointerType *Ptr = DestType->getAs<PointerType>();
17412       if (!Ptr) {
17413         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17414           << E->getSourceRange();
17415         return ExprError();
17416       }
17417 
17418       if (isa<CallExpr>(E->getSubExpr())) {
17419         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17420           << E->getSourceRange();
17421         return ExprError();
17422       }
17423 
17424       assert(E->getValueKind() == VK_RValue);
17425       assert(E->getObjectKind() == OK_Ordinary);
17426       E->setType(DestType);
17427 
17428       // Build the sub-expression as if it were an object of the pointee type.
17429       DestType = Ptr->getPointeeType();
17430       ExprResult SubResult = Visit(E->getSubExpr());
17431       if (SubResult.isInvalid()) return ExprError();
17432       E->setSubExpr(SubResult.get());
17433       return E;
17434     }
17435 
17436     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17437 
17438     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17439 
17440     ExprResult VisitMemberExpr(MemberExpr *E) {
17441       return resolveDecl(E, E->getMemberDecl());
17442     }
17443 
17444     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17445       return resolveDecl(E, E->getDecl());
17446     }
17447   };
17448 }
17449 
17450 /// Rebuilds a call expression which yielded __unknown_anytype.
17451 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17452   Expr *CalleeExpr = E->getCallee();
17453 
17454   enum FnKind {
17455     FK_MemberFunction,
17456     FK_FunctionPointer,
17457     FK_BlockPointer
17458   };
17459 
17460   FnKind Kind;
17461   QualType CalleeType = CalleeExpr->getType();
17462   if (CalleeType == S.Context.BoundMemberTy) {
17463     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17464     Kind = FK_MemberFunction;
17465     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17466   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17467     CalleeType = Ptr->getPointeeType();
17468     Kind = FK_FunctionPointer;
17469   } else {
17470     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17471     Kind = FK_BlockPointer;
17472   }
17473   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17474 
17475   // Verify that this is a legal result type of a function.
17476   if (DestType->isArrayType() || DestType->isFunctionType()) {
17477     unsigned diagID = diag::err_func_returning_array_function;
17478     if (Kind == FK_BlockPointer)
17479       diagID = diag::err_block_returning_array_function;
17480 
17481     S.Diag(E->getExprLoc(), diagID)
17482       << DestType->isFunctionType() << DestType;
17483     return ExprError();
17484   }
17485 
17486   // Otherwise, go ahead and set DestType as the call's result.
17487   E->setType(DestType.getNonLValueExprType(S.Context));
17488   E->setValueKind(Expr::getValueKindForType(DestType));
17489   assert(E->getObjectKind() == OK_Ordinary);
17490 
17491   // Rebuild the function type, replacing the result type with DestType.
17492   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17493   if (Proto) {
17494     // __unknown_anytype(...) is a special case used by the debugger when
17495     // it has no idea what a function's signature is.
17496     //
17497     // We want to build this call essentially under the K&R
17498     // unprototyped rules, but making a FunctionNoProtoType in C++
17499     // would foul up all sorts of assumptions.  However, we cannot
17500     // simply pass all arguments as variadic arguments, nor can we
17501     // portably just call the function under a non-variadic type; see
17502     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17503     // However, it turns out that in practice it is generally safe to
17504     // call a function declared as "A foo(B,C,D);" under the prototype
17505     // "A foo(B,C,D,...);".  The only known exception is with the
17506     // Windows ABI, where any variadic function is implicitly cdecl
17507     // regardless of its normal CC.  Therefore we change the parameter
17508     // types to match the types of the arguments.
17509     //
17510     // This is a hack, but it is far superior to moving the
17511     // corresponding target-specific code from IR-gen to Sema/AST.
17512 
17513     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17514     SmallVector<QualType, 8> ArgTypes;
17515     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17516       ArgTypes.reserve(E->getNumArgs());
17517       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17518         Expr *Arg = E->getArg(i);
17519         QualType ArgType = Arg->getType();
17520         if (E->isLValue()) {
17521           ArgType = S.Context.getLValueReferenceType(ArgType);
17522         } else if (E->isXValue()) {
17523           ArgType = S.Context.getRValueReferenceType(ArgType);
17524         }
17525         ArgTypes.push_back(ArgType);
17526       }
17527       ParamTypes = ArgTypes;
17528     }
17529     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17530                                          Proto->getExtProtoInfo());
17531   } else {
17532     DestType = S.Context.getFunctionNoProtoType(DestType,
17533                                                 FnType->getExtInfo());
17534   }
17535 
17536   // Rebuild the appropriate pointer-to-function type.
17537   switch (Kind) {
17538   case FK_MemberFunction:
17539     // Nothing to do.
17540     break;
17541 
17542   case FK_FunctionPointer:
17543     DestType = S.Context.getPointerType(DestType);
17544     break;
17545 
17546   case FK_BlockPointer:
17547     DestType = S.Context.getBlockPointerType(DestType);
17548     break;
17549   }
17550 
17551   // Finally, we can recurse.
17552   ExprResult CalleeResult = Visit(CalleeExpr);
17553   if (!CalleeResult.isUsable()) return ExprError();
17554   E->setCallee(CalleeResult.get());
17555 
17556   // Bind a temporary if necessary.
17557   return S.MaybeBindToTemporary(E);
17558 }
17559 
17560 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17561   // Verify that this is a legal result type of a call.
17562   if (DestType->isArrayType() || DestType->isFunctionType()) {
17563     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17564       << DestType->isFunctionType() << DestType;
17565     return ExprError();
17566   }
17567 
17568   // Rewrite the method result type if available.
17569   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17570     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17571     Method->setReturnType(DestType);
17572   }
17573 
17574   // Change the type of the message.
17575   E->setType(DestType.getNonReferenceType());
17576   E->setValueKind(Expr::getValueKindForType(DestType));
17577 
17578   return S.MaybeBindToTemporary(E);
17579 }
17580 
17581 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17582   // The only case we should ever see here is a function-to-pointer decay.
17583   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17584     assert(E->getValueKind() == VK_RValue);
17585     assert(E->getObjectKind() == OK_Ordinary);
17586 
17587     E->setType(DestType);
17588 
17589     // Rebuild the sub-expression as the pointee (function) type.
17590     DestType = DestType->castAs<PointerType>()->getPointeeType();
17591 
17592     ExprResult Result = Visit(E->getSubExpr());
17593     if (!Result.isUsable()) return ExprError();
17594 
17595     E->setSubExpr(Result.get());
17596     return E;
17597   } else if (E->getCastKind() == CK_LValueToRValue) {
17598     assert(E->getValueKind() == VK_RValue);
17599     assert(E->getObjectKind() == OK_Ordinary);
17600 
17601     assert(isa<BlockPointerType>(E->getType()));
17602 
17603     E->setType(DestType);
17604 
17605     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17606     DestType = S.Context.getLValueReferenceType(DestType);
17607 
17608     ExprResult Result = Visit(E->getSubExpr());
17609     if (!Result.isUsable()) return ExprError();
17610 
17611     E->setSubExpr(Result.get());
17612     return E;
17613   } else {
17614     llvm_unreachable("Unhandled cast type!");
17615   }
17616 }
17617 
17618 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17619   ExprValueKind ValueKind = VK_LValue;
17620   QualType Type = DestType;
17621 
17622   // We know how to make this work for certain kinds of decls:
17623 
17624   //  - functions
17625   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17626     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17627       DestType = Ptr->getPointeeType();
17628       ExprResult Result = resolveDecl(E, VD);
17629       if (Result.isInvalid()) return ExprError();
17630       return S.ImpCastExprToType(Result.get(), Type,
17631                                  CK_FunctionToPointerDecay, VK_RValue);
17632     }
17633 
17634     if (!Type->isFunctionType()) {
17635       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17636         << VD << E->getSourceRange();
17637       return ExprError();
17638     }
17639     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17640       // We must match the FunctionDecl's type to the hack introduced in
17641       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17642       // type. See the lengthy commentary in that routine.
17643       QualType FDT = FD->getType();
17644       const FunctionType *FnType = FDT->castAs<FunctionType>();
17645       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17646       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17647       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17648         SourceLocation Loc = FD->getLocation();
17649         FunctionDecl *NewFD = FunctionDecl::Create(
17650             S.Context, FD->getDeclContext(), Loc, Loc,
17651             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17652             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17653             /*ConstexprKind*/ CSK_unspecified);
17654 
17655         if (FD->getQualifier())
17656           NewFD->setQualifierInfo(FD->getQualifierLoc());
17657 
17658         SmallVector<ParmVarDecl*, 16> Params;
17659         for (const auto &AI : FT->param_types()) {
17660           ParmVarDecl *Param =
17661             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17662           Param->setScopeInfo(0, Params.size());
17663           Params.push_back(Param);
17664         }
17665         NewFD->setParams(Params);
17666         DRE->setDecl(NewFD);
17667         VD = DRE->getDecl();
17668       }
17669     }
17670 
17671     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17672       if (MD->isInstance()) {
17673         ValueKind = VK_RValue;
17674         Type = S.Context.BoundMemberTy;
17675       }
17676 
17677     // Function references aren't l-values in C.
17678     if (!S.getLangOpts().CPlusPlus)
17679       ValueKind = VK_RValue;
17680 
17681   //  - variables
17682   } else if (isa<VarDecl>(VD)) {
17683     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17684       Type = RefTy->getPointeeType();
17685     } else if (Type->isFunctionType()) {
17686       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17687         << VD << E->getSourceRange();
17688       return ExprError();
17689     }
17690 
17691   //  - nothing else
17692   } else {
17693     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17694       << VD << E->getSourceRange();
17695     return ExprError();
17696   }
17697 
17698   // Modifying the declaration like this is friendly to IR-gen but
17699   // also really dangerous.
17700   VD->setType(DestType);
17701   E->setType(Type);
17702   E->setValueKind(ValueKind);
17703   return E;
17704 }
17705 
17706 /// Check a cast of an unknown-any type.  We intentionally only
17707 /// trigger this for C-style casts.
17708 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17709                                      Expr *CastExpr, CastKind &CastKind,
17710                                      ExprValueKind &VK, CXXCastPath &Path) {
17711   // The type we're casting to must be either void or complete.
17712   if (!CastType->isVoidType() &&
17713       RequireCompleteType(TypeRange.getBegin(), CastType,
17714                           diag::err_typecheck_cast_to_incomplete))
17715     return ExprError();
17716 
17717   // Rewrite the casted expression from scratch.
17718   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17719   if (!result.isUsable()) return ExprError();
17720 
17721   CastExpr = result.get();
17722   VK = CastExpr->getValueKind();
17723   CastKind = CK_NoOp;
17724 
17725   return CastExpr;
17726 }
17727 
17728 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17729   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17730 }
17731 
17732 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17733                                     Expr *arg, QualType &paramType) {
17734   // If the syntactic form of the argument is not an explicit cast of
17735   // any sort, just do default argument promotion.
17736   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17737   if (!castArg) {
17738     ExprResult result = DefaultArgumentPromotion(arg);
17739     if (result.isInvalid()) return ExprError();
17740     paramType = result.get()->getType();
17741     return result;
17742   }
17743 
17744   // Otherwise, use the type that was written in the explicit cast.
17745   assert(!arg->hasPlaceholderType());
17746   paramType = castArg->getTypeAsWritten();
17747 
17748   // Copy-initialize a parameter of that type.
17749   InitializedEntity entity =
17750     InitializedEntity::InitializeParameter(Context, paramType,
17751                                            /*consumed*/ false);
17752   return PerformCopyInitialization(entity, callLoc, arg);
17753 }
17754 
17755 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17756   Expr *orig = E;
17757   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17758   while (true) {
17759     E = E->IgnoreParenImpCasts();
17760     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17761       E = call->getCallee();
17762       diagID = diag::err_uncasted_call_of_unknown_any;
17763     } else {
17764       break;
17765     }
17766   }
17767 
17768   SourceLocation loc;
17769   NamedDecl *d;
17770   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17771     loc = ref->getLocation();
17772     d = ref->getDecl();
17773   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17774     loc = mem->getMemberLoc();
17775     d = mem->getMemberDecl();
17776   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17777     diagID = diag::err_uncasted_call_of_unknown_any;
17778     loc = msg->getSelectorStartLoc();
17779     d = msg->getMethodDecl();
17780     if (!d) {
17781       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17782         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17783         << orig->getSourceRange();
17784       return ExprError();
17785     }
17786   } else {
17787     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17788       << E->getSourceRange();
17789     return ExprError();
17790   }
17791 
17792   S.Diag(loc, diagID) << d << orig->getSourceRange();
17793 
17794   // Never recoverable.
17795   return ExprError();
17796 }
17797 
17798 /// Check for operands with placeholder types and complain if found.
17799 /// Returns ExprError() if there was an error and no recovery was possible.
17800 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17801   if (!getLangOpts().CPlusPlus) {
17802     // C cannot handle TypoExpr nodes on either side of a binop because it
17803     // doesn't handle dependent types properly, so make sure any TypoExprs have
17804     // been dealt with before checking the operands.
17805     ExprResult Result = CorrectDelayedTyposInExpr(E);
17806     if (!Result.isUsable()) return ExprError();
17807     E = Result.get();
17808   }
17809 
17810   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17811   if (!placeholderType) return E;
17812 
17813   switch (placeholderType->getKind()) {
17814 
17815   // Overloaded expressions.
17816   case BuiltinType::Overload: {
17817     // Try to resolve a single function template specialization.
17818     // This is obligatory.
17819     ExprResult Result = E;
17820     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17821       return Result;
17822 
17823     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17824     // leaves Result unchanged on failure.
17825     Result = E;
17826     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17827       return Result;
17828 
17829     // If that failed, try to recover with a call.
17830     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17831                          /*complain*/ true);
17832     return Result;
17833   }
17834 
17835   // Bound member functions.
17836   case BuiltinType::BoundMember: {
17837     ExprResult result = E;
17838     const Expr *BME = E->IgnoreParens();
17839     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17840     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17841     if (isa<CXXPseudoDestructorExpr>(BME)) {
17842       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17843     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17844       if (ME->getMemberNameInfo().getName().getNameKind() ==
17845           DeclarationName::CXXDestructorName)
17846         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17847     }
17848     tryToRecoverWithCall(result, PD,
17849                          /*complain*/ true);
17850     return result;
17851   }
17852 
17853   // ARC unbridged casts.
17854   case BuiltinType::ARCUnbridgedCast: {
17855     Expr *realCast = stripARCUnbridgedCast(E);
17856     diagnoseARCUnbridgedCast(realCast);
17857     return realCast;
17858   }
17859 
17860   // Expressions of unknown type.
17861   case BuiltinType::UnknownAny:
17862     return diagnoseUnknownAnyExpr(*this, E);
17863 
17864   // Pseudo-objects.
17865   case BuiltinType::PseudoObject:
17866     return checkPseudoObjectRValue(E);
17867 
17868   case BuiltinType::BuiltinFn: {
17869     // Accept __noop without parens by implicitly converting it to a call expr.
17870     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17871     if (DRE) {
17872       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17873       if (FD->getBuiltinID() == Builtin::BI__noop) {
17874         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17875                               CK_BuiltinFnToFnPtr)
17876                 .get();
17877         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17878                                 VK_RValue, SourceLocation());
17879       }
17880     }
17881 
17882     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17883     return ExprError();
17884   }
17885 
17886   // Expressions of unknown type.
17887   case BuiltinType::OMPArraySection:
17888     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17889     return ExprError();
17890 
17891   // Everything else should be impossible.
17892 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17893   case BuiltinType::Id:
17894 #include "clang/Basic/OpenCLImageTypes.def"
17895 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17896   case BuiltinType::Id:
17897 #include "clang/Basic/OpenCLExtensionTypes.def"
17898 #define SVE_TYPE(Name, Id, SingletonId) \
17899   case BuiltinType::Id:
17900 #include "clang/Basic/AArch64SVEACLETypes.def"
17901 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17902 #define PLACEHOLDER_TYPE(Id, SingletonId)
17903 #include "clang/AST/BuiltinTypes.def"
17904     break;
17905   }
17906 
17907   llvm_unreachable("invalid placeholder type!");
17908 }
17909 
17910 bool Sema::CheckCaseExpression(Expr *E) {
17911   if (E->isTypeDependent())
17912     return true;
17913   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17914     return E->getType()->isIntegralOrEnumerationType();
17915   return false;
17916 }
17917 
17918 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17919 ExprResult
17920 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17921   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17922          "Unknown Objective-C Boolean value!");
17923   QualType BoolT = Context.ObjCBuiltinBoolTy;
17924   if (!Context.getBOOLDecl()) {
17925     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17926                         Sema::LookupOrdinaryName);
17927     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17928       NamedDecl *ND = Result.getFoundDecl();
17929       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17930         Context.setBOOLDecl(TD);
17931     }
17932   }
17933   if (Context.getBOOLDecl())
17934     BoolT = Context.getBOOLType();
17935   return new (Context)
17936       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17937 }
17938 
17939 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17940     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17941     SourceLocation RParen) {
17942 
17943   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17944 
17945   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17946     return Spec.getPlatform() == Platform;
17947   });
17948 
17949   VersionTuple Version;
17950   if (Spec != AvailSpecs.end())
17951     Version = Spec->getVersion();
17952 
17953   // The use of `@available` in the enclosing function should be analyzed to
17954   // warn when it's used inappropriately (i.e. not if(@available)).
17955   if (getCurFunctionOrMethodDecl())
17956     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17957   else if (getCurBlock() || getCurLambda())
17958     getCurFunction()->HasPotentialAvailabilityViolations = true;
17959 
17960   return new (Context)
17961       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17962 }
17963