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     // In Microsoft mode, if we are performing lookup from within a friend
1994     // function definition declared at class scope then we must set
1995     // DC to the lexical parent to be able to search into the parent
1996     // class.
1997     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999         DC->getLexicalParent()->isRecord())
2000       DC = DC->getLexicalParent();
2001     else
2002       DC = DC->getParent();
2003   }
2004 
2005   // We didn't find anything, so try to correct for a typo.
2006   TypoCorrection Corrected;
2007   if (S && Out) {
2008     SourceLocation TypoLoc = R.getNameLoc();
2009     assert(!ExplicitTemplateArgs &&
2010            "Diagnosing an empty lookup with explicit template args!");
2011     *Out = CorrectTypoDelayed(
2012         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2013         [=](const TypoCorrection &TC) {
2014           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015                                         diagnostic, diagnostic_suggest);
2016         },
2017         nullptr, CTK_ErrorRecovery);
2018     if (*Out)
2019       return true;
2020   } else if (S &&
2021              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2022                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2023     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024     bool DroppedSpecifier =
2025         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026     R.setLookupName(Corrected.getCorrection());
2027 
2028     bool AcceptableWithRecovery = false;
2029     bool AcceptableWithoutRecovery = false;
2030     NamedDecl *ND = Corrected.getFoundDecl();
2031     if (ND) {
2032       if (Corrected.isOverloaded()) {
2033         OverloadCandidateSet OCS(R.getNameLoc(),
2034                                  OverloadCandidateSet::CSK_Normal);
2035         OverloadCandidateSet::iterator Best;
2036         for (NamedDecl *CD : Corrected) {
2037           if (FunctionTemplateDecl *FTD =
2038                    dyn_cast<FunctionTemplateDecl>(CD))
2039             AddTemplateOverloadCandidate(
2040                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041                 Args, OCS);
2042           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045                                    Args, OCS);
2046         }
2047         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048         case OR_Success:
2049           ND = Best->FoundDecl;
2050           Corrected.setCorrectionDecl(ND);
2051           break;
2052         default:
2053           // FIXME: Arbitrarily pick the first declaration for the note.
2054           Corrected.setCorrectionDecl(ND);
2055           break;
2056         }
2057       }
2058       R.addDecl(ND);
2059       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060         CXXRecordDecl *Record = nullptr;
2061         if (Corrected.getCorrectionSpecifier()) {
2062           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063           Record = Ty->getAsCXXRecordDecl();
2064         }
2065         if (!Record)
2066           Record = cast<CXXRecordDecl>(
2067               ND->getDeclContext()->getRedeclContext());
2068         R.setNamingClass(Record);
2069       }
2070 
2071       auto *UnderlyingND = ND->getUnderlyingDecl();
2072       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073                                isa<FunctionTemplateDecl>(UnderlyingND);
2074       // FIXME: If we ended up with a typo for a type name or
2075       // Objective-C class name, we're in trouble because the parser
2076       // is in the wrong place to recover. Suggest the typo
2077       // correction, but don't make it a fix-it since we're not going
2078       // to recover well anyway.
2079       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2080                                   getAsTypeTemplateDecl(UnderlyingND) ||
2081                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2082     } else {
2083       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2084       // because we aren't able to recover.
2085       AcceptableWithoutRecovery = true;
2086     }
2087 
2088     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2089       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2090                             ? diag::note_implicit_param_decl
2091                             : diag::note_previous_decl;
2092       if (SS.isEmpty())
2093         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2094                      PDiag(NoteID), AcceptableWithRecovery);
2095       else
2096         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2097                                   << Name << computeDeclContext(SS, false)
2098                                   << DroppedSpecifier << SS.getRange(),
2099                      PDiag(NoteID), AcceptableWithRecovery);
2100 
2101       // Tell the callee whether to try to recover.
2102       return !AcceptableWithRecovery;
2103     }
2104   }
2105   R.clear();
2106 
2107   // Emit a special diagnostic for failed member lookups.
2108   // FIXME: computing the declaration context might fail here (?)
2109   if (!SS.isEmpty()) {
2110     Diag(R.getNameLoc(), diag::err_no_member)
2111       << Name << computeDeclContext(SS, false)
2112       << SS.getRange();
2113     return true;
2114   }
2115 
2116   // Give up, we can't recover.
2117   Diag(R.getNameLoc(), diagnostic) << Name;
2118   return true;
2119 }
2120 
2121 /// In Microsoft mode, if we are inside a template class whose parent class has
2122 /// dependent base classes, and we can't resolve an unqualified identifier, then
2123 /// assume the identifier is a member of a dependent base class.  We can only
2124 /// recover successfully in static methods, instance methods, and other contexts
2125 /// where 'this' is available.  This doesn't precisely match MSVC's
2126 /// instantiation model, but it's close enough.
2127 static Expr *
2128 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2129                                DeclarationNameInfo &NameInfo,
2130                                SourceLocation TemplateKWLoc,
2131                                const TemplateArgumentListInfo *TemplateArgs) {
2132   // Only try to recover from lookup into dependent bases in static methods or
2133   // contexts where 'this' is available.
2134   QualType ThisType = S.getCurrentThisType();
2135   const CXXRecordDecl *RD = nullptr;
2136   if (!ThisType.isNull())
2137     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2138   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2139     RD = MD->getParent();
2140   if (!RD || !RD->hasAnyDependentBases())
2141     return nullptr;
2142 
2143   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2144   // is available, suggest inserting 'this->' as a fixit.
2145   SourceLocation Loc = NameInfo.getLoc();
2146   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2147   DB << NameInfo.getName() << RD;
2148 
2149   if (!ThisType.isNull()) {
2150     DB << FixItHint::CreateInsertion(Loc, "this->");
2151     return CXXDependentScopeMemberExpr::Create(
2152         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2153         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2154         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2155   }
2156 
2157   // Synthesize a fake NNS that points to the derived class.  This will
2158   // perform name lookup during template instantiation.
2159   CXXScopeSpec SS;
2160   auto *NNS =
2161       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2162   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2163   return DependentScopeDeclRefExpr::Create(
2164       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2165       TemplateArgs);
2166 }
2167 
2168 ExprResult
2169 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2170                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2171                         bool HasTrailingLParen, bool IsAddressOfOperand,
2172                         CorrectionCandidateCallback *CCC,
2173                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2174   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2175          "cannot be direct & operand and have a trailing lparen");
2176   if (SS.isInvalid())
2177     return ExprError();
2178 
2179   TemplateArgumentListInfo TemplateArgsBuffer;
2180 
2181   // Decompose the UnqualifiedId into the following data.
2182   DeclarationNameInfo NameInfo;
2183   const TemplateArgumentListInfo *TemplateArgs;
2184   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2185 
2186   DeclarationName Name = NameInfo.getName();
2187   IdentifierInfo *II = Name.getAsIdentifierInfo();
2188   SourceLocation NameLoc = NameInfo.getLoc();
2189 
2190   if (II && II->isEditorPlaceholder()) {
2191     // FIXME: When typed placeholders are supported we can create a typed
2192     // placeholder expression node.
2193     return ExprError();
2194   }
2195 
2196   // C++ [temp.dep.expr]p3:
2197   //   An id-expression is type-dependent if it contains:
2198   //     -- an identifier that was declared with a dependent type,
2199   //        (note: handled after lookup)
2200   //     -- a template-id that is dependent,
2201   //        (note: handled in BuildTemplateIdExpr)
2202   //     -- a conversion-function-id that specifies a dependent type,
2203   //     -- a nested-name-specifier that contains a class-name that
2204   //        names a dependent type.
2205   // Determine whether this is a member of an unknown specialization;
2206   // we need to handle these differently.
2207   bool DependentID = false;
2208   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2209       Name.getCXXNameType()->isDependentType()) {
2210     DependentID = true;
2211   } else if (SS.isSet()) {
2212     if (DeclContext *DC = computeDeclContext(SS, false)) {
2213       if (RequireCompleteDeclContext(SS, DC))
2214         return ExprError();
2215     } else {
2216       DependentID = true;
2217     }
2218   }
2219 
2220   if (DependentID)
2221     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2222                                       IsAddressOfOperand, TemplateArgs);
2223 
2224   // Perform the required lookup.
2225   LookupResult R(*this, NameInfo,
2226                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2227                      ? LookupObjCImplicitSelfParam
2228                      : LookupOrdinaryName);
2229   if (TemplateKWLoc.isValid() || TemplateArgs) {
2230     // Lookup the template name again to correctly establish the context in
2231     // which it was found. This is really unfortunate as we already did the
2232     // lookup to determine that it was a template name in the first place. If
2233     // this becomes a performance hit, we can work harder to preserve those
2234     // results until we get here but it's likely not worth it.
2235     bool MemberOfUnknownSpecialization;
2236     AssumedTemplateKind AssumedTemplate;
2237     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2238                            MemberOfUnknownSpecialization, TemplateKWLoc,
2239                            &AssumedTemplate))
2240       return ExprError();
2241 
2242     if (MemberOfUnknownSpecialization ||
2243         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246   } else {
2247     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2248     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2249 
2250     // If the result might be in a dependent base class, this is a dependent
2251     // id-expression.
2252     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2253       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2254                                         IsAddressOfOperand, TemplateArgs);
2255 
2256     // If this reference is in an Objective-C method, then we need to do
2257     // some special Objective-C lookup, too.
2258     if (IvarLookupFollowUp) {
2259       ExprResult E(LookupInObjCMethod(R, S, II, true));
2260       if (E.isInvalid())
2261         return ExprError();
2262 
2263       if (Expr *Ex = E.getAs<Expr>())
2264         return Ex;
2265     }
2266   }
2267 
2268   if (R.isAmbiguous())
2269     return ExprError();
2270 
2271   // This could be an implicitly declared function reference (legal in C90,
2272   // extension in C99, forbidden in C++).
2273   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2274     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2275     if (D) R.addDecl(D);
2276   }
2277 
2278   // Determine whether this name might be a candidate for
2279   // argument-dependent lookup.
2280   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2281 
2282   if (R.empty() && !ADL) {
2283     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2284       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2285                                                    TemplateKWLoc, TemplateArgs))
2286         return E;
2287     }
2288 
2289     // Don't diagnose an empty lookup for inline assembly.
2290     if (IsInlineAsmIdentifier)
2291       return ExprError();
2292 
2293     // If this name wasn't predeclared and if this is not a function
2294     // call, diagnose the problem.
2295     TypoExpr *TE = nullptr;
2296     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2297                                                        : nullptr);
2298     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2299     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2300            "Typo correction callback misconfigured");
2301     if (CCC) {
2302       // Make sure the callback knows what the typo being diagnosed is.
2303       CCC->setTypoName(II);
2304       if (SS.isValid())
2305         CCC->setTypoNNS(SS.getScopeRep());
2306     }
2307     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2308     // a template name, but we happen to have always already looked up the name
2309     // before we get here if it must be a template name.
2310     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2311                             None, &TE)) {
2312       if (TE && KeywordReplacement) {
2313         auto &State = getTypoExprState(TE);
2314         auto BestTC = State.Consumer->getNextCorrection();
2315         if (BestTC.isKeyword()) {
2316           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2317           if (State.DiagHandler)
2318             State.DiagHandler(BestTC);
2319           KeywordReplacement->startToken();
2320           KeywordReplacement->setKind(II->getTokenID());
2321           KeywordReplacement->setIdentifierInfo(II);
2322           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2323           // Clean up the state associated with the TypoExpr, since it has
2324           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2325           clearDelayedTypo(TE);
2326           // Signal that a correction to a keyword was performed by returning a
2327           // valid-but-null ExprResult.
2328           return (Expr*)nullptr;
2329         }
2330         State.Consumer->resetCorrectionStream();
2331       }
2332       return TE ? TE : ExprError();
2333     }
2334 
2335     assert(!R.empty() &&
2336            "DiagnoseEmptyLookup returned false but added no results");
2337 
2338     // If we found an Objective-C instance variable, let
2339     // LookupInObjCMethod build the appropriate expression to
2340     // reference the ivar.
2341     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2342       R.clear();
2343       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2344       // In a hopelessly buggy code, Objective-C instance variable
2345       // lookup fails and no expression will be built to reference it.
2346       if (!E.isInvalid() && !E.get())
2347         return ExprError();
2348       return E;
2349     }
2350   }
2351 
2352   // This is guaranteed from this point on.
2353   assert(!R.empty() || ADL);
2354 
2355   // Check whether this might be a C++ implicit instance member access.
2356   // C++ [class.mfct.non-static]p3:
2357   //   When an id-expression that is not part of a class member access
2358   //   syntax and not used to form a pointer to member is used in the
2359   //   body of a non-static member function of class X, if name lookup
2360   //   resolves the name in the id-expression to a non-static non-type
2361   //   member of some class C, the id-expression is transformed into a
2362   //   class member access expression using (*this) as the
2363   //   postfix-expression to the left of the . operator.
2364   //
2365   // But we don't actually need to do this for '&' operands if R
2366   // resolved to a function or overloaded function set, because the
2367   // expression is ill-formed if it actually works out to be a
2368   // non-static member function:
2369   //
2370   // C++ [expr.ref]p4:
2371   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2372   //   [t]he expression can be used only as the left-hand operand of a
2373   //   member function call.
2374   //
2375   // There are other safeguards against such uses, but it's important
2376   // to get this right here so that we don't end up making a
2377   // spuriously dependent expression if we're inside a dependent
2378   // instance method.
2379   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2380     bool MightBeImplicitMember;
2381     if (!IsAddressOfOperand)
2382       MightBeImplicitMember = true;
2383     else if (!SS.isEmpty())
2384       MightBeImplicitMember = false;
2385     else if (R.isOverloadedResult())
2386       MightBeImplicitMember = false;
2387     else if (R.isUnresolvableResult())
2388       MightBeImplicitMember = true;
2389     else
2390       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2391                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2392                               isa<MSPropertyDecl>(R.getFoundDecl());
2393 
2394     if (MightBeImplicitMember)
2395       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2396                                              R, TemplateArgs, S);
2397   }
2398 
2399   if (TemplateArgs || TemplateKWLoc.isValid()) {
2400 
2401     // In C++1y, if this is a variable template id, then check it
2402     // in BuildTemplateIdExpr().
2403     // The single lookup result must be a variable template declaration.
2404     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2405         Id.TemplateId->Kind == TNK_Var_template) {
2406       assert(R.getAsSingle<VarTemplateDecl>() &&
2407              "There should only be one declaration found.");
2408     }
2409 
2410     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2411   }
2412 
2413   return BuildDeclarationNameExpr(SS, R, ADL);
2414 }
2415 
2416 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2417 /// declaration name, generally during template instantiation.
2418 /// There's a large number of things which don't need to be done along
2419 /// this path.
2420 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2421     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2422     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2423   DeclContext *DC = computeDeclContext(SS, false);
2424   if (!DC)
2425     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2426                                      NameInfo, /*TemplateArgs=*/nullptr);
2427 
2428   if (RequireCompleteDeclContext(SS, DC))
2429     return ExprError();
2430 
2431   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2432   LookupQualifiedName(R, DC);
2433 
2434   if (R.isAmbiguous())
2435     return ExprError();
2436 
2437   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2438     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2439                                      NameInfo, /*TemplateArgs=*/nullptr);
2440 
2441   if (R.empty()) {
2442     Diag(NameInfo.getLoc(), diag::err_no_member)
2443       << NameInfo.getName() << DC << SS.getRange();
2444     return ExprError();
2445   }
2446 
2447   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2448     // Diagnose a missing typename if this resolved unambiguously to a type in
2449     // a dependent context.  If we can recover with a type, downgrade this to
2450     // a warning in Microsoft compatibility mode.
2451     unsigned DiagID = diag::err_typename_missing;
2452     if (RecoveryTSI && getLangOpts().MSVCCompat)
2453       DiagID = diag::ext_typename_missing;
2454     SourceLocation Loc = SS.getBeginLoc();
2455     auto D = Diag(Loc, DiagID);
2456     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2457       << SourceRange(Loc, NameInfo.getEndLoc());
2458 
2459     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2460     // context.
2461     if (!RecoveryTSI)
2462       return ExprError();
2463 
2464     // Only issue the fixit if we're prepared to recover.
2465     D << FixItHint::CreateInsertion(Loc, "typename ");
2466 
2467     // Recover by pretending this was an elaborated type.
2468     QualType Ty = Context.getTypeDeclType(TD);
2469     TypeLocBuilder TLB;
2470     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2471 
2472     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2473     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2474     QTL.setElaboratedKeywordLoc(SourceLocation());
2475     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2476 
2477     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2478 
2479     return ExprEmpty();
2480   }
2481 
2482   // Defend against this resolving to an implicit member access. We usually
2483   // won't get here if this might be a legitimate a class member (we end up in
2484   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2485   // a pointer-to-member or in an unevaluated context in C++11.
2486   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2487     return BuildPossibleImplicitMemberExpr(SS,
2488                                            /*TemplateKWLoc=*/SourceLocation(),
2489                                            R, /*TemplateArgs=*/nullptr, S);
2490 
2491   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2492 }
2493 
2494 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2495 /// detected that we're currently inside an ObjC method.  Perform some
2496 /// additional lookup.
2497 ///
2498 /// Ideally, most of this would be done by lookup, but there's
2499 /// actually quite a lot of extra work involved.
2500 ///
2501 /// Returns a null sentinel to indicate trivial success.
2502 ExprResult
2503 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2504                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2505   SourceLocation Loc = Lookup.getNameLoc();
2506   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2507 
2508   // Check for error condition which is already reported.
2509   if (!CurMethod)
2510     return ExprError();
2511 
2512   // There are two cases to handle here.  1) scoped lookup could have failed,
2513   // in which case we should look for an ivar.  2) scoped lookup could have
2514   // found a decl, but that decl is outside the current instance method (i.e.
2515   // a global variable).  In these two cases, we do a lookup for an ivar with
2516   // this name, if the lookup sucedes, we replace it our current decl.
2517 
2518   // If we're in a class method, we don't normally want to look for
2519   // ivars.  But if we don't find anything else, and there's an
2520   // ivar, that's an error.
2521   bool IsClassMethod = CurMethod->isClassMethod();
2522 
2523   bool LookForIvars;
2524   if (Lookup.empty())
2525     LookForIvars = true;
2526   else if (IsClassMethod)
2527     LookForIvars = false;
2528   else
2529     LookForIvars = (Lookup.isSingleResult() &&
2530                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2531   ObjCInterfaceDecl *IFace = nullptr;
2532   if (LookForIvars) {
2533     IFace = CurMethod->getClassInterface();
2534     ObjCInterfaceDecl *ClassDeclared;
2535     ObjCIvarDecl *IV = nullptr;
2536     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2537       // Diagnose using an ivar in a class method.
2538       if (IsClassMethod)
2539         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540                          << IV->getDeclName());
2541 
2542       // If we're referencing an invalid decl, just return this as a silent
2543       // error node.  The error diagnostic was already emitted on the decl.
2544       if (IV->isInvalidDecl())
2545         return ExprError();
2546 
2547       // Check if referencing a field with __attribute__((deprecated)).
2548       if (DiagnoseUseOfDecl(IV, Loc))
2549         return ExprError();
2550 
2551       // Diagnose the use of an ivar outside of the declaring class.
2552       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2553           !declaresSameEntity(ClassDeclared, IFace) &&
2554           !getLangOpts().DebuggerSupport)
2555         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2556 
2557       // FIXME: This should use a new expr for a direct reference, don't
2558       // turn this into Self->ivar, just return a BareIVarExpr or something.
2559       IdentifierInfo &II = Context.Idents.get("self");
2560       UnqualifiedId SelfName;
2561       SelfName.setIdentifier(&II, SourceLocation());
2562       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2563       CXXScopeSpec SelfScopeSpec;
2564       SourceLocation TemplateKWLoc;
2565       ExprResult SelfExpr =
2566           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2567                             /*HasTrailingLParen=*/false,
2568                             /*IsAddressOfOperand=*/false);
2569       if (SelfExpr.isInvalid())
2570         return ExprError();
2571 
2572       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2573       if (SelfExpr.isInvalid())
2574         return ExprError();
2575 
2576       MarkAnyDeclReferenced(Loc, IV, true);
2577 
2578       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2579       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2580           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2581         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2582 
2583       ObjCIvarRefExpr *Result = new (Context)
2584           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2585                           IV->getLocation(), SelfExpr.get(), true, true);
2586 
2587       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2588         if (!isUnevaluatedContext() &&
2589             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2590           getCurFunction()->recordUseOfWeak(Result);
2591       }
2592       if (getLangOpts().ObjCAutoRefCount)
2593         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2594           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2595 
2596       return Result;
2597     }
2598   } else if (CurMethod->isInstanceMethod()) {
2599     // We should warn if a local variable hides an ivar.
2600     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2601       ObjCInterfaceDecl *ClassDeclared;
2602       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2603         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2604             declaresSameEntity(IFace, ClassDeclared))
2605           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2606       }
2607     }
2608   } else if (Lookup.isSingleResult() &&
2609              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2610     // If accessing a stand-alone ivar in a class method, this is an error.
2611     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2612       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2613                        << IV->getDeclName());
2614   }
2615 
2616   if (Lookup.empty() && II && AllowBuiltinCreation) {
2617     // FIXME. Consolidate this with similar code in LookupName.
2618     if (unsigned BuiltinID = II->getBuiltinID()) {
2619       if (!(getLangOpts().CPlusPlus &&
2620             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2621         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2622                                            S, Lookup.isForRedeclaration(),
2623                                            Lookup.getNameLoc());
2624         if (D) Lookup.addDecl(D);
2625       }
2626     }
2627   }
2628   // Sentinel value saying that we didn't do anything special.
2629   return ExprResult((Expr *)nullptr);
2630 }
2631 
2632 /// Cast a base object to a member's actual type.
2633 ///
2634 /// Logically this happens in three phases:
2635 ///
2636 /// * First we cast from the base type to the naming class.
2637 ///   The naming class is the class into which we were looking
2638 ///   when we found the member;  it's the qualifier type if a
2639 ///   qualifier was provided, and otherwise it's the base type.
2640 ///
2641 /// * Next we cast from the naming class to the declaring class.
2642 ///   If the member we found was brought into a class's scope by
2643 ///   a using declaration, this is that class;  otherwise it's
2644 ///   the class declaring the member.
2645 ///
2646 /// * Finally we cast from the declaring class to the "true"
2647 ///   declaring class of the member.  This conversion does not
2648 ///   obey access control.
2649 ExprResult
2650 Sema::PerformObjectMemberConversion(Expr *From,
2651                                     NestedNameSpecifier *Qualifier,
2652                                     NamedDecl *FoundDecl,
2653                                     NamedDecl *Member) {
2654   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2655   if (!RD)
2656     return From;
2657 
2658   QualType DestRecordType;
2659   QualType DestType;
2660   QualType FromRecordType;
2661   QualType FromType = From->getType();
2662   bool PointerConversions = false;
2663   if (isa<FieldDecl>(Member)) {
2664     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2665     auto FromPtrType = FromType->getAs<PointerType>();
2666     DestRecordType = Context.getAddrSpaceQualType(
2667         DestRecordType, FromPtrType
2668                             ? FromType->getPointeeType().getAddressSpace()
2669                             : FromType.getAddressSpace());
2670 
2671     if (FromPtrType) {
2672       DestType = Context.getPointerType(DestRecordType);
2673       FromRecordType = FromPtrType->getPointeeType();
2674       PointerConversions = true;
2675     } else {
2676       DestType = DestRecordType;
2677       FromRecordType = FromType;
2678     }
2679   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2680     if (Method->isStatic())
2681       return From;
2682 
2683     DestType = Method->getThisType();
2684     DestRecordType = DestType->getPointeeType();
2685 
2686     if (FromType->getAs<PointerType>()) {
2687       FromRecordType = FromType->getPointeeType();
2688       PointerConversions = true;
2689     } else {
2690       FromRecordType = FromType;
2691       DestType = DestRecordType;
2692     }
2693   } else {
2694     // No conversion necessary.
2695     return From;
2696   }
2697 
2698   if (DestType->isDependentType() || FromType->isDependentType())
2699     return From;
2700 
2701   // If the unqualified types are the same, no conversion is necessary.
2702   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2703     return From;
2704 
2705   SourceRange FromRange = From->getSourceRange();
2706   SourceLocation FromLoc = FromRange.getBegin();
2707 
2708   ExprValueKind VK = From->getValueKind();
2709 
2710   // C++ [class.member.lookup]p8:
2711   //   [...] Ambiguities can often be resolved by qualifying a name with its
2712   //   class name.
2713   //
2714   // If the member was a qualified name and the qualified referred to a
2715   // specific base subobject type, we'll cast to that intermediate type
2716   // first and then to the object in which the member is declared. That allows
2717   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2718   //
2719   //   class Base { public: int x; };
2720   //   class Derived1 : public Base { };
2721   //   class Derived2 : public Base { };
2722   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2723   //
2724   //   void VeryDerived::f() {
2725   //     x = 17; // error: ambiguous base subobjects
2726   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2727   //   }
2728   if (Qualifier && Qualifier->getAsType()) {
2729     QualType QType = QualType(Qualifier->getAsType(), 0);
2730     assert(QType->isRecordType() && "lookup done with non-record type");
2731 
2732     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2733 
2734     // In C++98, the qualifier type doesn't actually have to be a base
2735     // type of the object type, in which case we just ignore it.
2736     // Otherwise build the appropriate casts.
2737     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2738       CXXCastPath BasePath;
2739       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2740                                        FromLoc, FromRange, &BasePath))
2741         return ExprError();
2742 
2743       if (PointerConversions)
2744         QType = Context.getPointerType(QType);
2745       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2746                                VK, &BasePath).get();
2747 
2748       FromType = QType;
2749       FromRecordType = QRecordType;
2750 
2751       // If the qualifier type was the same as the destination type,
2752       // we're done.
2753       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2754         return From;
2755     }
2756   }
2757 
2758   bool IgnoreAccess = false;
2759 
2760   // If we actually found the member through a using declaration, cast
2761   // down to the using declaration's type.
2762   //
2763   // Pointer equality is fine here because only one declaration of a
2764   // class ever has member declarations.
2765   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2766     assert(isa<UsingShadowDecl>(FoundDecl));
2767     QualType URecordType = Context.getTypeDeclType(
2768                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2769 
2770     // We only need to do this if the naming-class to declaring-class
2771     // conversion is non-trivial.
2772     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2773       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2774       CXXCastPath BasePath;
2775       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2776                                        FromLoc, FromRange, &BasePath))
2777         return ExprError();
2778 
2779       QualType UType = URecordType;
2780       if (PointerConversions)
2781         UType = Context.getPointerType(UType);
2782       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2783                                VK, &BasePath).get();
2784       FromType = UType;
2785       FromRecordType = URecordType;
2786     }
2787 
2788     // We don't do access control for the conversion from the
2789     // declaring class to the true declaring class.
2790     IgnoreAccess = true;
2791   }
2792 
2793   CXXCastPath BasePath;
2794   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2795                                    FromLoc, FromRange, &BasePath,
2796                                    IgnoreAccess))
2797     return ExprError();
2798 
2799   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2800                            VK, &BasePath);
2801 }
2802 
2803 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2804                                       const LookupResult &R,
2805                                       bool HasTrailingLParen) {
2806   // Only when used directly as the postfix-expression of a call.
2807   if (!HasTrailingLParen)
2808     return false;
2809 
2810   // Never if a scope specifier was provided.
2811   if (SS.isSet())
2812     return false;
2813 
2814   // Only in C++ or ObjC++.
2815   if (!getLangOpts().CPlusPlus)
2816     return false;
2817 
2818   // Turn off ADL when we find certain kinds of declarations during
2819   // normal lookup:
2820   for (NamedDecl *D : R) {
2821     // C++0x [basic.lookup.argdep]p3:
2822     //     -- a declaration of a class member
2823     // Since using decls preserve this property, we check this on the
2824     // original decl.
2825     if (D->isCXXClassMember())
2826       return false;
2827 
2828     // C++0x [basic.lookup.argdep]p3:
2829     //     -- a block-scope function declaration that is not a
2830     //        using-declaration
2831     // NOTE: we also trigger this for function templates (in fact, we
2832     // don't check the decl type at all, since all other decl types
2833     // turn off ADL anyway).
2834     if (isa<UsingShadowDecl>(D))
2835       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2836     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2837       return false;
2838 
2839     // C++0x [basic.lookup.argdep]p3:
2840     //     -- a declaration that is neither a function or a function
2841     //        template
2842     // And also for builtin functions.
2843     if (isa<FunctionDecl>(D)) {
2844       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2845 
2846       // But also builtin functions.
2847       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2848         return false;
2849     } else if (!isa<FunctionTemplateDecl>(D))
2850       return false;
2851   }
2852 
2853   return true;
2854 }
2855 
2856 
2857 /// Diagnoses obvious problems with the use of the given declaration
2858 /// as an expression.  This is only actually called for lookups that
2859 /// were not overloaded, and it doesn't promise that the declaration
2860 /// will in fact be used.
2861 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2862   if (D->isInvalidDecl())
2863     return true;
2864 
2865   if (isa<TypedefNameDecl>(D)) {
2866     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2867     return true;
2868   }
2869 
2870   if (isa<ObjCInterfaceDecl>(D)) {
2871     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2872     return true;
2873   }
2874 
2875   if (isa<NamespaceDecl>(D)) {
2876     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2877     return true;
2878   }
2879 
2880   return false;
2881 }
2882 
2883 // Certain multiversion types should be treated as overloaded even when there is
2884 // only one result.
2885 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2886   assert(R.isSingleResult() && "Expected only a single result");
2887   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2888   return FD &&
2889          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2890 }
2891 
2892 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2893                                           LookupResult &R, bool NeedsADL,
2894                                           bool AcceptInvalidDecl) {
2895   // If this is a single, fully-resolved result and we don't need ADL,
2896   // just build an ordinary singleton decl ref.
2897   if (!NeedsADL && R.isSingleResult() &&
2898       !R.getAsSingle<FunctionTemplateDecl>() &&
2899       !ShouldLookupResultBeMultiVersionOverload(R))
2900     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2901                                     R.getRepresentativeDecl(), nullptr,
2902                                     AcceptInvalidDecl);
2903 
2904   // We only need to check the declaration if there's exactly one
2905   // result, because in the overloaded case the results can only be
2906   // functions and function templates.
2907   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2908       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2909     return ExprError();
2910 
2911   // Otherwise, just build an unresolved lookup expression.  Suppress
2912   // any lookup-related diagnostics; we'll hash these out later, when
2913   // we've picked a target.
2914   R.suppressDiagnostics();
2915 
2916   UnresolvedLookupExpr *ULE
2917     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2918                                    SS.getWithLocInContext(Context),
2919                                    R.getLookupNameInfo(),
2920                                    NeedsADL, R.isOverloadedResult(),
2921                                    R.begin(), R.end());
2922 
2923   return ULE;
2924 }
2925 
2926 static void
2927 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2928                                    ValueDecl *var, DeclContext *DC);
2929 
2930 /// Complete semantic analysis for a reference to the given declaration.
2931 ExprResult Sema::BuildDeclarationNameExpr(
2932     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2933     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2934     bool AcceptInvalidDecl) {
2935   assert(D && "Cannot refer to a NULL declaration");
2936   assert(!isa<FunctionTemplateDecl>(D) &&
2937          "Cannot refer unambiguously to a function template");
2938 
2939   SourceLocation Loc = NameInfo.getLoc();
2940   if (CheckDeclInExpr(*this, Loc, D))
2941     return ExprError();
2942 
2943   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2944     // Specifically diagnose references to class templates that are missing
2945     // a template argument list.
2946     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2947     return ExprError();
2948   }
2949 
2950   // Make sure that we're referring to a value.
2951   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2952   if (!VD) {
2953     Diag(Loc, diag::err_ref_non_value)
2954       << D << SS.getRange();
2955     Diag(D->getLocation(), diag::note_declared_at);
2956     return ExprError();
2957   }
2958 
2959   // Check whether this declaration can be used. Note that we suppress
2960   // this check when we're going to perform argument-dependent lookup
2961   // on this function name, because this might not be the function
2962   // that overload resolution actually selects.
2963   if (DiagnoseUseOfDecl(VD, Loc))
2964     return ExprError();
2965 
2966   // Only create DeclRefExpr's for valid Decl's.
2967   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2968     return ExprError();
2969 
2970   // Handle members of anonymous structs and unions.  If we got here,
2971   // and the reference is to a class member indirect field, then this
2972   // must be the subject of a pointer-to-member expression.
2973   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2974     if (!indirectField->isCXXClassMember())
2975       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2976                                                       indirectField);
2977 
2978   {
2979     QualType type = VD->getType();
2980     if (type.isNull())
2981       return ExprError();
2982     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2983       // C++ [except.spec]p17:
2984       //   An exception-specification is considered to be needed when:
2985       //   - in an expression, the function is the unique lookup result or
2986       //     the selected member of a set of overloaded functions.
2987       ResolveExceptionSpec(Loc, FPT);
2988       type = VD->getType();
2989     }
2990     ExprValueKind valueKind = VK_RValue;
2991 
2992     switch (D->getKind()) {
2993     // Ignore all the non-ValueDecl kinds.
2994 #define ABSTRACT_DECL(kind)
2995 #define VALUE(type, base)
2996 #define DECL(type, base) \
2997     case Decl::type:
2998 #include "clang/AST/DeclNodes.inc"
2999       llvm_unreachable("invalid value decl kind");
3000 
3001     // These shouldn't make it here.
3002     case Decl::ObjCAtDefsField:
3003       llvm_unreachable("forming non-member reference to ivar?");
3004 
3005     // Enum constants are always r-values and never references.
3006     // Unresolved using declarations are dependent.
3007     case Decl::EnumConstant:
3008     case Decl::UnresolvedUsingValue:
3009     case Decl::OMPDeclareReduction:
3010     case Decl::OMPDeclareMapper:
3011       valueKind = VK_RValue;
3012       break;
3013 
3014     // Fields and indirect fields that got here must be for
3015     // pointer-to-member expressions; we just call them l-values for
3016     // internal consistency, because this subexpression doesn't really
3017     // exist in the high-level semantics.
3018     case Decl::Field:
3019     case Decl::IndirectField:
3020     case Decl::ObjCIvar:
3021       assert(getLangOpts().CPlusPlus &&
3022              "building reference to field in C?");
3023 
3024       // These can't have reference type in well-formed programs, but
3025       // for internal consistency we do this anyway.
3026       type = type.getNonReferenceType();
3027       valueKind = VK_LValue;
3028       break;
3029 
3030     // Non-type template parameters are either l-values or r-values
3031     // depending on the type.
3032     case Decl::NonTypeTemplateParm: {
3033       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3034         type = reftype->getPointeeType();
3035         valueKind = VK_LValue; // even if the parameter is an r-value reference
3036         break;
3037       }
3038 
3039       // For non-references, we need to strip qualifiers just in case
3040       // the template parameter was declared as 'const int' or whatever.
3041       valueKind = VK_RValue;
3042       type = type.getUnqualifiedType();
3043       break;
3044     }
3045 
3046     case Decl::Var:
3047     case Decl::VarTemplateSpecialization:
3048     case Decl::VarTemplatePartialSpecialization:
3049     case Decl::Decomposition:
3050     case Decl::OMPCapturedExpr:
3051       // In C, "extern void blah;" is valid and is an r-value.
3052       if (!getLangOpts().CPlusPlus &&
3053           !type.hasQualifiers() &&
3054           type->isVoidType()) {
3055         valueKind = VK_RValue;
3056         break;
3057       }
3058       LLVM_FALLTHROUGH;
3059 
3060     case Decl::ImplicitParam:
3061     case Decl::ParmVar: {
3062       // These are always l-values.
3063       valueKind = VK_LValue;
3064       type = type.getNonReferenceType();
3065 
3066       // FIXME: Does the addition of const really only apply in
3067       // potentially-evaluated contexts? Since the variable isn't actually
3068       // captured in an unevaluated context, it seems that the answer is no.
3069       if (!isUnevaluatedContext()) {
3070         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3071         if (!CapturedType.isNull())
3072           type = CapturedType;
3073       }
3074 
3075       break;
3076     }
3077 
3078     case Decl::Binding: {
3079       // These are always lvalues.
3080       valueKind = VK_LValue;
3081       type = type.getNonReferenceType();
3082       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3083       // decides how that's supposed to work.
3084       auto *BD = cast<BindingDecl>(VD);
3085       if (BD->getDeclContext() != CurContext) {
3086         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3087         if (DD && DD->hasLocalStorage())
3088           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3089       }
3090       break;
3091     }
3092 
3093     case Decl::Function: {
3094       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3095         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3096           type = Context.BuiltinFnTy;
3097           valueKind = VK_RValue;
3098           break;
3099         }
3100       }
3101 
3102       const FunctionType *fty = type->castAs<FunctionType>();
3103 
3104       // If we're referring to a function with an __unknown_anytype
3105       // result type, make the entire expression __unknown_anytype.
3106       if (fty->getReturnType() == Context.UnknownAnyTy) {
3107         type = Context.UnknownAnyTy;
3108         valueKind = VK_RValue;
3109         break;
3110       }
3111 
3112       // Functions are l-values in C++.
3113       if (getLangOpts().CPlusPlus) {
3114         valueKind = VK_LValue;
3115         break;
3116       }
3117 
3118       // C99 DR 316 says that, if a function type comes from a
3119       // function definition (without a prototype), that type is only
3120       // used for checking compatibility. Therefore, when referencing
3121       // the function, we pretend that we don't have the full function
3122       // type.
3123       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3124           isa<FunctionProtoType>(fty))
3125         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3126                                               fty->getExtInfo());
3127 
3128       // Functions are r-values in C.
3129       valueKind = VK_RValue;
3130       break;
3131     }
3132 
3133     case Decl::CXXDeductionGuide:
3134       llvm_unreachable("building reference to deduction guide");
3135 
3136     case Decl::MSProperty:
3137       valueKind = VK_LValue;
3138       break;
3139 
3140     case Decl::CXXMethod:
3141       // If we're referring to a method with an __unknown_anytype
3142       // result type, make the entire expression __unknown_anytype.
3143       // This should only be possible with a type written directly.
3144       if (const FunctionProtoType *proto
3145             = dyn_cast<FunctionProtoType>(VD->getType()))
3146         if (proto->getReturnType() == Context.UnknownAnyTy) {
3147           type = Context.UnknownAnyTy;
3148           valueKind = VK_RValue;
3149           break;
3150         }
3151 
3152       // C++ methods are l-values if static, r-values if non-static.
3153       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3154         valueKind = VK_LValue;
3155         break;
3156       }
3157       LLVM_FALLTHROUGH;
3158 
3159     case Decl::CXXConversion:
3160     case Decl::CXXDestructor:
3161     case Decl::CXXConstructor:
3162       valueKind = VK_RValue;
3163       break;
3164     }
3165 
3166     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3167                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3168                             TemplateArgs);
3169   }
3170 }
3171 
3172 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3173                                     SmallString<32> &Target) {
3174   Target.resize(CharByteWidth * (Source.size() + 1));
3175   char *ResultPtr = &Target[0];
3176   const llvm::UTF8 *ErrorPtr;
3177   bool success =
3178       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3179   (void)success;
3180   assert(success);
3181   Target.resize(ResultPtr - &Target[0]);
3182 }
3183 
3184 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3185                                      PredefinedExpr::IdentKind IK) {
3186   // Pick the current block, lambda, captured statement or function.
3187   Decl *currentDecl = nullptr;
3188   if (const BlockScopeInfo *BSI = getCurBlock())
3189     currentDecl = BSI->TheDecl;
3190   else if (const LambdaScopeInfo *LSI = getCurLambda())
3191     currentDecl = LSI->CallOperator;
3192   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3193     currentDecl = CSI->TheCapturedDecl;
3194   else
3195     currentDecl = getCurFunctionOrMethodDecl();
3196 
3197   if (!currentDecl) {
3198     Diag(Loc, diag::ext_predef_outside_function);
3199     currentDecl = Context.getTranslationUnitDecl();
3200   }
3201 
3202   QualType ResTy;
3203   StringLiteral *SL = nullptr;
3204   if (cast<DeclContext>(currentDecl)->isDependentContext())
3205     ResTy = Context.DependentTy;
3206   else {
3207     // Pre-defined identifiers are of type char[x], where x is the length of
3208     // the string.
3209     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3210     unsigned Length = Str.length();
3211 
3212     llvm::APInt LengthI(32, Length + 1);
3213     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3214       ResTy =
3215           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3216       SmallString<32> RawChars;
3217       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3218                               Str, RawChars);
3219       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3220                                            /*IndexTypeQuals*/ 0);
3221       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3222                                  /*Pascal*/ false, ResTy, Loc);
3223     } else {
3224       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3225       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3226                                            /*IndexTypeQuals*/ 0);
3227       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3228                                  /*Pascal*/ false, ResTy, Loc);
3229     }
3230   }
3231 
3232   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3233 }
3234 
3235 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3236   PredefinedExpr::IdentKind IK;
3237 
3238   switch (Kind) {
3239   default: llvm_unreachable("Unknown simple primary expr!");
3240   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3241   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3242   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3243   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3244   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3245   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3246   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3247   }
3248 
3249   return BuildPredefinedExpr(Loc, IK);
3250 }
3251 
3252 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3253   SmallString<16> CharBuffer;
3254   bool Invalid = false;
3255   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3256   if (Invalid)
3257     return ExprError();
3258 
3259   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3260                             PP, Tok.getKind());
3261   if (Literal.hadError())
3262     return ExprError();
3263 
3264   QualType Ty;
3265   if (Literal.isWide())
3266     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3267   else if (Literal.isUTF8() && getLangOpts().Char8)
3268     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3269   else if (Literal.isUTF16())
3270     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3271   else if (Literal.isUTF32())
3272     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3273   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3274     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3275   else
3276     Ty = Context.CharTy;  // 'x' -> char in C++
3277 
3278   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3279   if (Literal.isWide())
3280     Kind = CharacterLiteral::Wide;
3281   else if (Literal.isUTF16())
3282     Kind = CharacterLiteral::UTF16;
3283   else if (Literal.isUTF32())
3284     Kind = CharacterLiteral::UTF32;
3285   else if (Literal.isUTF8())
3286     Kind = CharacterLiteral::UTF8;
3287 
3288   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3289                                              Tok.getLocation());
3290 
3291   if (Literal.getUDSuffix().empty())
3292     return Lit;
3293 
3294   // We're building a user-defined literal.
3295   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296   SourceLocation UDSuffixLoc =
3297     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299   // Make sure we're allowed user-defined literals here.
3300   if (!UDLScope)
3301     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3302 
3303   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3304   //   operator "" X (ch)
3305   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3306                                         Lit, Tok.getLocation());
3307 }
3308 
3309 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3310   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3311   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3312                                 Context.IntTy, Loc);
3313 }
3314 
3315 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3316                                   QualType Ty, SourceLocation Loc) {
3317   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3318 
3319   using llvm::APFloat;
3320   APFloat Val(Format);
3321 
3322   APFloat::opStatus result = Literal.GetFloatValue(Val);
3323 
3324   // Overflow is always an error, but underflow is only an error if
3325   // we underflowed to zero (APFloat reports denormals as underflow).
3326   if ((result & APFloat::opOverflow) ||
3327       ((result & APFloat::opUnderflow) && Val.isZero())) {
3328     unsigned diagnostic;
3329     SmallString<20> buffer;
3330     if (result & APFloat::opOverflow) {
3331       diagnostic = diag::warn_float_overflow;
3332       APFloat::getLargest(Format).toString(buffer);
3333     } else {
3334       diagnostic = diag::warn_float_underflow;
3335       APFloat::getSmallest(Format).toString(buffer);
3336     }
3337 
3338     S.Diag(Loc, diagnostic)
3339       << Ty
3340       << StringRef(buffer.data(), buffer.size());
3341   }
3342 
3343   bool isExact = (result == APFloat::opOK);
3344   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3345 }
3346 
3347 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3348   assert(E && "Invalid expression");
3349 
3350   if (E->isValueDependent())
3351     return false;
3352 
3353   QualType QT = E->getType();
3354   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3355     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3356     return true;
3357   }
3358 
3359   llvm::APSInt ValueAPS;
3360   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3361 
3362   if (R.isInvalid())
3363     return true;
3364 
3365   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3366   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3367     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3368         << ValueAPS.toString(10) << ValueIsPositive;
3369     return true;
3370   }
3371 
3372   return false;
3373 }
3374 
3375 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3376   // Fast path for a single digit (which is quite common).  A single digit
3377   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3378   if (Tok.getLength() == 1) {
3379     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3380     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3381   }
3382 
3383   SmallString<128> SpellingBuffer;
3384   // NumericLiteralParser wants to overread by one character.  Add padding to
3385   // the buffer in case the token is copied to the buffer.  If getSpelling()
3386   // returns a StringRef to the memory buffer, it should have a null char at
3387   // the EOF, so it is also safe.
3388   SpellingBuffer.resize(Tok.getLength() + 1);
3389 
3390   // Get the spelling of the token, which eliminates trigraphs, etc.
3391   bool Invalid = false;
3392   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3393   if (Invalid)
3394     return ExprError();
3395 
3396   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3397   if (Literal.hadError)
3398     return ExprError();
3399 
3400   if (Literal.hasUDSuffix()) {
3401     // We're building a user-defined literal.
3402     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3403     SourceLocation UDSuffixLoc =
3404       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3405 
3406     // Make sure we're allowed user-defined literals here.
3407     if (!UDLScope)
3408       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3409 
3410     QualType CookedTy;
3411     if (Literal.isFloatingLiteral()) {
3412       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3413       // long double, the literal is treated as a call of the form
3414       //   operator "" X (f L)
3415       CookedTy = Context.LongDoubleTy;
3416     } else {
3417       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3418       // unsigned long long, the literal is treated as a call of the form
3419       //   operator "" X (n ULL)
3420       CookedTy = Context.UnsignedLongLongTy;
3421     }
3422 
3423     DeclarationName OpName =
3424       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3425     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3426     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3427 
3428     SourceLocation TokLoc = Tok.getLocation();
3429 
3430     // Perform literal operator lookup to determine if we're building a raw
3431     // literal or a cooked one.
3432     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3433     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3434                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3435                                   /*AllowStringTemplate*/ false,
3436                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3437     case LOLR_ErrorNoDiagnostic:
3438       // Lookup failure for imaginary constants isn't fatal, there's still the
3439       // GNU extension producing _Complex types.
3440       break;
3441     case LOLR_Error:
3442       return ExprError();
3443     case LOLR_Cooked: {
3444       Expr *Lit;
3445       if (Literal.isFloatingLiteral()) {
3446         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3447       } else {
3448         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3449         if (Literal.GetIntegerValue(ResultVal))
3450           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3451               << /* Unsigned */ 1;
3452         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3453                                      Tok.getLocation());
3454       }
3455       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3456     }
3457 
3458     case LOLR_Raw: {
3459       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3460       // literal is treated as a call of the form
3461       //   operator "" X ("n")
3462       unsigned Length = Literal.getUDSuffixOffset();
3463       QualType StrTy = Context.getConstantArrayType(
3464           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3465           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3466       Expr *Lit = StringLiteral::Create(
3467           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3468           /*Pascal*/false, StrTy, &TokLoc, 1);
3469       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3470     }
3471 
3472     case LOLR_Template: {
3473       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3474       // template), L is treated as a call fo the form
3475       //   operator "" X <'c1', 'c2', ... 'ck'>()
3476       // where n is the source character sequence c1 c2 ... ck.
3477       TemplateArgumentListInfo ExplicitArgs;
3478       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3479       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3480       llvm::APSInt Value(CharBits, CharIsUnsigned);
3481       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3482         Value = TokSpelling[I];
3483         TemplateArgument Arg(Context, Value, Context.CharTy);
3484         TemplateArgumentLocInfo ArgInfo;
3485         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3486       }
3487       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3488                                       &ExplicitArgs);
3489     }
3490     case LOLR_StringTemplate:
3491       llvm_unreachable("unexpected literal operator lookup result");
3492     }
3493   }
3494 
3495   Expr *Res;
3496 
3497   if (Literal.isFixedPointLiteral()) {
3498     QualType Ty;
3499 
3500     if (Literal.isAccum) {
3501       if (Literal.isHalf) {
3502         Ty = Context.ShortAccumTy;
3503       } else if (Literal.isLong) {
3504         Ty = Context.LongAccumTy;
3505       } else {
3506         Ty = Context.AccumTy;
3507       }
3508     } else if (Literal.isFract) {
3509       if (Literal.isHalf) {
3510         Ty = Context.ShortFractTy;
3511       } else if (Literal.isLong) {
3512         Ty = Context.LongFractTy;
3513       } else {
3514         Ty = Context.FractTy;
3515       }
3516     }
3517 
3518     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3519 
3520     bool isSigned = !Literal.isUnsigned;
3521     unsigned scale = Context.getFixedPointScale(Ty);
3522     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3523 
3524     llvm::APInt Val(bit_width, 0, isSigned);
3525     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3526     bool ValIsZero = Val.isNullValue() && !Overflowed;
3527 
3528     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3529     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3530       // Clause 6.4.4 - The value of a constant shall be in the range of
3531       // representable values for its type, with exception for constants of a
3532       // fract type with a value of exactly 1; such a constant shall denote
3533       // the maximal value for the type.
3534       --Val;
3535     else if (Val.ugt(MaxVal) || Overflowed)
3536       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3537 
3538     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3539                                               Tok.getLocation(), scale);
3540   } else if (Literal.isFloatingLiteral()) {
3541     QualType Ty;
3542     if (Literal.isHalf){
3543       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3544         Ty = Context.HalfTy;
3545       else {
3546         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3547         return ExprError();
3548       }
3549     } else if (Literal.isFloat)
3550       Ty = Context.FloatTy;
3551     else if (Literal.isLong)
3552       Ty = Context.LongDoubleTy;
3553     else if (Literal.isFloat16)
3554       Ty = Context.Float16Ty;
3555     else if (Literal.isFloat128)
3556       Ty = Context.Float128Ty;
3557     else
3558       Ty = Context.DoubleTy;
3559 
3560     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3561 
3562     if (Ty == Context.DoubleTy) {
3563       if (getLangOpts().SinglePrecisionConstants) {
3564         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3565         if (BTy->getKind() != BuiltinType::Float) {
3566           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3567         }
3568       } else if (getLangOpts().OpenCL &&
3569                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3570         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3571         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3572         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3573       }
3574     }
3575   } else if (!Literal.isIntegerLiteral()) {
3576     return ExprError();
3577   } else {
3578     QualType Ty;
3579 
3580     // 'long long' is a C99 or C++11 feature.
3581     if (!getLangOpts().C99 && Literal.isLongLong) {
3582       if (getLangOpts().CPlusPlus)
3583         Diag(Tok.getLocation(),
3584              getLangOpts().CPlusPlus11 ?
3585              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3586       else
3587         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3588     }
3589 
3590     // Get the value in the widest-possible width.
3591     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3592     llvm::APInt ResultVal(MaxWidth, 0);
3593 
3594     if (Literal.GetIntegerValue(ResultVal)) {
3595       // If this value didn't fit into uintmax_t, error and force to ull.
3596       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3597           << /* Unsigned */ 1;
3598       Ty = Context.UnsignedLongLongTy;
3599       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3600              "long long is not intmax_t?");
3601     } else {
3602       // If this value fits into a ULL, try to figure out what else it fits into
3603       // according to the rules of C99 6.4.4.1p5.
3604 
3605       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3606       // be an unsigned int.
3607       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3608 
3609       // Check from smallest to largest, picking the smallest type we can.
3610       unsigned Width = 0;
3611 
3612       // Microsoft specific integer suffixes are explicitly sized.
3613       if (Literal.MicrosoftInteger) {
3614         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3615           Width = 8;
3616           Ty = Context.CharTy;
3617         } else {
3618           Width = Literal.MicrosoftInteger;
3619           Ty = Context.getIntTypeForBitwidth(Width,
3620                                              /*Signed=*/!Literal.isUnsigned);
3621         }
3622       }
3623 
3624       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3625         // Are int/unsigned possibilities?
3626         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3627 
3628         // Does it fit in a unsigned int?
3629         if (ResultVal.isIntN(IntSize)) {
3630           // Does it fit in a signed int?
3631           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3632             Ty = Context.IntTy;
3633           else if (AllowUnsigned)
3634             Ty = Context.UnsignedIntTy;
3635           Width = IntSize;
3636         }
3637       }
3638 
3639       // Are long/unsigned long possibilities?
3640       if (Ty.isNull() && !Literal.isLongLong) {
3641         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3642 
3643         // Does it fit in a unsigned long?
3644         if (ResultVal.isIntN(LongSize)) {
3645           // Does it fit in a signed long?
3646           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3647             Ty = Context.LongTy;
3648           else if (AllowUnsigned)
3649             Ty = Context.UnsignedLongTy;
3650           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3651           // is compatible.
3652           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3653             const unsigned LongLongSize =
3654                 Context.getTargetInfo().getLongLongWidth();
3655             Diag(Tok.getLocation(),
3656                  getLangOpts().CPlusPlus
3657                      ? Literal.isLong
3658                            ? diag::warn_old_implicitly_unsigned_long_cxx
3659                            : /*C++98 UB*/ diag::
3660                                  ext_old_implicitly_unsigned_long_cxx
3661                      : diag::warn_old_implicitly_unsigned_long)
3662                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3663                                             : /*will be ill-formed*/ 1);
3664             Ty = Context.UnsignedLongTy;
3665           }
3666           Width = LongSize;
3667         }
3668       }
3669 
3670       // Check long long if needed.
3671       if (Ty.isNull()) {
3672         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3673 
3674         // Does it fit in a unsigned long long?
3675         if (ResultVal.isIntN(LongLongSize)) {
3676           // Does it fit in a signed long long?
3677           // To be compatible with MSVC, hex integer literals ending with the
3678           // LL or i64 suffix are always signed in Microsoft mode.
3679           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3680               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3681             Ty = Context.LongLongTy;
3682           else if (AllowUnsigned)
3683             Ty = Context.UnsignedLongLongTy;
3684           Width = LongLongSize;
3685         }
3686       }
3687 
3688       // If we still couldn't decide a type, we probably have something that
3689       // does not fit in a signed long long, but has no U suffix.
3690       if (Ty.isNull()) {
3691         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3692         Ty = Context.UnsignedLongLongTy;
3693         Width = Context.getTargetInfo().getLongLongWidth();
3694       }
3695 
3696       if (ResultVal.getBitWidth() != Width)
3697         ResultVal = ResultVal.trunc(Width);
3698     }
3699     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3700   }
3701 
3702   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3703   if (Literal.isImaginary) {
3704     Res = new (Context) ImaginaryLiteral(Res,
3705                                         Context.getComplexType(Res->getType()));
3706 
3707     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3708   }
3709   return Res;
3710 }
3711 
3712 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3713   assert(E && "ActOnParenExpr() missing expr");
3714   return new (Context) ParenExpr(L, R, E);
3715 }
3716 
3717 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3718                                          SourceLocation Loc,
3719                                          SourceRange ArgRange) {
3720   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3721   // scalar or vector data type argument..."
3722   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3723   // type (C99 6.2.5p18) or void.
3724   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3725     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3726       << T << ArgRange;
3727     return true;
3728   }
3729 
3730   assert((T->isVoidType() || !T->isIncompleteType()) &&
3731          "Scalar types should always be complete");
3732   return false;
3733 }
3734 
3735 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3736                                            SourceLocation Loc,
3737                                            SourceRange ArgRange,
3738                                            UnaryExprOrTypeTrait TraitKind) {
3739   // Invalid types must be hard errors for SFINAE in C++.
3740   if (S.LangOpts.CPlusPlus)
3741     return true;
3742 
3743   // C99 6.5.3.4p1:
3744   if (T->isFunctionType() &&
3745       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3746        TraitKind == UETT_PreferredAlignOf)) {
3747     // sizeof(function)/alignof(function) is allowed as an extension.
3748     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3749       << TraitKind << ArgRange;
3750     return false;
3751   }
3752 
3753   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3754   // this is an error (OpenCL v1.1 s6.3.k)
3755   if (T->isVoidType()) {
3756     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3757                                         : diag::ext_sizeof_alignof_void_type;
3758     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3759     return false;
3760   }
3761 
3762   return true;
3763 }
3764 
3765 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3766                                              SourceLocation Loc,
3767                                              SourceRange ArgRange,
3768                                              UnaryExprOrTypeTrait TraitKind) {
3769   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3770   // runtime doesn't allow it.
3771   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3772     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3773       << T << (TraitKind == UETT_SizeOf)
3774       << ArgRange;
3775     return true;
3776   }
3777 
3778   return false;
3779 }
3780 
3781 /// Check whether E is a pointer from a decayed array type (the decayed
3782 /// pointer type is equal to T) and emit a warning if it is.
3783 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3784                                      Expr *E) {
3785   // Don't warn if the operation changed the type.
3786   if (T != E->getType())
3787     return;
3788 
3789   // Now look for array decays.
3790   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3791   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3792     return;
3793 
3794   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3795                                              << ICE->getType()
3796                                              << ICE->getSubExpr()->getType();
3797 }
3798 
3799 /// Check the constraints on expression operands to unary type expression
3800 /// and type traits.
3801 ///
3802 /// Completes any types necessary and validates the constraints on the operand
3803 /// expression. The logic mostly mirrors the type-based overload, but may modify
3804 /// the expression as it completes the type for that expression through template
3805 /// instantiation, etc.
3806 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3807                                             UnaryExprOrTypeTrait ExprKind) {
3808   QualType ExprTy = E->getType();
3809   assert(!ExprTy->isReferenceType());
3810 
3811   if (ExprKind == UETT_VecStep)
3812     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3813                                         E->getSourceRange());
3814 
3815   // Whitelist some types as extensions
3816   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3817                                       E->getSourceRange(), ExprKind))
3818     return false;
3819 
3820   // 'alignof' applied to an expression only requires the base element type of
3821   // the expression to be complete. 'sizeof' requires the expression's type to
3822   // be complete (and will attempt to complete it if it's an array of unknown
3823   // bound).
3824   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3825     if (RequireCompleteType(E->getExprLoc(),
3826                             Context.getBaseElementType(E->getType()),
3827                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3828                             E->getSourceRange()))
3829       return true;
3830   } else {
3831     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3832                                 ExprKind, E->getSourceRange()))
3833       return true;
3834   }
3835 
3836   // Completing the expression's type may have changed it.
3837   ExprTy = E->getType();
3838   assert(!ExprTy->isReferenceType());
3839 
3840   if (ExprTy->isFunctionType()) {
3841     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3842       << ExprKind << E->getSourceRange();
3843     return true;
3844   }
3845 
3846   // The operand for sizeof and alignof is in an unevaluated expression context,
3847   // so side effects could result in unintended consequences.
3848   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3849        ExprKind == UETT_PreferredAlignOf) &&
3850       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3851     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3852 
3853   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3854                                        E->getSourceRange(), ExprKind))
3855     return true;
3856 
3857   if (ExprKind == UETT_SizeOf) {
3858     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3859       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3860         QualType OType = PVD->getOriginalType();
3861         QualType Type = PVD->getType();
3862         if (Type->isPointerType() && OType->isArrayType()) {
3863           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3864             << Type << OType;
3865           Diag(PVD->getLocation(), diag::note_declared_at);
3866         }
3867       }
3868     }
3869 
3870     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3871     // decays into a pointer and returns an unintended result. This is most
3872     // likely a typo for "sizeof(array) op x".
3873     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3874       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3875                                BO->getLHS());
3876       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3877                                BO->getRHS());
3878     }
3879   }
3880 
3881   return false;
3882 }
3883 
3884 /// Check the constraints on operands to unary expression and type
3885 /// traits.
3886 ///
3887 /// This will complete any types necessary, and validate the various constraints
3888 /// on those operands.
3889 ///
3890 /// The UsualUnaryConversions() function is *not* called by this routine.
3891 /// C99 6.3.2.1p[2-4] all state:
3892 ///   Except when it is the operand of the sizeof operator ...
3893 ///
3894 /// C++ [expr.sizeof]p4
3895 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3896 ///   standard conversions are not applied to the operand of sizeof.
3897 ///
3898 /// This policy is followed for all of the unary trait expressions.
3899 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3900                                             SourceLocation OpLoc,
3901                                             SourceRange ExprRange,
3902                                             UnaryExprOrTypeTrait ExprKind) {
3903   if (ExprType->isDependentType())
3904     return false;
3905 
3906   // C++ [expr.sizeof]p2:
3907   //     When applied to a reference or a reference type, the result
3908   //     is the size of the referenced type.
3909   // C++11 [expr.alignof]p3:
3910   //     When alignof is applied to a reference type, the result
3911   //     shall be the alignment of the referenced type.
3912   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3913     ExprType = Ref->getPointeeType();
3914 
3915   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3916   //   When alignof or _Alignof is applied to an array type, the result
3917   //   is the alignment of the element type.
3918   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3919       ExprKind == UETT_OpenMPRequiredSimdAlign)
3920     ExprType = Context.getBaseElementType(ExprType);
3921 
3922   if (ExprKind == UETT_VecStep)
3923     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3924 
3925   // Whitelist some types as extensions
3926   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3927                                       ExprKind))
3928     return false;
3929 
3930   if (RequireCompleteType(OpLoc, ExprType,
3931                           diag::err_sizeof_alignof_incomplete_type,
3932                           ExprKind, ExprRange))
3933     return true;
3934 
3935   if (ExprType->isFunctionType()) {
3936     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3937       << ExprKind << ExprRange;
3938     return true;
3939   }
3940 
3941   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3942                                        ExprKind))
3943     return true;
3944 
3945   return false;
3946 }
3947 
3948 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3949   E = E->IgnoreParens();
3950 
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   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3963     D = DRE->getDecl();
3964   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3965     D = ME->getMemberDecl();
3966   }
3967 
3968   // If it's a field, require the containing struct to have a
3969   // complete definition so that we can compute the layout.
3970   //
3971   // This can happen in C++11 onwards, either by naming the member
3972   // in a way that is not transformed into a member access expression
3973   // (in an unevaluated operand, for instance), or by naming the member
3974   // in a trailing-return-type.
3975   //
3976   // For the record, since __alignof__ on expressions is a GCC
3977   // extension, GCC seems to permit this but always gives the
3978   // nonsensical answer 0.
3979   //
3980   // We don't really need the layout here --- we could instead just
3981   // directly check for all the appropriate alignment-lowing
3982   // attributes --- but that would require duplicating a lot of
3983   // logic that just isn't worth duplicating for such a marginal
3984   // use-case.
3985   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3986     // Fast path this check, since we at least know the record has a
3987     // definition if we can find a member of it.
3988     if (!FD->getParent()->isCompleteDefinition()) {
3989       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3990         << E->getSourceRange();
3991       return true;
3992     }
3993 
3994     // Otherwise, if it's a field, and the field doesn't have
3995     // reference type, then it must have a complete type (or be a
3996     // flexible array member, which we explicitly want to
3997     // white-list anyway), which makes the following checks trivial.
3998     if (!FD->getType()->isReferenceType())
3999       return false;
4000   }
4001 
4002   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4003 }
4004 
4005 bool Sema::CheckVecStepExpr(Expr *E) {
4006   E = E->IgnoreParens();
4007 
4008   // Cannot know anything else if the expression is dependent.
4009   if (E->isTypeDependent())
4010     return false;
4011 
4012   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4013 }
4014 
4015 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4016                                         CapturingScopeInfo *CSI) {
4017   assert(T->isVariablyModifiedType());
4018   assert(CSI != nullptr);
4019 
4020   // We're going to walk down into the type and look for VLA expressions.
4021   do {
4022     const Type *Ty = T.getTypePtr();
4023     switch (Ty->getTypeClass()) {
4024 #define TYPE(Class, Base)
4025 #define ABSTRACT_TYPE(Class, Base)
4026 #define NON_CANONICAL_TYPE(Class, Base)
4027 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4028 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4029 #include "clang/AST/TypeNodes.def"
4030       T = QualType();
4031       break;
4032     // These types are never variably-modified.
4033     case Type::Builtin:
4034     case Type::Complex:
4035     case Type::Vector:
4036     case Type::ExtVector:
4037     case Type::Record:
4038     case Type::Enum:
4039     case Type::Elaborated:
4040     case Type::TemplateSpecialization:
4041     case Type::ObjCObject:
4042     case Type::ObjCInterface:
4043     case Type::ObjCObjectPointer:
4044     case Type::ObjCTypeParam:
4045     case Type::Pipe:
4046       llvm_unreachable("type class is never variably-modified!");
4047     case Type::Adjusted:
4048       T = cast<AdjustedType>(Ty)->getOriginalType();
4049       break;
4050     case Type::Decayed:
4051       T = cast<DecayedType>(Ty)->getPointeeType();
4052       break;
4053     case Type::Pointer:
4054       T = cast<PointerType>(Ty)->getPointeeType();
4055       break;
4056     case Type::BlockPointer:
4057       T = cast<BlockPointerType>(Ty)->getPointeeType();
4058       break;
4059     case Type::LValueReference:
4060     case Type::RValueReference:
4061       T = cast<ReferenceType>(Ty)->getPointeeType();
4062       break;
4063     case Type::MemberPointer:
4064       T = cast<MemberPointerType>(Ty)->getPointeeType();
4065       break;
4066     case Type::ConstantArray:
4067     case Type::IncompleteArray:
4068       // Losing element qualification here is fine.
4069       T = cast<ArrayType>(Ty)->getElementType();
4070       break;
4071     case Type::VariableArray: {
4072       // Losing element qualification here is fine.
4073       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4074 
4075       // Unknown size indication requires no size computation.
4076       // Otherwise, evaluate and record it.
4077       auto Size = VAT->getSizeExpr();
4078       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4079           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4080         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4081 
4082       T = VAT->getElementType();
4083       break;
4084     }
4085     case Type::FunctionProto:
4086     case Type::FunctionNoProto:
4087       T = cast<FunctionType>(Ty)->getReturnType();
4088       break;
4089     case Type::Paren:
4090     case Type::TypeOf:
4091     case Type::UnaryTransform:
4092     case Type::Attributed:
4093     case Type::SubstTemplateTypeParm:
4094     case Type::PackExpansion:
4095     case Type::MacroQualified:
4096       // Keep walking after single level desugaring.
4097       T = T.getSingleStepDesugaredType(Context);
4098       break;
4099     case Type::Typedef:
4100       T = cast<TypedefType>(Ty)->desugar();
4101       break;
4102     case Type::Decltype:
4103       T = cast<DecltypeType>(Ty)->desugar();
4104       break;
4105     case Type::Auto:
4106     case Type::DeducedTemplateSpecialization:
4107       T = cast<DeducedType>(Ty)->getDeducedType();
4108       break;
4109     case Type::TypeOfExpr:
4110       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4111       break;
4112     case Type::Atomic:
4113       T = cast<AtomicType>(Ty)->getValueType();
4114       break;
4115     }
4116   } while (!T.isNull() && T->isVariablyModifiedType());
4117 }
4118 
4119 /// Build a sizeof or alignof expression given a type operand.
4120 ExprResult
4121 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4122                                      SourceLocation OpLoc,
4123                                      UnaryExprOrTypeTrait ExprKind,
4124                                      SourceRange R) {
4125   if (!TInfo)
4126     return ExprError();
4127 
4128   QualType T = TInfo->getType();
4129 
4130   if (!T->isDependentType() &&
4131       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4132     return ExprError();
4133 
4134   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4135     if (auto *TT = T->getAs<TypedefType>()) {
4136       for (auto I = FunctionScopes.rbegin(),
4137                 E = std::prev(FunctionScopes.rend());
4138            I != E; ++I) {
4139         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4140         if (CSI == nullptr)
4141           break;
4142         DeclContext *DC = nullptr;
4143         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4144           DC = LSI->CallOperator;
4145         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4146           DC = CRSI->TheCapturedDecl;
4147         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4148           DC = BSI->TheDecl;
4149         if (DC) {
4150           if (DC->containsDecl(TT->getDecl()))
4151             break;
4152           captureVariablyModifiedType(Context, T, CSI);
4153         }
4154       }
4155     }
4156   }
4157 
4158   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4159   return new (Context) UnaryExprOrTypeTraitExpr(
4160       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4161 }
4162 
4163 /// Build a sizeof or alignof expression given an expression
4164 /// operand.
4165 ExprResult
4166 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4167                                      UnaryExprOrTypeTrait ExprKind) {
4168   ExprResult PE = CheckPlaceholderExpr(E);
4169   if (PE.isInvalid())
4170     return ExprError();
4171 
4172   E = PE.get();
4173 
4174   // Verify that the operand is valid.
4175   bool isInvalid = false;
4176   if (E->isTypeDependent()) {
4177     // Delay type-checking for type-dependent expressions.
4178   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4179     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4180   } else if (ExprKind == UETT_VecStep) {
4181     isInvalid = CheckVecStepExpr(E);
4182   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4183       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4184       isInvalid = true;
4185   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4186     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4187     isInvalid = true;
4188   } else {
4189     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4190   }
4191 
4192   if (isInvalid)
4193     return ExprError();
4194 
4195   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4196     PE = TransformToPotentiallyEvaluated(E);
4197     if (PE.isInvalid()) return ExprError();
4198     E = PE.get();
4199   }
4200 
4201   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4202   return new (Context) UnaryExprOrTypeTraitExpr(
4203       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4204 }
4205 
4206 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4207 /// expr and the same for @c alignof and @c __alignof
4208 /// Note that the ArgRange is invalid if isType is false.
4209 ExprResult
4210 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4211                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4212                                     void *TyOrEx, SourceRange ArgRange) {
4213   // If error parsing type, ignore.
4214   if (!TyOrEx) return ExprError();
4215 
4216   if (IsType) {
4217     TypeSourceInfo *TInfo;
4218     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4219     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4220   }
4221 
4222   Expr *ArgEx = (Expr *)TyOrEx;
4223   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4224   return Result;
4225 }
4226 
4227 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4228                                      bool IsReal) {
4229   if (V.get()->isTypeDependent())
4230     return S.Context.DependentTy;
4231 
4232   // _Real and _Imag are only l-values for normal l-values.
4233   if (V.get()->getObjectKind() != OK_Ordinary) {
4234     V = S.DefaultLvalueConversion(V.get());
4235     if (V.isInvalid())
4236       return QualType();
4237   }
4238 
4239   // These operators return the element type of a complex type.
4240   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4241     return CT->getElementType();
4242 
4243   // Otherwise they pass through real integer and floating point types here.
4244   if (V.get()->getType()->isArithmeticType())
4245     return V.get()->getType();
4246 
4247   // Test for placeholders.
4248   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4249   if (PR.isInvalid()) return QualType();
4250   if (PR.get() != V.get()) {
4251     V = PR;
4252     return CheckRealImagOperand(S, V, Loc, IsReal);
4253   }
4254 
4255   // Reject anything else.
4256   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4257     << (IsReal ? "__real" : "__imag");
4258   return QualType();
4259 }
4260 
4261 
4262 
4263 ExprResult
4264 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265                           tok::TokenKind Kind, Expr *Input) {
4266   UnaryOperatorKind Opc;
4267   switch (Kind) {
4268   default: llvm_unreachable("Unknown unary op!");
4269   case tok::plusplus:   Opc = UO_PostInc; break;
4270   case tok::minusminus: Opc = UO_PostDec; break;
4271   }
4272 
4273   // Since this might is a postfix expression, get rid of ParenListExprs.
4274   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4275   if (Result.isInvalid()) return ExprError();
4276   Input = Result.get();
4277 
4278   return BuildUnaryOp(S, OpLoc, Opc, Input);
4279 }
4280 
4281 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4282 ///
4283 /// \return true on error
4284 static bool checkArithmeticOnObjCPointer(Sema &S,
4285                                          SourceLocation opLoc,
4286                                          Expr *op) {
4287   assert(op->getType()->isObjCObjectPointerType());
4288   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4289       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4290     return false;
4291 
4292   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4293     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4294     << op->getSourceRange();
4295   return true;
4296 }
4297 
4298 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4299   auto *BaseNoParens = Base->IgnoreParens();
4300   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4301     return MSProp->getPropertyDecl()->getType()->isArrayType();
4302   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4303 }
4304 
4305 ExprResult
4306 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4307                               Expr *idx, SourceLocation rbLoc) {
4308   if (base && !base->getType().isNull() &&
4309       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4310     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4311                                     /*Length=*/nullptr, rbLoc);
4312 
4313   // Since this might be a postfix expression, get rid of ParenListExprs.
4314   if (isa<ParenListExpr>(base)) {
4315     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4316     if (result.isInvalid()) return ExprError();
4317     base = result.get();
4318   }
4319 
4320   // A comma-expression as the index is deprecated in C++2a onwards.
4321   if (getLangOpts().CPlusPlus2a &&
4322       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4323        (isa<CXXOperatorCallExpr>(idx) &&
4324         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4325     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4326       << SourceRange(base->getBeginLoc(), rbLoc);
4327   }
4328 
4329   // Handle any non-overload placeholder types in the base and index
4330   // expressions.  We can't handle overloads here because the other
4331   // operand might be an overloadable type, in which case the overload
4332   // resolution for the operator overload should get the first crack
4333   // at the overload.
4334   bool IsMSPropertySubscript = false;
4335   if (base->getType()->isNonOverloadPlaceholderType()) {
4336     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4337     if (!IsMSPropertySubscript) {
4338       ExprResult result = CheckPlaceholderExpr(base);
4339       if (result.isInvalid())
4340         return ExprError();
4341       base = result.get();
4342     }
4343   }
4344   if (idx->getType()->isNonOverloadPlaceholderType()) {
4345     ExprResult result = CheckPlaceholderExpr(idx);
4346     if (result.isInvalid()) return ExprError();
4347     idx = result.get();
4348   }
4349 
4350   // Build an unanalyzed expression if either operand is type-dependent.
4351   if (getLangOpts().CPlusPlus &&
4352       (base->isTypeDependent() || idx->isTypeDependent())) {
4353     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4354                                             VK_LValue, OK_Ordinary, rbLoc);
4355   }
4356 
4357   // MSDN, property (C++)
4358   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4359   // This attribute can also be used in the declaration of an empty array in a
4360   // class or structure definition. For example:
4361   // __declspec(property(get=GetX, put=PutX)) int x[];
4362   // The above statement indicates that x[] can be used with one or more array
4363   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4364   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4365   if (IsMSPropertySubscript) {
4366     // Build MS property subscript expression if base is MS property reference
4367     // or MS property subscript.
4368     return new (Context) MSPropertySubscriptExpr(
4369         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4370   }
4371 
4372   // Use C++ overloaded-operator rules if either operand has record
4373   // type.  The spec says to do this if either type is *overloadable*,
4374   // but enum types can't declare subscript operators or conversion
4375   // operators, so there's nothing interesting for overload resolution
4376   // to do if there aren't any record types involved.
4377   //
4378   // ObjC pointers have their own subscripting logic that is not tied
4379   // to overload resolution and so should not take this path.
4380   if (getLangOpts().CPlusPlus &&
4381       (base->getType()->isRecordType() ||
4382        (!base->getType()->isObjCObjectPointerType() &&
4383         idx->getType()->isRecordType()))) {
4384     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4385   }
4386 
4387   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4388 
4389   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4390     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4391 
4392   return Res;
4393 }
4394 
4395 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4396   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4397   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4398 
4399   // For expressions like `&(*s).b`, the base is recorded and what should be
4400   // checked.
4401   const MemberExpr *Member = nullptr;
4402   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4403     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4404 
4405   LastRecord.PossibleDerefs.erase(StrippedExpr);
4406 }
4407 
4408 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4409   QualType ResultTy = E->getType();
4410   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4411 
4412   // Bail if the element is an array since it is not memory access.
4413   if (isa<ArrayType>(ResultTy))
4414     return;
4415 
4416   if (ResultTy->hasAttr(attr::NoDeref)) {
4417     LastRecord.PossibleDerefs.insert(E);
4418     return;
4419   }
4420 
4421   // Check if the base type is a pointer to a member access of a struct
4422   // marked with noderef.
4423   const Expr *Base = E->getBase();
4424   QualType BaseTy = Base->getType();
4425   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4426     // Not a pointer access
4427     return;
4428 
4429   const MemberExpr *Member = nullptr;
4430   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4431          Member->isArrow())
4432     Base = Member->getBase();
4433 
4434   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4435     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4436       LastRecord.PossibleDerefs.insert(E);
4437   }
4438 }
4439 
4440 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4441                                           Expr *LowerBound,
4442                                           SourceLocation ColonLoc, Expr *Length,
4443                                           SourceLocation RBLoc) {
4444   if (Base->getType()->isPlaceholderType() &&
4445       !Base->getType()->isSpecificPlaceholderType(
4446           BuiltinType::OMPArraySection)) {
4447     ExprResult Result = CheckPlaceholderExpr(Base);
4448     if (Result.isInvalid())
4449       return ExprError();
4450     Base = Result.get();
4451   }
4452   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4453     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Result = DefaultLvalueConversion(Result.get());
4457     if (Result.isInvalid())
4458       return ExprError();
4459     LowerBound = Result.get();
4460   }
4461   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4462     ExprResult Result = CheckPlaceholderExpr(Length);
4463     if (Result.isInvalid())
4464       return ExprError();
4465     Result = DefaultLvalueConversion(Result.get());
4466     if (Result.isInvalid())
4467       return ExprError();
4468     Length = Result.get();
4469   }
4470 
4471   // Build an unanalyzed expression if either operand is type-dependent.
4472   if (Base->isTypeDependent() ||
4473       (LowerBound &&
4474        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4475       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4476     return new (Context)
4477         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4478                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4479   }
4480 
4481   // Perform default conversions.
4482   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4483   QualType ResultTy;
4484   if (OriginalTy->isAnyPointerType()) {
4485     ResultTy = OriginalTy->getPointeeType();
4486   } else if (OriginalTy->isArrayType()) {
4487     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4488   } else {
4489     return ExprError(
4490         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4491         << Base->getSourceRange());
4492   }
4493   // C99 6.5.2.1p1
4494   if (LowerBound) {
4495     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4496                                                       LowerBound);
4497     if (Res.isInvalid())
4498       return ExprError(Diag(LowerBound->getExprLoc(),
4499                             diag::err_omp_typecheck_section_not_integer)
4500                        << 0 << LowerBound->getSourceRange());
4501     LowerBound = Res.get();
4502 
4503     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4504         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4505       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4506           << 0 << LowerBound->getSourceRange();
4507   }
4508   if (Length) {
4509     auto Res =
4510         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4511     if (Res.isInvalid())
4512       return ExprError(Diag(Length->getExprLoc(),
4513                             diag::err_omp_typecheck_section_not_integer)
4514                        << 1 << Length->getSourceRange());
4515     Length = Res.get();
4516 
4517     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4518         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4519       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4520           << 1 << Length->getSourceRange();
4521   }
4522 
4523   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4524   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4525   // type. Note that functions are not objects, and that (in C99 parlance)
4526   // incomplete types are not object types.
4527   if (ResultTy->isFunctionType()) {
4528     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4529         << ResultTy << Base->getSourceRange();
4530     return ExprError();
4531   }
4532 
4533   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4534                           diag::err_omp_section_incomplete_type, Base))
4535     return ExprError();
4536 
4537   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4538     Expr::EvalResult Result;
4539     if (LowerBound->EvaluateAsInt(Result, Context)) {
4540       // OpenMP 4.5, [2.4 Array Sections]
4541       // The array section must be a subset of the original array.
4542       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4543       if (LowerBoundValue.isNegative()) {
4544         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4545             << LowerBound->getSourceRange();
4546         return ExprError();
4547       }
4548     }
4549   }
4550 
4551   if (Length) {
4552     Expr::EvalResult Result;
4553     if (Length->EvaluateAsInt(Result, Context)) {
4554       // OpenMP 4.5, [2.4 Array Sections]
4555       // The length must evaluate to non-negative integers.
4556       llvm::APSInt LengthValue = Result.Val.getInt();
4557       if (LengthValue.isNegative()) {
4558         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4559             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4560             << Length->getSourceRange();
4561         return ExprError();
4562       }
4563     }
4564   } else if (ColonLoc.isValid() &&
4565              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4566                                       !OriginalTy->isVariableArrayType()))) {
4567     // OpenMP 4.5, [2.4 Array Sections]
4568     // When the size of the array dimension is not known, the length must be
4569     // specified explicitly.
4570     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4571         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4572     return ExprError();
4573   }
4574 
4575   if (!Base->getType()->isSpecificPlaceholderType(
4576           BuiltinType::OMPArraySection)) {
4577     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4578     if (Result.isInvalid())
4579       return ExprError();
4580     Base = Result.get();
4581   }
4582   return new (Context)
4583       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4584                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4585 }
4586 
4587 ExprResult
4588 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4589                                       Expr *Idx, SourceLocation RLoc) {
4590   Expr *LHSExp = Base;
4591   Expr *RHSExp = Idx;
4592 
4593   ExprValueKind VK = VK_LValue;
4594   ExprObjectKind OK = OK_Ordinary;
4595 
4596   // Per C++ core issue 1213, the result is an xvalue if either operand is
4597   // a non-lvalue array, and an lvalue otherwise.
4598   if (getLangOpts().CPlusPlus11) {
4599     for (auto *Op : {LHSExp, RHSExp}) {
4600       Op = Op->IgnoreImplicit();
4601       if (Op->getType()->isArrayType() && !Op->isLValue())
4602         VK = VK_XValue;
4603     }
4604   }
4605 
4606   // Perform default conversions.
4607   if (!LHSExp->getType()->getAs<VectorType>()) {
4608     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4609     if (Result.isInvalid())
4610       return ExprError();
4611     LHSExp = Result.get();
4612   }
4613   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4614   if (Result.isInvalid())
4615     return ExprError();
4616   RHSExp = Result.get();
4617 
4618   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4619 
4620   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4621   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4622   // in the subscript position. As a result, we need to derive the array base
4623   // and index from the expression types.
4624   Expr *BaseExpr, *IndexExpr;
4625   QualType ResultType;
4626   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629     ResultType = Context.DependentTy;
4630   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4631     BaseExpr = LHSExp;
4632     IndexExpr = RHSExp;
4633     ResultType = PTy->getPointeeType();
4634   } else if (const ObjCObjectPointerType *PTy =
4635                LHSTy->getAs<ObjCObjectPointerType>()) {
4636     BaseExpr = LHSExp;
4637     IndexExpr = RHSExp;
4638 
4639     // Use custom logic if this should be the pseudo-object subscript
4640     // expression.
4641     if (!LangOpts.isSubscriptPointerArithmetic())
4642       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4643                                           nullptr);
4644 
4645     ResultType = PTy->getPointeeType();
4646   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4647      // Handle the uncommon case of "123[Ptr]".
4648     BaseExpr = RHSExp;
4649     IndexExpr = LHSExp;
4650     ResultType = PTy->getPointeeType();
4651   } else if (const ObjCObjectPointerType *PTy =
4652                RHSTy->getAs<ObjCObjectPointerType>()) {
4653      // Handle the uncommon case of "123[Ptr]".
4654     BaseExpr = RHSExp;
4655     IndexExpr = LHSExp;
4656     ResultType = PTy->getPointeeType();
4657     if (!LangOpts.isSubscriptPointerArithmetic()) {
4658       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4659         << ResultType << BaseExpr->getSourceRange();
4660       return ExprError();
4661     }
4662   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4663     BaseExpr = LHSExp;    // vectors: V[123]
4664     IndexExpr = RHSExp;
4665     // We apply C++ DR1213 to vector subscripting too.
4666     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4667       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4668       if (Materialized.isInvalid())
4669         return ExprError();
4670       LHSExp = Materialized.get();
4671     }
4672     VK = LHSExp->getValueKind();
4673     if (VK != VK_RValue)
4674       OK = OK_VectorComponent;
4675 
4676     ResultType = VTy->getElementType();
4677     QualType BaseType = BaseExpr->getType();
4678     Qualifiers BaseQuals = BaseType.getQualifiers();
4679     Qualifiers MemberQuals = ResultType.getQualifiers();
4680     Qualifiers Combined = BaseQuals + MemberQuals;
4681     if (Combined != MemberQuals)
4682       ResultType = Context.getQualifiedType(ResultType, Combined);
4683   } else if (LHSTy->isArrayType()) {
4684     // If we see an array that wasn't promoted by
4685     // DefaultFunctionArrayLvalueConversion, it must be an array that
4686     // wasn't promoted because of the C90 rule that doesn't
4687     // allow promoting non-lvalue arrays.  Warn, then
4688     // force the promotion here.
4689     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4690         << LHSExp->getSourceRange();
4691     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4692                                CK_ArrayToPointerDecay).get();
4693     LHSTy = LHSExp->getType();
4694 
4695     BaseExpr = LHSExp;
4696     IndexExpr = RHSExp;
4697     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4698   } else if (RHSTy->isArrayType()) {
4699     // Same as previous, except for 123[f().a] case
4700     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4701         << RHSExp->getSourceRange();
4702     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4703                                CK_ArrayToPointerDecay).get();
4704     RHSTy = RHSExp->getType();
4705 
4706     BaseExpr = RHSExp;
4707     IndexExpr = LHSExp;
4708     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4709   } else {
4710     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4711        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4712   }
4713   // C99 6.5.2.1p1
4714   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4715     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4716                      << IndexExpr->getSourceRange());
4717 
4718   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4719        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4720          && !IndexExpr->isTypeDependent())
4721     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4722 
4723   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4724   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4725   // type. Note that Functions are not objects, and that (in C99 parlance)
4726   // incomplete types are not object types.
4727   if (ResultType->isFunctionType()) {
4728     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4729         << ResultType << BaseExpr->getSourceRange();
4730     return ExprError();
4731   }
4732 
4733   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4734     // GNU extension: subscripting on pointer to void
4735     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4736       << BaseExpr->getSourceRange();
4737 
4738     // C forbids expressions of unqualified void type from being l-values.
4739     // See IsCForbiddenLValueType.
4740     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4741   } else if (!ResultType->isDependentType() &&
4742       RequireCompleteType(LLoc, ResultType,
4743                           diag::err_subscript_incomplete_type, BaseExpr))
4744     return ExprError();
4745 
4746   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4747          !ResultType.isCForbiddenLValueType());
4748 
4749   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4750       FunctionScopes.size() > 1) {
4751     if (auto *TT =
4752             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4753       for (auto I = FunctionScopes.rbegin(),
4754                 E = std::prev(FunctionScopes.rend());
4755            I != E; ++I) {
4756         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4757         if (CSI == nullptr)
4758           break;
4759         DeclContext *DC = nullptr;
4760         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4761           DC = LSI->CallOperator;
4762         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4763           DC = CRSI->TheCapturedDecl;
4764         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4765           DC = BSI->TheDecl;
4766         if (DC) {
4767           if (DC->containsDecl(TT->getDecl()))
4768             break;
4769           captureVariablyModifiedType(
4770               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4771         }
4772       }
4773     }
4774   }
4775 
4776   return new (Context)
4777       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4778 }
4779 
4780 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4781                                   ParmVarDecl *Param) {
4782   if (Param->hasUnparsedDefaultArg()) {
4783     Diag(CallLoc,
4784          diag::err_use_of_default_argument_to_function_declared_later) <<
4785       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4786     Diag(UnparsedDefaultArgLocs[Param],
4787          diag::note_default_argument_declared_here);
4788     return true;
4789   }
4790 
4791   if (Param->hasUninstantiatedDefaultArg()) {
4792     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4793 
4794     EnterExpressionEvaluationContext EvalContext(
4795         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4796 
4797     // Instantiate the expression.
4798     //
4799     // FIXME: Pass in a correct Pattern argument, otherwise
4800     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4801     //
4802     // template<typename T>
4803     // struct A {
4804     //   static int FooImpl();
4805     //
4806     //   template<typename Tp>
4807     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4808     //   // template argument list [[T], [Tp]], should be [[Tp]].
4809     //   friend A<Tp> Foo(int a);
4810     // };
4811     //
4812     // template<typename T>
4813     // A<T> Foo(int a = A<T>::FooImpl());
4814     MultiLevelTemplateArgumentList MutiLevelArgList
4815       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4816 
4817     InstantiatingTemplate Inst(*this, CallLoc, Param,
4818                                MutiLevelArgList.getInnermost());
4819     if (Inst.isInvalid())
4820       return true;
4821     if (Inst.isAlreadyInstantiating()) {
4822       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4823       Param->setInvalidDecl();
4824       return true;
4825     }
4826 
4827     ExprResult Result;
4828     {
4829       // C++ [dcl.fct.default]p5:
4830       //   The names in the [default argument] expression are bound, and
4831       //   the semantic constraints are checked, at the point where the
4832       //   default argument expression appears.
4833       ContextRAII SavedContext(*this, FD);
4834       LocalInstantiationScope Local(*this);
4835       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4836                                 /*DirectInit*/false);
4837     }
4838     if (Result.isInvalid())
4839       return true;
4840 
4841     // Check the expression as an initializer for the parameter.
4842     InitializedEntity Entity
4843       = InitializedEntity::InitializeParameter(Context, Param);
4844     InitializationKind Kind = InitializationKind::CreateCopy(
4845         Param->getLocation(),
4846         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4847     Expr *ResultE = Result.getAs<Expr>();
4848 
4849     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4850     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4851     if (Result.isInvalid())
4852       return true;
4853 
4854     Result =
4855         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4856                             /*DiscardedValue*/ false);
4857     if (Result.isInvalid())
4858       return true;
4859 
4860     // Remember the instantiated default argument.
4861     Param->setDefaultArg(Result.getAs<Expr>());
4862     if (ASTMutationListener *L = getASTMutationListener()) {
4863       L->DefaultArgumentInstantiated(Param);
4864     }
4865   }
4866 
4867   // If the default argument expression is not set yet, we are building it now.
4868   if (!Param->hasInit()) {
4869     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4870     Param->setInvalidDecl();
4871     return true;
4872   }
4873 
4874   // If the default expression creates temporaries, we need to
4875   // push them to the current stack of expression temporaries so they'll
4876   // be properly destroyed.
4877   // FIXME: We should really be rebuilding the default argument with new
4878   // bound temporaries; see the comment in PR5810.
4879   // We don't need to do that with block decls, though, because
4880   // blocks in default argument expression can never capture anything.
4881   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4882     // Set the "needs cleanups" bit regardless of whether there are
4883     // any explicit objects.
4884     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4885 
4886     // Append all the objects to the cleanup list.  Right now, this
4887     // should always be a no-op, because blocks in default argument
4888     // expressions should never be able to capture anything.
4889     assert(!Init->getNumObjects() &&
4890            "default argument expression has capturing blocks?");
4891   }
4892 
4893   // We already type-checked the argument, so we know it works.
4894   // Just mark all of the declarations in this potentially-evaluated expression
4895   // as being "referenced".
4896   EnterExpressionEvaluationContext EvalContext(
4897       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4898   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4899                                    /*SkipLocalVariables=*/true);
4900   return false;
4901 }
4902 
4903 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4904                                         FunctionDecl *FD, ParmVarDecl *Param) {
4905   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4906     return ExprError();
4907   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4908 }
4909 
4910 Sema::VariadicCallType
4911 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4912                           Expr *Fn) {
4913   if (Proto && Proto->isVariadic()) {
4914     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4915       return VariadicConstructor;
4916     else if (Fn && Fn->getType()->isBlockPointerType())
4917       return VariadicBlock;
4918     else if (FDecl) {
4919       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4920         if (Method->isInstance())
4921           return VariadicMethod;
4922     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4923       return VariadicMethod;
4924     return VariadicFunction;
4925   }
4926   return VariadicDoesNotApply;
4927 }
4928 
4929 namespace {
4930 class FunctionCallCCC final : public FunctionCallFilterCCC {
4931 public:
4932   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4933                   unsigned NumArgs, MemberExpr *ME)
4934       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4935         FunctionName(FuncName) {}
4936 
4937   bool ValidateCandidate(const TypoCorrection &candidate) override {
4938     if (!candidate.getCorrectionSpecifier() ||
4939         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4940       return false;
4941     }
4942 
4943     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4944   }
4945 
4946   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4947     return std::make_unique<FunctionCallCCC>(*this);
4948   }
4949 
4950 private:
4951   const IdentifierInfo *const FunctionName;
4952 };
4953 }
4954 
4955 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4956                                                FunctionDecl *FDecl,
4957                                                ArrayRef<Expr *> Args) {
4958   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4959   DeclarationName FuncName = FDecl->getDeclName();
4960   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4961 
4962   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4963   if (TypoCorrection Corrected = S.CorrectTypo(
4964           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4965           S.getScopeForContext(S.CurContext), nullptr, CCC,
4966           Sema::CTK_ErrorRecovery)) {
4967     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4968       if (Corrected.isOverloaded()) {
4969         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4970         OverloadCandidateSet::iterator Best;
4971         for (NamedDecl *CD : Corrected) {
4972           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4973             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4974                                    OCS);
4975         }
4976         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4977         case OR_Success:
4978           ND = Best->FoundDecl;
4979           Corrected.setCorrectionDecl(ND);
4980           break;
4981         default:
4982           break;
4983         }
4984       }
4985       ND = ND->getUnderlyingDecl();
4986       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4987         return Corrected;
4988     }
4989   }
4990   return TypoCorrection();
4991 }
4992 
4993 /// ConvertArgumentsForCall - Converts the arguments specified in
4994 /// Args/NumArgs to the parameter types of the function FDecl with
4995 /// function prototype Proto. Call is the call expression itself, and
4996 /// Fn is the function expression. For a C++ member function, this
4997 /// routine does not attempt to convert the object argument. Returns
4998 /// true if the call is ill-formed.
4999 bool
5000 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5001                               FunctionDecl *FDecl,
5002                               const FunctionProtoType *Proto,
5003                               ArrayRef<Expr *> Args,
5004                               SourceLocation RParenLoc,
5005                               bool IsExecConfig) {
5006   // Bail out early if calling a builtin with custom typechecking.
5007   if (FDecl)
5008     if (unsigned ID = FDecl->getBuiltinID())
5009       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5010         return false;
5011 
5012   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5013   // assignment, to the types of the corresponding parameter, ...
5014   unsigned NumParams = Proto->getNumParams();
5015   bool Invalid = false;
5016   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5017   unsigned FnKind = Fn->getType()->isBlockPointerType()
5018                        ? 1 /* block */
5019                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5020                                        : 0 /* function */);
5021 
5022   // If too few arguments are available (and we don't have default
5023   // arguments for the remaining parameters), don't make the call.
5024   if (Args.size() < NumParams) {
5025     if (Args.size() < MinArgs) {
5026       TypoCorrection TC;
5027       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5028         unsigned diag_id =
5029             MinArgs == NumParams && !Proto->isVariadic()
5030                 ? diag::err_typecheck_call_too_few_args_suggest
5031                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5032         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5033                                         << static_cast<unsigned>(Args.size())
5034                                         << TC.getCorrectionRange());
5035       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5036         Diag(RParenLoc,
5037              MinArgs == NumParams && !Proto->isVariadic()
5038                  ? diag::err_typecheck_call_too_few_args_one
5039                  : diag::err_typecheck_call_too_few_args_at_least_one)
5040             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5041       else
5042         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5043                             ? diag::err_typecheck_call_too_few_args
5044                             : diag::err_typecheck_call_too_few_args_at_least)
5045             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5046             << Fn->getSourceRange();
5047 
5048       // Emit the location of the prototype.
5049       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5050         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5051 
5052       return true;
5053     }
5054     // We reserve space for the default arguments when we create
5055     // the call expression, before calling ConvertArgumentsForCall.
5056     assert((Call->getNumArgs() == NumParams) &&
5057            "We should have reserved space for the default arguments before!");
5058   }
5059 
5060   // If too many are passed and not variadic, error on the extras and drop
5061   // them.
5062   if (Args.size() > NumParams) {
5063     if (!Proto->isVariadic()) {
5064       TypoCorrection TC;
5065       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5066         unsigned diag_id =
5067             MinArgs == NumParams && !Proto->isVariadic()
5068                 ? diag::err_typecheck_call_too_many_args_suggest
5069                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5070         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5071                                         << static_cast<unsigned>(Args.size())
5072                                         << TC.getCorrectionRange());
5073       } else if (NumParams == 1 && FDecl &&
5074                  FDecl->getParamDecl(0)->getDeclName())
5075         Diag(Args[NumParams]->getBeginLoc(),
5076              MinArgs == NumParams
5077                  ? diag::err_typecheck_call_too_many_args_one
5078                  : diag::err_typecheck_call_too_many_args_at_most_one)
5079             << FnKind << FDecl->getParamDecl(0)
5080             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5081             << SourceRange(Args[NumParams]->getBeginLoc(),
5082                            Args.back()->getEndLoc());
5083       else
5084         Diag(Args[NumParams]->getBeginLoc(),
5085              MinArgs == NumParams
5086                  ? diag::err_typecheck_call_too_many_args
5087                  : diag::err_typecheck_call_too_many_args_at_most)
5088             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5089             << Fn->getSourceRange()
5090             << SourceRange(Args[NumParams]->getBeginLoc(),
5091                            Args.back()->getEndLoc());
5092 
5093       // Emit the location of the prototype.
5094       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5095         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5096 
5097       // This deletes the extra arguments.
5098       Call->shrinkNumArgs(NumParams);
5099       return true;
5100     }
5101   }
5102   SmallVector<Expr *, 8> AllArgs;
5103   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5104 
5105   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5106                                    AllArgs, CallType);
5107   if (Invalid)
5108     return true;
5109   unsigned TotalNumArgs = AllArgs.size();
5110   for (unsigned i = 0; i < TotalNumArgs; ++i)
5111     Call->setArg(i, AllArgs[i]);
5112 
5113   return false;
5114 }
5115 
5116 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5117                                   const FunctionProtoType *Proto,
5118                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5119                                   SmallVectorImpl<Expr *> &AllArgs,
5120                                   VariadicCallType CallType, bool AllowExplicit,
5121                                   bool IsListInitialization) {
5122   unsigned NumParams = Proto->getNumParams();
5123   bool Invalid = false;
5124   size_t ArgIx = 0;
5125   // Continue to check argument types (even if we have too few/many args).
5126   for (unsigned i = FirstParam; i < NumParams; i++) {
5127     QualType ProtoArgType = Proto->getParamType(i);
5128 
5129     Expr *Arg;
5130     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5131     if (ArgIx < Args.size()) {
5132       Arg = Args[ArgIx++];
5133 
5134       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5135                               diag::err_call_incomplete_argument, Arg))
5136         return true;
5137 
5138       // Strip the unbridged-cast placeholder expression off, if applicable.
5139       bool CFAudited = false;
5140       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5141           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5142           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5143         Arg = stripARCUnbridgedCast(Arg);
5144       else if (getLangOpts().ObjCAutoRefCount &&
5145                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5146                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5147         CFAudited = true;
5148 
5149       if (Proto->getExtParameterInfo(i).isNoEscape())
5150         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5151           BE->getBlockDecl()->setDoesNotEscape();
5152 
5153       InitializedEntity Entity =
5154           Param ? InitializedEntity::InitializeParameter(Context, Param,
5155                                                          ProtoArgType)
5156                 : InitializedEntity::InitializeParameter(
5157                       Context, ProtoArgType, Proto->isParamConsumed(i));
5158 
5159       // Remember that parameter belongs to a CF audited API.
5160       if (CFAudited)
5161         Entity.setParameterCFAudited();
5162 
5163       ExprResult ArgE = PerformCopyInitialization(
5164           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5165       if (ArgE.isInvalid())
5166         return true;
5167 
5168       Arg = ArgE.getAs<Expr>();
5169     } else {
5170       assert(Param && "can't use default arguments without a known callee");
5171 
5172       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5173       if (ArgExpr.isInvalid())
5174         return true;
5175 
5176       Arg = ArgExpr.getAs<Expr>();
5177     }
5178 
5179     // Check for array bounds violations for each argument to the call. This
5180     // check only triggers warnings when the argument isn't a more complex Expr
5181     // with its own checking, such as a BinaryOperator.
5182     CheckArrayAccess(Arg);
5183 
5184     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5185     CheckStaticArrayArgument(CallLoc, Param, Arg);
5186 
5187     AllArgs.push_back(Arg);
5188   }
5189 
5190   // If this is a variadic call, handle args passed through "...".
5191   if (CallType != VariadicDoesNotApply) {
5192     // Assume that extern "C" functions with variadic arguments that
5193     // return __unknown_anytype aren't *really* variadic.
5194     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5195         FDecl->isExternC()) {
5196       for (Expr *A : Args.slice(ArgIx)) {
5197         QualType paramType; // ignored
5198         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5199         Invalid |= arg.isInvalid();
5200         AllArgs.push_back(arg.get());
5201       }
5202 
5203     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5204     } else {
5205       for (Expr *A : Args.slice(ArgIx)) {
5206         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5207         Invalid |= Arg.isInvalid();
5208         AllArgs.push_back(Arg.get());
5209       }
5210     }
5211 
5212     // Check for array bounds violations.
5213     for (Expr *A : Args.slice(ArgIx))
5214       CheckArrayAccess(A);
5215   }
5216   return Invalid;
5217 }
5218 
5219 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5220   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5221   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5222     TL = DTL.getOriginalLoc();
5223   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5224     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5225       << ATL.getLocalSourceRange();
5226 }
5227 
5228 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5229 /// array parameter, check that it is non-null, and that if it is formed by
5230 /// array-to-pointer decay, the underlying array is sufficiently large.
5231 ///
5232 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5233 /// array type derivation, then for each call to the function, the value of the
5234 /// corresponding actual argument shall provide access to the first element of
5235 /// an array with at least as many elements as specified by the size expression.
5236 void
5237 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5238                                ParmVarDecl *Param,
5239                                const Expr *ArgExpr) {
5240   // Static array parameters are not supported in C++.
5241   if (!Param || getLangOpts().CPlusPlus)
5242     return;
5243 
5244   QualType OrigTy = Param->getOriginalType();
5245 
5246   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5247   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5248     return;
5249 
5250   if (ArgExpr->isNullPointerConstant(Context,
5251                                      Expr::NPC_NeverValueDependent)) {
5252     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5253     DiagnoseCalleeStaticArrayParam(*this, Param);
5254     return;
5255   }
5256 
5257   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5258   if (!CAT)
5259     return;
5260 
5261   const ConstantArrayType *ArgCAT =
5262     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5263   if (!ArgCAT)
5264     return;
5265 
5266   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5267                                              ArgCAT->getElementType())) {
5268     if (ArgCAT->getSize().ult(CAT->getSize())) {
5269       Diag(CallLoc, diag::warn_static_array_too_small)
5270           << ArgExpr->getSourceRange()
5271           << (unsigned)ArgCAT->getSize().getZExtValue()
5272           << (unsigned)CAT->getSize().getZExtValue() << 0;
5273       DiagnoseCalleeStaticArrayParam(*this, Param);
5274     }
5275     return;
5276   }
5277 
5278   Optional<CharUnits> ArgSize =
5279       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5280   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5281   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5282     Diag(CallLoc, diag::warn_static_array_too_small)
5283         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5284         << (unsigned)ParmSize->getQuantity() << 1;
5285     DiagnoseCalleeStaticArrayParam(*this, Param);
5286   }
5287 }
5288 
5289 /// Given a function expression of unknown-any type, try to rebuild it
5290 /// to have a function type.
5291 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5292 
5293 /// Is the given type a placeholder that we need to lower out
5294 /// immediately during argument processing?
5295 static bool isPlaceholderToRemoveAsArg(QualType type) {
5296   // Placeholders are never sugared.
5297   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5298   if (!placeholder) return false;
5299 
5300   switch (placeholder->getKind()) {
5301   // Ignore all the non-placeholder types.
5302 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5303   case BuiltinType::Id:
5304 #include "clang/Basic/OpenCLImageTypes.def"
5305 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5306   case BuiltinType::Id:
5307 #include "clang/Basic/OpenCLExtensionTypes.def"
5308   // In practice we'll never use this, since all SVE types are sugared
5309   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5310 #define SVE_TYPE(Name, Id, SingletonId) \
5311   case BuiltinType::Id:
5312 #include "clang/Basic/AArch64SVEACLETypes.def"
5313 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5314 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5315 #include "clang/AST/BuiltinTypes.def"
5316     return false;
5317 
5318   // We cannot lower out overload sets; they might validly be resolved
5319   // by the call machinery.
5320   case BuiltinType::Overload:
5321     return false;
5322 
5323   // Unbridged casts in ARC can be handled in some call positions and
5324   // should be left in place.
5325   case BuiltinType::ARCUnbridgedCast:
5326     return false;
5327 
5328   // Pseudo-objects should be converted as soon as possible.
5329   case BuiltinType::PseudoObject:
5330     return true;
5331 
5332   // The debugger mode could theoretically but currently does not try
5333   // to resolve unknown-typed arguments based on known parameter types.
5334   case BuiltinType::UnknownAny:
5335     return true;
5336 
5337   // These are always invalid as call arguments and should be reported.
5338   case BuiltinType::BoundMember:
5339   case BuiltinType::BuiltinFn:
5340   case BuiltinType::OMPArraySection:
5341     return true;
5342 
5343   }
5344   llvm_unreachable("bad builtin type kind");
5345 }
5346 
5347 /// Check an argument list for placeholders that we won't try to
5348 /// handle later.
5349 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5350   // Apply this processing to all the arguments at once instead of
5351   // dying at the first failure.
5352   bool hasInvalid = false;
5353   for (size_t i = 0, e = args.size(); i != e; i++) {
5354     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5355       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5356       if (result.isInvalid()) hasInvalid = true;
5357       else args[i] = result.get();
5358     } else if (hasInvalid) {
5359       (void)S.CorrectDelayedTyposInExpr(args[i]);
5360     }
5361   }
5362   return hasInvalid;
5363 }
5364 
5365 /// If a builtin function has a pointer argument with no explicit address
5366 /// space, then it should be able to accept a pointer to any address
5367 /// space as input.  In order to do this, we need to replace the
5368 /// standard builtin declaration with one that uses the same address space
5369 /// as the call.
5370 ///
5371 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5372 ///                  it does not contain any pointer arguments without
5373 ///                  an address space qualifer.  Otherwise the rewritten
5374 ///                  FunctionDecl is returned.
5375 /// TODO: Handle pointer return types.
5376 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5377                                                 FunctionDecl *FDecl,
5378                                                 MultiExprArg ArgExprs) {
5379 
5380   QualType DeclType = FDecl->getType();
5381   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5382 
5383   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5384       ArgExprs.size() < FT->getNumParams())
5385     return nullptr;
5386 
5387   bool NeedsNewDecl = false;
5388   unsigned i = 0;
5389   SmallVector<QualType, 8> OverloadParams;
5390 
5391   for (QualType ParamType : FT->param_types()) {
5392 
5393     // Convert array arguments to pointer to simplify type lookup.
5394     ExprResult ArgRes =
5395         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5396     if (ArgRes.isInvalid())
5397       return nullptr;
5398     Expr *Arg = ArgRes.get();
5399     QualType ArgType = Arg->getType();
5400     if (!ParamType->isPointerType() ||
5401         ParamType.getQualifiers().hasAddressSpace() ||
5402         !ArgType->isPointerType() ||
5403         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5404       OverloadParams.push_back(ParamType);
5405       continue;
5406     }
5407 
5408     QualType PointeeType = ParamType->getPointeeType();
5409     if (PointeeType.getQualifiers().hasAddressSpace())
5410       continue;
5411 
5412     NeedsNewDecl = true;
5413     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5414 
5415     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5416     OverloadParams.push_back(Context.getPointerType(PointeeType));
5417   }
5418 
5419   if (!NeedsNewDecl)
5420     return nullptr;
5421 
5422   FunctionProtoType::ExtProtoInfo EPI;
5423   EPI.Variadic = FT->isVariadic();
5424   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5425                                                 OverloadParams, EPI);
5426   DeclContext *Parent = FDecl->getParent();
5427   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5428                                                     FDecl->getLocation(),
5429                                                     FDecl->getLocation(),
5430                                                     FDecl->getIdentifier(),
5431                                                     OverloadTy,
5432                                                     /*TInfo=*/nullptr,
5433                                                     SC_Extern, false,
5434                                                     /*hasPrototype=*/true);
5435   SmallVector<ParmVarDecl*, 16> Params;
5436   FT = cast<FunctionProtoType>(OverloadTy);
5437   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5438     QualType ParamType = FT->getParamType(i);
5439     ParmVarDecl *Parm =
5440         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5441                                 SourceLocation(), nullptr, ParamType,
5442                                 /*TInfo=*/nullptr, SC_None, nullptr);
5443     Parm->setScopeInfo(0, i);
5444     Params.push_back(Parm);
5445   }
5446   OverloadDecl->setParams(Params);
5447   return OverloadDecl;
5448 }
5449 
5450 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5451                                     FunctionDecl *Callee,
5452                                     MultiExprArg ArgExprs) {
5453   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5454   // similar attributes) really don't like it when functions are called with an
5455   // invalid number of args.
5456   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5457                          /*PartialOverloading=*/false) &&
5458       !Callee->isVariadic())
5459     return;
5460   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5461     return;
5462 
5463   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5464     S.Diag(Fn->getBeginLoc(),
5465            isa<CXXMethodDecl>(Callee)
5466                ? diag::err_ovl_no_viable_member_function_in_call
5467                : diag::err_ovl_no_viable_function_in_call)
5468         << Callee << Callee->getSourceRange();
5469     S.Diag(Callee->getLocation(),
5470            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5471         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5472     return;
5473   }
5474 }
5475 
5476 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5477     const UnresolvedMemberExpr *const UME, Sema &S) {
5478 
5479   const auto GetFunctionLevelDCIfCXXClass =
5480       [](Sema &S) -> const CXXRecordDecl * {
5481     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5482     if (!DC || !DC->getParent())
5483       return nullptr;
5484 
5485     // If the call to some member function was made from within a member
5486     // function body 'M' return return 'M's parent.
5487     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5488       return MD->getParent()->getCanonicalDecl();
5489     // else the call was made from within a default member initializer of a
5490     // class, so return the class.
5491     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5492       return RD->getCanonicalDecl();
5493     return nullptr;
5494   };
5495   // If our DeclContext is neither a member function nor a class (in the
5496   // case of a lambda in a default member initializer), we can't have an
5497   // enclosing 'this'.
5498 
5499   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5500   if (!CurParentClass)
5501     return false;
5502 
5503   // The naming class for implicit member functions call is the class in which
5504   // name lookup starts.
5505   const CXXRecordDecl *const NamingClass =
5506       UME->getNamingClass()->getCanonicalDecl();
5507   assert(NamingClass && "Must have naming class even for implicit access");
5508 
5509   // If the unresolved member functions were found in a 'naming class' that is
5510   // related (either the same or derived from) to the class that contains the
5511   // member function that itself contained the implicit member access.
5512 
5513   return CurParentClass == NamingClass ||
5514          CurParentClass->isDerivedFrom(NamingClass);
5515 }
5516 
5517 static void
5518 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5519     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5520 
5521   if (!UME)
5522     return;
5523 
5524   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5525   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5526   // already been captured, or if this is an implicit member function call (if
5527   // it isn't, an attempt to capture 'this' should already have been made).
5528   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5529       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5530     return;
5531 
5532   // Check if the naming class in which the unresolved members were found is
5533   // related (same as or is a base of) to the enclosing class.
5534 
5535   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5536     return;
5537 
5538 
5539   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5540   // If the enclosing function is not dependent, then this lambda is
5541   // capture ready, so if we can capture this, do so.
5542   if (!EnclosingFunctionCtx->isDependentContext()) {
5543     // If the current lambda and all enclosing lambdas can capture 'this' -
5544     // then go ahead and capture 'this' (since our unresolved overload set
5545     // contains at least one non-static member function).
5546     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5547       S.CheckCXXThisCapture(CallLoc);
5548   } else if (S.CurContext->isDependentContext()) {
5549     // ... since this is an implicit member reference, that might potentially
5550     // involve a 'this' capture, mark 'this' for potential capture in
5551     // enclosing lambdas.
5552     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5553       CurLSI->addPotentialThisCapture(CallLoc);
5554   }
5555 }
5556 
5557 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5558                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5559                                Expr *ExecConfig) {
5560   ExprResult Call =
5561       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5562   if (Call.isInvalid())
5563     return Call;
5564 
5565   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5566   // language modes.
5567   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5568     if (ULE->hasExplicitTemplateArgs() &&
5569         ULE->decls_begin() == ULE->decls_end()) {
5570       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5571                                  ? diag::warn_cxx17_compat_adl_only_template_id
5572                                  : diag::ext_adl_only_template_id)
5573           << ULE->getName();
5574     }
5575   }
5576 
5577   return Call;
5578 }
5579 
5580 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5581 /// This provides the location of the left/right parens and a list of comma
5582 /// locations.
5583 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5584                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5585                                Expr *ExecConfig, bool IsExecConfig) {
5586   // Since this might be a postfix expression, get rid of ParenListExprs.
5587   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5588   if (Result.isInvalid()) return ExprError();
5589   Fn = Result.get();
5590 
5591   if (checkArgsForPlaceholders(*this, ArgExprs))
5592     return ExprError();
5593 
5594   if (getLangOpts().CPlusPlus) {
5595     // If this is a pseudo-destructor expression, build the call immediately.
5596     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5597       if (!ArgExprs.empty()) {
5598         // Pseudo-destructor calls should not have any arguments.
5599         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5600             << FixItHint::CreateRemoval(
5601                    SourceRange(ArgExprs.front()->getBeginLoc(),
5602                                ArgExprs.back()->getEndLoc()));
5603       }
5604 
5605       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5606                               VK_RValue, RParenLoc);
5607     }
5608     if (Fn->getType() == Context.PseudoObjectTy) {
5609       ExprResult result = CheckPlaceholderExpr(Fn);
5610       if (result.isInvalid()) return ExprError();
5611       Fn = result.get();
5612     }
5613 
5614     // Determine whether this is a dependent call inside a C++ template,
5615     // in which case we won't do any semantic analysis now.
5616     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5617       if (ExecConfig) {
5618         return CUDAKernelCallExpr::Create(
5619             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5620             Context.DependentTy, VK_RValue, RParenLoc);
5621       } else {
5622 
5623         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5624             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5625             Fn->getBeginLoc());
5626 
5627         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5628                                 VK_RValue, RParenLoc);
5629       }
5630     }
5631 
5632     // Determine whether this is a call to an object (C++ [over.call.object]).
5633     if (Fn->getType()->isRecordType())
5634       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5635                                           RParenLoc);
5636 
5637     if (Fn->getType() == Context.UnknownAnyTy) {
5638       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5639       if (result.isInvalid()) return ExprError();
5640       Fn = result.get();
5641     }
5642 
5643     if (Fn->getType() == Context.BoundMemberTy) {
5644       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5645                                        RParenLoc);
5646     }
5647   }
5648 
5649   // Check for overloaded calls.  This can happen even in C due to extensions.
5650   if (Fn->getType() == Context.OverloadTy) {
5651     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5652 
5653     // We aren't supposed to apply this logic if there's an '&' involved.
5654     if (!find.HasFormOfMemberPointer) {
5655       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5656         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5657                                 VK_RValue, RParenLoc);
5658       OverloadExpr *ovl = find.Expression;
5659       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5660         return BuildOverloadedCallExpr(
5661             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5662             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5663       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5664                                        RParenLoc);
5665     }
5666   }
5667 
5668   // If we're directly calling a function, get the appropriate declaration.
5669   if (Fn->getType() == Context.UnknownAnyTy) {
5670     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5671     if (result.isInvalid()) return ExprError();
5672     Fn = result.get();
5673   }
5674 
5675   Expr *NakedFn = Fn->IgnoreParens();
5676 
5677   bool CallingNDeclIndirectly = false;
5678   NamedDecl *NDecl = nullptr;
5679   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5680     if (UnOp->getOpcode() == UO_AddrOf) {
5681       CallingNDeclIndirectly = true;
5682       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5683     }
5684   }
5685 
5686   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5687     NDecl = DRE->getDecl();
5688 
5689     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5690     if (FDecl && FDecl->getBuiltinID()) {
5691       // Rewrite the function decl for this builtin by replacing parameters
5692       // with no explicit address space with the address space of the arguments
5693       // in ArgExprs.
5694       if ((FDecl =
5695                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5696         NDecl = FDecl;
5697         Fn = DeclRefExpr::Create(
5698             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5699             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5700             nullptr, DRE->isNonOdrUse());
5701       }
5702     }
5703   } else if (isa<MemberExpr>(NakedFn))
5704     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5705 
5706   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5707     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5708                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5709       return ExprError();
5710 
5711     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5712       return ExprError();
5713 
5714     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5715   }
5716 
5717   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5718                                ExecConfig, IsExecConfig);
5719 }
5720 
5721 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5722 ///
5723 /// __builtin_astype( value, dst type )
5724 ///
5725 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5726                                  SourceLocation BuiltinLoc,
5727                                  SourceLocation RParenLoc) {
5728   ExprValueKind VK = VK_RValue;
5729   ExprObjectKind OK = OK_Ordinary;
5730   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5731   QualType SrcTy = E->getType();
5732   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5733     return ExprError(Diag(BuiltinLoc,
5734                           diag::err_invalid_astype_of_different_size)
5735                      << DstTy
5736                      << SrcTy
5737                      << E->getSourceRange());
5738   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5739 }
5740 
5741 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5742 /// provided arguments.
5743 ///
5744 /// __builtin_convertvector( value, dst type )
5745 ///
5746 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5747                                         SourceLocation BuiltinLoc,
5748                                         SourceLocation RParenLoc) {
5749   TypeSourceInfo *TInfo;
5750   GetTypeFromParser(ParsedDestTy, &TInfo);
5751   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5752 }
5753 
5754 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5755 /// i.e. an expression not of \p OverloadTy.  The expression should
5756 /// unary-convert to an expression of function-pointer or
5757 /// block-pointer type.
5758 ///
5759 /// \param NDecl the declaration being called, if available
5760 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5761                                        SourceLocation LParenLoc,
5762                                        ArrayRef<Expr *> Args,
5763                                        SourceLocation RParenLoc, Expr *Config,
5764                                        bool IsExecConfig, ADLCallKind UsesADL) {
5765   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5766   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5767 
5768   // Functions with 'interrupt' attribute cannot be called directly.
5769   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5770     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5771     return ExprError();
5772   }
5773 
5774   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5775   // so there's some risk when calling out to non-interrupt handler functions
5776   // that the callee might not preserve them. This is easy to diagnose here,
5777   // but can be very challenging to debug.
5778   if (auto *Caller = getCurFunctionDecl())
5779     if (Caller->hasAttr<ARMInterruptAttr>()) {
5780       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5781       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5782         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5783     }
5784 
5785   // Promote the function operand.
5786   // We special-case function promotion here because we only allow promoting
5787   // builtin functions to function pointers in the callee of a call.
5788   ExprResult Result;
5789   QualType ResultTy;
5790   if (BuiltinID &&
5791       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5792     // Extract the return type from the (builtin) function pointer type.
5793     // FIXME Several builtins still have setType in
5794     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5795     // Builtins.def to ensure they are correct before removing setType calls.
5796     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5797     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5798     ResultTy = FDecl->getCallResultType();
5799   } else {
5800     Result = CallExprUnaryConversions(Fn);
5801     ResultTy = Context.BoolTy;
5802   }
5803   if (Result.isInvalid())
5804     return ExprError();
5805   Fn = Result.get();
5806 
5807   // Check for a valid function type, but only if it is not a builtin which
5808   // requires custom type checking. These will be handled by
5809   // CheckBuiltinFunctionCall below just after creation of the call expression.
5810   const FunctionType *FuncT = nullptr;
5811   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5812   retry:
5813     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5814       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5815       // have type pointer to function".
5816       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5817       if (!FuncT)
5818         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5819                          << Fn->getType() << Fn->getSourceRange());
5820     } else if (const BlockPointerType *BPT =
5821                    Fn->getType()->getAs<BlockPointerType>()) {
5822       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5823     } else {
5824       // Handle calls to expressions of unknown-any type.
5825       if (Fn->getType() == Context.UnknownAnyTy) {
5826         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5827         if (rewrite.isInvalid())
5828           return ExprError();
5829         Fn = rewrite.get();
5830         goto retry;
5831       }
5832 
5833       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5834                        << Fn->getType() << Fn->getSourceRange());
5835     }
5836   }
5837 
5838   // Get the number of parameters in the function prototype, if any.
5839   // We will allocate space for max(Args.size(), NumParams) arguments
5840   // in the call expression.
5841   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5842   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5843 
5844   CallExpr *TheCall;
5845   if (Config) {
5846     assert(UsesADL == ADLCallKind::NotADL &&
5847            "CUDAKernelCallExpr should not use ADL");
5848     TheCall =
5849         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5850                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5851   } else {
5852     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5853                                RParenLoc, NumParams, UsesADL);
5854   }
5855 
5856   if (!getLangOpts().CPlusPlus) {
5857     // Forget about the nulled arguments since typo correction
5858     // do not handle them well.
5859     TheCall->shrinkNumArgs(Args.size());
5860     // C cannot always handle TypoExpr nodes in builtin calls and direct
5861     // function calls as their argument checking don't necessarily handle
5862     // dependent types properly, so make sure any TypoExprs have been
5863     // dealt with.
5864     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5865     if (!Result.isUsable()) return ExprError();
5866     CallExpr *TheOldCall = TheCall;
5867     TheCall = dyn_cast<CallExpr>(Result.get());
5868     bool CorrectedTypos = TheCall != TheOldCall;
5869     if (!TheCall) return Result;
5870     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5871 
5872     // A new call expression node was created if some typos were corrected.
5873     // However it may not have been constructed with enough storage. In this
5874     // case, rebuild the node with enough storage. The waste of space is
5875     // immaterial since this only happens when some typos were corrected.
5876     if (CorrectedTypos && Args.size() < NumParams) {
5877       if (Config)
5878         TheCall = CUDAKernelCallExpr::Create(
5879             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5880             RParenLoc, NumParams);
5881       else
5882         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5883                                    RParenLoc, NumParams, UsesADL);
5884     }
5885     // We can now handle the nulled arguments for the default arguments.
5886     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5887   }
5888 
5889   // Bail out early if calling a builtin with custom type checking.
5890   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5891     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5892 
5893   if (getLangOpts().CUDA) {
5894     if (Config) {
5895       // CUDA: Kernel calls must be to global functions
5896       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5897         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5898             << FDecl << Fn->getSourceRange());
5899 
5900       // CUDA: Kernel function must have 'void' return type
5901       if (!FuncT->getReturnType()->isVoidType())
5902         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5903             << Fn->getType() << Fn->getSourceRange());
5904     } else {
5905       // CUDA: Calls to global functions must be configured
5906       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5907         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5908             << FDecl << Fn->getSourceRange());
5909     }
5910   }
5911 
5912   // Check for a valid return type
5913   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5914                           FDecl))
5915     return ExprError();
5916 
5917   // We know the result type of the call, set it.
5918   TheCall->setType(FuncT->getCallResultType(Context));
5919   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5920 
5921   if (Proto) {
5922     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5923                                 IsExecConfig))
5924       return ExprError();
5925   } else {
5926     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5927 
5928     if (FDecl) {
5929       // Check if we have too few/too many template arguments, based
5930       // on our knowledge of the function definition.
5931       const FunctionDecl *Def = nullptr;
5932       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5933         Proto = Def->getType()->getAs<FunctionProtoType>();
5934        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5935           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5936           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5937       }
5938 
5939       // If the function we're calling isn't a function prototype, but we have
5940       // a function prototype from a prior declaratiom, use that prototype.
5941       if (!FDecl->hasPrototype())
5942         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5943     }
5944 
5945     // Promote the arguments (C99 6.5.2.2p6).
5946     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5947       Expr *Arg = Args[i];
5948 
5949       if (Proto && i < Proto->getNumParams()) {
5950         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5951             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5952         ExprResult ArgE =
5953             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5954         if (ArgE.isInvalid())
5955           return true;
5956 
5957         Arg = ArgE.getAs<Expr>();
5958 
5959       } else {
5960         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5961 
5962         if (ArgE.isInvalid())
5963           return true;
5964 
5965         Arg = ArgE.getAs<Expr>();
5966       }
5967 
5968       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5969                               diag::err_call_incomplete_argument, Arg))
5970         return ExprError();
5971 
5972       TheCall->setArg(i, Arg);
5973     }
5974   }
5975 
5976   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5977     if (!Method->isStatic())
5978       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5979         << Fn->getSourceRange());
5980 
5981   // Check for sentinels
5982   if (NDecl)
5983     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5984 
5985   // Do special checking on direct calls to functions.
5986   if (FDecl) {
5987     if (CheckFunctionCall(FDecl, TheCall, Proto))
5988       return ExprError();
5989 
5990     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5991 
5992     if (BuiltinID)
5993       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5994   } else if (NDecl) {
5995     if (CheckPointerCall(NDecl, TheCall, Proto))
5996       return ExprError();
5997   } else {
5998     if (CheckOtherCall(TheCall, Proto))
5999       return ExprError();
6000   }
6001 
6002   return MaybeBindToTemporary(TheCall);
6003 }
6004 
6005 ExprResult
6006 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6007                            SourceLocation RParenLoc, Expr *InitExpr) {
6008   assert(Ty && "ActOnCompoundLiteral(): missing type");
6009   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6010 
6011   TypeSourceInfo *TInfo;
6012   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6013   if (!TInfo)
6014     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6015 
6016   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6017 }
6018 
6019 ExprResult
6020 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6021                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6022   QualType literalType = TInfo->getType();
6023 
6024   if (literalType->isArrayType()) {
6025     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6026           diag::err_illegal_decl_array_incomplete_type,
6027           SourceRange(LParenLoc,
6028                       LiteralExpr->getSourceRange().getEnd())))
6029       return ExprError();
6030     if (literalType->isVariableArrayType())
6031       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6032         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6033   } else if (!literalType->isDependentType() &&
6034              RequireCompleteType(LParenLoc, literalType,
6035                diag::err_typecheck_decl_incomplete_type,
6036                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6037     return ExprError();
6038 
6039   InitializedEntity Entity
6040     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6041   InitializationKind Kind
6042     = InitializationKind::CreateCStyleCast(LParenLoc,
6043                                            SourceRange(LParenLoc, RParenLoc),
6044                                            /*InitList=*/true);
6045   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6046   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6047                                       &literalType);
6048   if (Result.isInvalid())
6049     return ExprError();
6050   LiteralExpr = Result.get();
6051 
6052   bool isFileScope = !CurContext->isFunctionOrMethod();
6053 
6054   // In C, compound literals are l-values for some reason.
6055   // For GCC compatibility, in C++, file-scope array compound literals with
6056   // constant initializers are also l-values, and compound literals are
6057   // otherwise prvalues.
6058   //
6059   // (GCC also treats C++ list-initialized file-scope array prvalues with
6060   // constant initializers as l-values, but that's non-conforming, so we don't
6061   // follow it there.)
6062   //
6063   // FIXME: It would be better to handle the lvalue cases as materializing and
6064   // lifetime-extending a temporary object, but our materialized temporaries
6065   // representation only supports lifetime extension from a variable, not "out
6066   // of thin air".
6067   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6068   // is bound to the result of applying array-to-pointer decay to the compound
6069   // literal.
6070   // FIXME: GCC supports compound literals of reference type, which should
6071   // obviously have a value kind derived from the kind of reference involved.
6072   ExprValueKind VK =
6073       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6074           ? VK_RValue
6075           : VK_LValue;
6076 
6077   if (isFileScope)
6078     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6079       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6080         Expr *Init = ILE->getInit(i);
6081         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6082       }
6083 
6084   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6085                                               VK, LiteralExpr, isFileScope);
6086   if (isFileScope) {
6087     if (!LiteralExpr->isTypeDependent() &&
6088         !LiteralExpr->isValueDependent() &&
6089         !literalType->isDependentType()) // C99 6.5.2.5p3
6090       if (CheckForConstantInitializer(LiteralExpr, literalType))
6091         return ExprError();
6092   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6093              literalType.getAddressSpace() != LangAS::Default) {
6094     // Embedded-C extensions to C99 6.5.2.5:
6095     //   "If the compound literal occurs inside the body of a function, the
6096     //   type name shall not be qualified by an address-space qualifier."
6097     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6098       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6099     return ExprError();
6100   }
6101 
6102   return MaybeBindToTemporary(E);
6103 }
6104 
6105 ExprResult
6106 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6107                     SourceLocation RBraceLoc) {
6108   // Immediately handle non-overload placeholders.  Overloads can be
6109   // resolved contextually, but everything else here can't.
6110   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6111     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6112       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6113 
6114       // Ignore failures; dropping the entire initializer list because
6115       // of one failure would be terrible for indexing/etc.
6116       if (result.isInvalid()) continue;
6117 
6118       InitArgList[I] = result.get();
6119     }
6120   }
6121 
6122   // Semantic analysis for initializers is done by ActOnDeclarator() and
6123   // CheckInitializer() - it requires knowledge of the object being initialized.
6124 
6125   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6126                                                RBraceLoc);
6127   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6128   return E;
6129 }
6130 
6131 /// Do an explicit extend of the given block pointer if we're in ARC.
6132 void Sema::maybeExtendBlockObject(ExprResult &E) {
6133   assert(E.get()->getType()->isBlockPointerType());
6134   assert(E.get()->isRValue());
6135 
6136   // Only do this in an r-value context.
6137   if (!getLangOpts().ObjCAutoRefCount) return;
6138 
6139   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6140                                CK_ARCExtendBlockObject, E.get(),
6141                                /*base path*/ nullptr, VK_RValue);
6142   Cleanup.setExprNeedsCleanups(true);
6143 }
6144 
6145 /// Prepare a conversion of the given expression to an ObjC object
6146 /// pointer type.
6147 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6148   QualType type = E.get()->getType();
6149   if (type->isObjCObjectPointerType()) {
6150     return CK_BitCast;
6151   } else if (type->isBlockPointerType()) {
6152     maybeExtendBlockObject(E);
6153     return CK_BlockPointerToObjCPointerCast;
6154   } else {
6155     assert(type->isPointerType());
6156     return CK_CPointerToObjCPointerCast;
6157   }
6158 }
6159 
6160 /// Prepares for a scalar cast, performing all the necessary stages
6161 /// except the final cast and returning the kind required.
6162 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6163   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6164   // Also, callers should have filtered out the invalid cases with
6165   // pointers.  Everything else should be possible.
6166 
6167   QualType SrcTy = Src.get()->getType();
6168   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6169     return CK_NoOp;
6170 
6171   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6172   case Type::STK_MemberPointer:
6173     llvm_unreachable("member pointer type in C");
6174 
6175   case Type::STK_CPointer:
6176   case Type::STK_BlockPointer:
6177   case Type::STK_ObjCObjectPointer:
6178     switch (DestTy->getScalarTypeKind()) {
6179     case Type::STK_CPointer: {
6180       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6181       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6182       if (SrcAS != DestAS)
6183         return CK_AddressSpaceConversion;
6184       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6185         return CK_NoOp;
6186       return CK_BitCast;
6187     }
6188     case Type::STK_BlockPointer:
6189       return (SrcKind == Type::STK_BlockPointer
6190                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6191     case Type::STK_ObjCObjectPointer:
6192       if (SrcKind == Type::STK_ObjCObjectPointer)
6193         return CK_BitCast;
6194       if (SrcKind == Type::STK_CPointer)
6195         return CK_CPointerToObjCPointerCast;
6196       maybeExtendBlockObject(Src);
6197       return CK_BlockPointerToObjCPointerCast;
6198     case Type::STK_Bool:
6199       return CK_PointerToBoolean;
6200     case Type::STK_Integral:
6201       return CK_PointerToIntegral;
6202     case Type::STK_Floating:
6203     case Type::STK_FloatingComplex:
6204     case Type::STK_IntegralComplex:
6205     case Type::STK_MemberPointer:
6206     case Type::STK_FixedPoint:
6207       llvm_unreachable("illegal cast from pointer");
6208     }
6209     llvm_unreachable("Should have returned before this");
6210 
6211   case Type::STK_FixedPoint:
6212     switch (DestTy->getScalarTypeKind()) {
6213     case Type::STK_FixedPoint:
6214       return CK_FixedPointCast;
6215     case Type::STK_Bool:
6216       return CK_FixedPointToBoolean;
6217     case Type::STK_Integral:
6218       return CK_FixedPointToIntegral;
6219     case Type::STK_Floating:
6220     case Type::STK_IntegralComplex:
6221     case Type::STK_FloatingComplex:
6222       Diag(Src.get()->getExprLoc(),
6223            diag::err_unimplemented_conversion_with_fixed_point_type)
6224           << DestTy;
6225       return CK_IntegralCast;
6226     case Type::STK_CPointer:
6227     case Type::STK_ObjCObjectPointer:
6228     case Type::STK_BlockPointer:
6229     case Type::STK_MemberPointer:
6230       llvm_unreachable("illegal cast to pointer type");
6231     }
6232     llvm_unreachable("Should have returned before this");
6233 
6234   case Type::STK_Bool: // casting from bool is like casting from an integer
6235   case Type::STK_Integral:
6236     switch (DestTy->getScalarTypeKind()) {
6237     case Type::STK_CPointer:
6238     case Type::STK_ObjCObjectPointer:
6239     case Type::STK_BlockPointer:
6240       if (Src.get()->isNullPointerConstant(Context,
6241                                            Expr::NPC_ValueDependentIsNull))
6242         return CK_NullToPointer;
6243       return CK_IntegralToPointer;
6244     case Type::STK_Bool:
6245       return CK_IntegralToBoolean;
6246     case Type::STK_Integral:
6247       return CK_IntegralCast;
6248     case Type::STK_Floating:
6249       return CK_IntegralToFloating;
6250     case Type::STK_IntegralComplex:
6251       Src = ImpCastExprToType(Src.get(),
6252                       DestTy->castAs<ComplexType>()->getElementType(),
6253                       CK_IntegralCast);
6254       return CK_IntegralRealToComplex;
6255     case Type::STK_FloatingComplex:
6256       Src = ImpCastExprToType(Src.get(),
6257                       DestTy->castAs<ComplexType>()->getElementType(),
6258                       CK_IntegralToFloating);
6259       return CK_FloatingRealToComplex;
6260     case Type::STK_MemberPointer:
6261       llvm_unreachable("member pointer type in C");
6262     case Type::STK_FixedPoint:
6263       return CK_IntegralToFixedPoint;
6264     }
6265     llvm_unreachable("Should have returned before this");
6266 
6267   case Type::STK_Floating:
6268     switch (DestTy->getScalarTypeKind()) {
6269     case Type::STK_Floating:
6270       return CK_FloatingCast;
6271     case Type::STK_Bool:
6272       return CK_FloatingToBoolean;
6273     case Type::STK_Integral:
6274       return CK_FloatingToIntegral;
6275     case Type::STK_FloatingComplex:
6276       Src = ImpCastExprToType(Src.get(),
6277                               DestTy->castAs<ComplexType>()->getElementType(),
6278                               CK_FloatingCast);
6279       return CK_FloatingRealToComplex;
6280     case Type::STK_IntegralComplex:
6281       Src = ImpCastExprToType(Src.get(),
6282                               DestTy->castAs<ComplexType>()->getElementType(),
6283                               CK_FloatingToIntegral);
6284       return CK_IntegralRealToComplex;
6285     case Type::STK_CPointer:
6286     case Type::STK_ObjCObjectPointer:
6287     case Type::STK_BlockPointer:
6288       llvm_unreachable("valid float->pointer cast?");
6289     case Type::STK_MemberPointer:
6290       llvm_unreachable("member pointer type in C");
6291     case Type::STK_FixedPoint:
6292       Diag(Src.get()->getExprLoc(),
6293            diag::err_unimplemented_conversion_with_fixed_point_type)
6294           << SrcTy;
6295       return CK_IntegralCast;
6296     }
6297     llvm_unreachable("Should have returned before this");
6298 
6299   case Type::STK_FloatingComplex:
6300     switch (DestTy->getScalarTypeKind()) {
6301     case Type::STK_FloatingComplex:
6302       return CK_FloatingComplexCast;
6303     case Type::STK_IntegralComplex:
6304       return CK_FloatingComplexToIntegralComplex;
6305     case Type::STK_Floating: {
6306       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6307       if (Context.hasSameType(ET, DestTy))
6308         return CK_FloatingComplexToReal;
6309       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6310       return CK_FloatingCast;
6311     }
6312     case Type::STK_Bool:
6313       return CK_FloatingComplexToBoolean;
6314     case Type::STK_Integral:
6315       Src = ImpCastExprToType(Src.get(),
6316                               SrcTy->castAs<ComplexType>()->getElementType(),
6317                               CK_FloatingComplexToReal);
6318       return CK_FloatingToIntegral;
6319     case Type::STK_CPointer:
6320     case Type::STK_ObjCObjectPointer:
6321     case Type::STK_BlockPointer:
6322       llvm_unreachable("valid complex float->pointer cast?");
6323     case Type::STK_MemberPointer:
6324       llvm_unreachable("member pointer type in C");
6325     case Type::STK_FixedPoint:
6326       Diag(Src.get()->getExprLoc(),
6327            diag::err_unimplemented_conversion_with_fixed_point_type)
6328           << SrcTy;
6329       return CK_IntegralCast;
6330     }
6331     llvm_unreachable("Should have returned before this");
6332 
6333   case Type::STK_IntegralComplex:
6334     switch (DestTy->getScalarTypeKind()) {
6335     case Type::STK_FloatingComplex:
6336       return CK_IntegralComplexToFloatingComplex;
6337     case Type::STK_IntegralComplex:
6338       return CK_IntegralComplexCast;
6339     case Type::STK_Integral: {
6340       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6341       if (Context.hasSameType(ET, DestTy))
6342         return CK_IntegralComplexToReal;
6343       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6344       return CK_IntegralCast;
6345     }
6346     case Type::STK_Bool:
6347       return CK_IntegralComplexToBoolean;
6348     case Type::STK_Floating:
6349       Src = ImpCastExprToType(Src.get(),
6350                               SrcTy->castAs<ComplexType>()->getElementType(),
6351                               CK_IntegralComplexToReal);
6352       return CK_IntegralToFloating;
6353     case Type::STK_CPointer:
6354     case Type::STK_ObjCObjectPointer:
6355     case Type::STK_BlockPointer:
6356       llvm_unreachable("valid complex int->pointer cast?");
6357     case Type::STK_MemberPointer:
6358       llvm_unreachable("member pointer type in C");
6359     case Type::STK_FixedPoint:
6360       Diag(Src.get()->getExprLoc(),
6361            diag::err_unimplemented_conversion_with_fixed_point_type)
6362           << SrcTy;
6363       return CK_IntegralCast;
6364     }
6365     llvm_unreachable("Should have returned before this");
6366   }
6367 
6368   llvm_unreachable("Unhandled scalar cast");
6369 }
6370 
6371 static bool breakDownVectorType(QualType type, uint64_t &len,
6372                                 QualType &eltType) {
6373   // Vectors are simple.
6374   if (const VectorType *vecType = type->getAs<VectorType>()) {
6375     len = vecType->getNumElements();
6376     eltType = vecType->getElementType();
6377     assert(eltType->isScalarType());
6378     return true;
6379   }
6380 
6381   // We allow lax conversion to and from non-vector types, but only if
6382   // they're real types (i.e. non-complex, non-pointer scalar types).
6383   if (!type->isRealType()) return false;
6384 
6385   len = 1;
6386   eltType = type;
6387   return true;
6388 }
6389 
6390 /// Are the two types lax-compatible vector types?  That is, given
6391 /// that one of them is a vector, do they have equal storage sizes,
6392 /// where the storage size is the number of elements times the element
6393 /// size?
6394 ///
6395 /// This will also return false if either of the types is neither a
6396 /// vector nor a real type.
6397 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6398   assert(destTy->isVectorType() || srcTy->isVectorType());
6399 
6400   // Disallow lax conversions between scalars and ExtVectors (these
6401   // conversions are allowed for other vector types because common headers
6402   // depend on them).  Most scalar OP ExtVector cases are handled by the
6403   // splat path anyway, which does what we want (convert, not bitcast).
6404   // What this rules out for ExtVectors is crazy things like char4*float.
6405   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6406   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6407 
6408   uint64_t srcLen, destLen;
6409   QualType srcEltTy, destEltTy;
6410   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6411   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6412 
6413   // ASTContext::getTypeSize will return the size rounded up to a
6414   // power of 2, so instead of using that, we need to use the raw
6415   // element size multiplied by the element count.
6416   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6417   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6418 
6419   return (srcLen * srcEltSize == destLen * destEltSize);
6420 }
6421 
6422 /// Is this a legal conversion between two types, one of which is
6423 /// known to be a vector type?
6424 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6425   assert(destTy->isVectorType() || srcTy->isVectorType());
6426 
6427   if (!Context.getLangOpts().LaxVectorConversions)
6428     return false;
6429   return areLaxCompatibleVectorTypes(srcTy, destTy);
6430 }
6431 
6432 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6433                            CastKind &Kind) {
6434   assert(VectorTy->isVectorType() && "Not a vector type!");
6435 
6436   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6437     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6438       return Diag(R.getBegin(),
6439                   Ty->isVectorType() ?
6440                   diag::err_invalid_conversion_between_vectors :
6441                   diag::err_invalid_conversion_between_vector_and_integer)
6442         << VectorTy << Ty << R;
6443   } else
6444     return Diag(R.getBegin(),
6445                 diag::err_invalid_conversion_between_vector_and_scalar)
6446       << VectorTy << Ty << R;
6447 
6448   Kind = CK_BitCast;
6449   return false;
6450 }
6451 
6452 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6453   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6454 
6455   if (DestElemTy == SplattedExpr->getType())
6456     return SplattedExpr;
6457 
6458   assert(DestElemTy->isFloatingType() ||
6459          DestElemTy->isIntegralOrEnumerationType());
6460 
6461   CastKind CK;
6462   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6463     // OpenCL requires that we convert `true` boolean expressions to -1, but
6464     // only when splatting vectors.
6465     if (DestElemTy->isFloatingType()) {
6466       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6467       // in two steps: boolean to signed integral, then to floating.
6468       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6469                                                  CK_BooleanToSignedIntegral);
6470       SplattedExpr = CastExprRes.get();
6471       CK = CK_IntegralToFloating;
6472     } else {
6473       CK = CK_BooleanToSignedIntegral;
6474     }
6475   } else {
6476     ExprResult CastExprRes = SplattedExpr;
6477     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6478     if (CastExprRes.isInvalid())
6479       return ExprError();
6480     SplattedExpr = CastExprRes.get();
6481   }
6482   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6483 }
6484 
6485 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6486                                     Expr *CastExpr, CastKind &Kind) {
6487   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6488 
6489   QualType SrcTy = CastExpr->getType();
6490 
6491   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6492   // an ExtVectorType.
6493   // In OpenCL, casts between vectors of different types are not allowed.
6494   // (See OpenCL 6.2).
6495   if (SrcTy->isVectorType()) {
6496     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6497         (getLangOpts().OpenCL &&
6498          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6499       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6500         << DestTy << SrcTy << R;
6501       return ExprError();
6502     }
6503     Kind = CK_BitCast;
6504     return CastExpr;
6505   }
6506 
6507   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6508   // conversion will take place first from scalar to elt type, and then
6509   // splat from elt type to vector.
6510   if (SrcTy->isPointerType())
6511     return Diag(R.getBegin(),
6512                 diag::err_invalid_conversion_between_vector_and_scalar)
6513       << DestTy << SrcTy << R;
6514 
6515   Kind = CK_VectorSplat;
6516   return prepareVectorSplat(DestTy, CastExpr);
6517 }
6518 
6519 ExprResult
6520 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6521                     Declarator &D, ParsedType &Ty,
6522                     SourceLocation RParenLoc, Expr *CastExpr) {
6523   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6524          "ActOnCastExpr(): missing type or expr");
6525 
6526   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6527   if (D.isInvalidType())
6528     return ExprError();
6529 
6530   if (getLangOpts().CPlusPlus) {
6531     // Check that there are no default arguments (C++ only).
6532     CheckExtraCXXDefaultArguments(D);
6533   } else {
6534     // Make sure any TypoExprs have been dealt with.
6535     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6536     if (!Res.isUsable())
6537       return ExprError();
6538     CastExpr = Res.get();
6539   }
6540 
6541   checkUnusedDeclAttributes(D);
6542 
6543   QualType castType = castTInfo->getType();
6544   Ty = CreateParsedType(castType, castTInfo);
6545 
6546   bool isVectorLiteral = false;
6547 
6548   // Check for an altivec or OpenCL literal,
6549   // i.e. all the elements are integer constants.
6550   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6551   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6552   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6553        && castType->isVectorType() && (PE || PLE)) {
6554     if (PLE && PLE->getNumExprs() == 0) {
6555       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6556       return ExprError();
6557     }
6558     if (PE || PLE->getNumExprs() == 1) {
6559       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6560       if (!E->getType()->isVectorType())
6561         isVectorLiteral = true;
6562     }
6563     else
6564       isVectorLiteral = true;
6565   }
6566 
6567   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6568   // then handle it as such.
6569   if (isVectorLiteral)
6570     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6571 
6572   // If the Expr being casted is a ParenListExpr, handle it specially.
6573   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6574   // sequence of BinOp comma operators.
6575   if (isa<ParenListExpr>(CastExpr)) {
6576     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6577     if (Result.isInvalid()) return ExprError();
6578     CastExpr = Result.get();
6579   }
6580 
6581   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6582       !getSourceManager().isInSystemMacro(LParenLoc))
6583     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6584 
6585   CheckTollFreeBridgeCast(castType, CastExpr);
6586 
6587   CheckObjCBridgeRelatedCast(castType, CastExpr);
6588 
6589   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6590 
6591   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6592 }
6593 
6594 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6595                                     SourceLocation RParenLoc, Expr *E,
6596                                     TypeSourceInfo *TInfo) {
6597   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6598          "Expected paren or paren list expression");
6599 
6600   Expr **exprs;
6601   unsigned numExprs;
6602   Expr *subExpr;
6603   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6604   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6605     LiteralLParenLoc = PE->getLParenLoc();
6606     LiteralRParenLoc = PE->getRParenLoc();
6607     exprs = PE->getExprs();
6608     numExprs = PE->getNumExprs();
6609   } else { // isa<ParenExpr> by assertion at function entrance
6610     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6611     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6612     subExpr = cast<ParenExpr>(E)->getSubExpr();
6613     exprs = &subExpr;
6614     numExprs = 1;
6615   }
6616 
6617   QualType Ty = TInfo->getType();
6618   assert(Ty->isVectorType() && "Expected vector type");
6619 
6620   SmallVector<Expr *, 8> initExprs;
6621   const VectorType *VTy = Ty->getAs<VectorType>();
6622   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6623 
6624   // '(...)' form of vector initialization in AltiVec: the number of
6625   // initializers must be one or must match the size of the vector.
6626   // If a single value is specified in the initializer then it will be
6627   // replicated to all the components of the vector
6628   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6629     // The number of initializers must be one or must match the size of the
6630     // vector. If a single value is specified in the initializer then it will
6631     // be replicated to all the components of the vector
6632     if (numExprs == 1) {
6633       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6634       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6635       if (Literal.isInvalid())
6636         return ExprError();
6637       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6638                                   PrepareScalarCast(Literal, ElemTy));
6639       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6640     }
6641     else if (numExprs < numElems) {
6642       Diag(E->getExprLoc(),
6643            diag::err_incorrect_number_of_vector_initializers);
6644       return ExprError();
6645     }
6646     else
6647       initExprs.append(exprs, exprs + numExprs);
6648   }
6649   else {
6650     // For OpenCL, when the number of initializers is a single value,
6651     // it will be replicated to all components of the vector.
6652     if (getLangOpts().OpenCL &&
6653         VTy->getVectorKind() == VectorType::GenericVector &&
6654         numExprs == 1) {
6655         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6656         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6657         if (Literal.isInvalid())
6658           return ExprError();
6659         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6660                                     PrepareScalarCast(Literal, ElemTy));
6661         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6662     }
6663 
6664     initExprs.append(exprs, exprs + numExprs);
6665   }
6666   // FIXME: This means that pretty-printing the final AST will produce curly
6667   // braces instead of the original commas.
6668   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6669                                                    initExprs, LiteralRParenLoc);
6670   initE->setType(Ty);
6671   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6672 }
6673 
6674 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6675 /// the ParenListExpr into a sequence of comma binary operators.
6676 ExprResult
6677 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6678   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6679   if (!E)
6680     return OrigExpr;
6681 
6682   ExprResult Result(E->getExpr(0));
6683 
6684   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6685     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6686                         E->getExpr(i));
6687 
6688   if (Result.isInvalid()) return ExprError();
6689 
6690   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6691 }
6692 
6693 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6694                                     SourceLocation R,
6695                                     MultiExprArg Val) {
6696   return ParenListExpr::Create(Context, L, Val, R);
6697 }
6698 
6699 /// Emit a specialized diagnostic when one expression is a null pointer
6700 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6701 /// emitted.
6702 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6703                                       SourceLocation QuestionLoc) {
6704   Expr *NullExpr = LHSExpr;
6705   Expr *NonPointerExpr = RHSExpr;
6706   Expr::NullPointerConstantKind NullKind =
6707       NullExpr->isNullPointerConstant(Context,
6708                                       Expr::NPC_ValueDependentIsNotNull);
6709 
6710   if (NullKind == Expr::NPCK_NotNull) {
6711     NullExpr = RHSExpr;
6712     NonPointerExpr = LHSExpr;
6713     NullKind =
6714         NullExpr->isNullPointerConstant(Context,
6715                                         Expr::NPC_ValueDependentIsNotNull);
6716   }
6717 
6718   if (NullKind == Expr::NPCK_NotNull)
6719     return false;
6720 
6721   if (NullKind == Expr::NPCK_ZeroExpression)
6722     return false;
6723 
6724   if (NullKind == Expr::NPCK_ZeroLiteral) {
6725     // In this case, check to make sure that we got here from a "NULL"
6726     // string in the source code.
6727     NullExpr = NullExpr->IgnoreParenImpCasts();
6728     SourceLocation loc = NullExpr->getExprLoc();
6729     if (!findMacroSpelling(loc, "NULL"))
6730       return false;
6731   }
6732 
6733   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6734   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6735       << NonPointerExpr->getType() << DiagType
6736       << NonPointerExpr->getSourceRange();
6737   return true;
6738 }
6739 
6740 /// Return false if the condition expression is valid, true otherwise.
6741 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6742   QualType CondTy = Cond->getType();
6743 
6744   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6745   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6746     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6747       << CondTy << Cond->getSourceRange();
6748     return true;
6749   }
6750 
6751   // C99 6.5.15p2
6752   if (CondTy->isScalarType()) return false;
6753 
6754   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6755     << CondTy << Cond->getSourceRange();
6756   return true;
6757 }
6758 
6759 /// Handle when one or both operands are void type.
6760 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6761                                          ExprResult &RHS) {
6762     Expr *LHSExpr = LHS.get();
6763     Expr *RHSExpr = RHS.get();
6764 
6765     if (!LHSExpr->getType()->isVoidType())
6766       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6767           << RHSExpr->getSourceRange();
6768     if (!RHSExpr->getType()->isVoidType())
6769       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6770           << LHSExpr->getSourceRange();
6771     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6772     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6773     return S.Context.VoidTy;
6774 }
6775 
6776 /// Return false if the NullExpr can be promoted to PointerTy,
6777 /// true otherwise.
6778 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6779                                         QualType PointerTy) {
6780   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6781       !NullExpr.get()->isNullPointerConstant(S.Context,
6782                                             Expr::NPC_ValueDependentIsNull))
6783     return true;
6784 
6785   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6786   return false;
6787 }
6788 
6789 /// Checks compatibility between two pointers and return the resulting
6790 /// type.
6791 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6792                                                      ExprResult &RHS,
6793                                                      SourceLocation Loc) {
6794   QualType LHSTy = LHS.get()->getType();
6795   QualType RHSTy = RHS.get()->getType();
6796 
6797   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6798     // Two identical pointers types are always compatible.
6799     return LHSTy;
6800   }
6801 
6802   QualType lhptee, rhptee;
6803 
6804   // Get the pointee types.
6805   bool IsBlockPointer = false;
6806   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6807     lhptee = LHSBTy->getPointeeType();
6808     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6809     IsBlockPointer = true;
6810   } else {
6811     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6812     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6813   }
6814 
6815   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6816   // differently qualified versions of compatible types, the result type is
6817   // a pointer to an appropriately qualified version of the composite
6818   // type.
6819 
6820   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6821   // clause doesn't make sense for our extensions. E.g. address space 2 should
6822   // be incompatible with address space 3: they may live on different devices or
6823   // anything.
6824   Qualifiers lhQual = lhptee.getQualifiers();
6825   Qualifiers rhQual = rhptee.getQualifiers();
6826 
6827   LangAS ResultAddrSpace = LangAS::Default;
6828   LangAS LAddrSpace = lhQual.getAddressSpace();
6829   LangAS RAddrSpace = rhQual.getAddressSpace();
6830 
6831   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6832   // spaces is disallowed.
6833   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6834     ResultAddrSpace = LAddrSpace;
6835   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6836     ResultAddrSpace = RAddrSpace;
6837   else {
6838     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6839         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6840         << RHS.get()->getSourceRange();
6841     return QualType();
6842   }
6843 
6844   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6845   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6846   lhQual.removeCVRQualifiers();
6847   rhQual.removeCVRQualifiers();
6848 
6849   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6850   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6851   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6852   // qual types are compatible iff
6853   //  * corresponded types are compatible
6854   //  * CVR qualifiers are equal
6855   //  * address spaces are equal
6856   // Thus for conditional operator we merge CVR and address space unqualified
6857   // pointees and if there is a composite type we return a pointer to it with
6858   // merged qualifiers.
6859   LHSCastKind =
6860       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6861   RHSCastKind =
6862       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6863   lhQual.removeAddressSpace();
6864   rhQual.removeAddressSpace();
6865 
6866   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6867   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6868 
6869   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6870 
6871   if (CompositeTy.isNull()) {
6872     // In this situation, we assume void* type. No especially good
6873     // reason, but this is what gcc does, and we do have to pick
6874     // to get a consistent AST.
6875     QualType incompatTy;
6876     incompatTy = S.Context.getPointerType(
6877         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6878     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6879     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6880 
6881     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6882     // for casts between types with incompatible address space qualifiers.
6883     // For the following code the compiler produces casts between global and
6884     // local address spaces of the corresponded innermost pointees:
6885     // local int *global *a;
6886     // global int *global *b;
6887     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6888     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6889         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6890         << RHS.get()->getSourceRange();
6891 
6892     return incompatTy;
6893   }
6894 
6895   // The pointer types are compatible.
6896   // In case of OpenCL ResultTy should have the address space qualifier
6897   // which is a superset of address spaces of both the 2nd and the 3rd
6898   // operands of the conditional operator.
6899   QualType ResultTy = [&, ResultAddrSpace]() {
6900     if (S.getLangOpts().OpenCL) {
6901       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6902       CompositeQuals.setAddressSpace(ResultAddrSpace);
6903       return S.Context
6904           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6905           .withCVRQualifiers(MergedCVRQual);
6906     }
6907     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6908   }();
6909   if (IsBlockPointer)
6910     ResultTy = S.Context.getBlockPointerType(ResultTy);
6911   else
6912     ResultTy = S.Context.getPointerType(ResultTy);
6913 
6914   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6915   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6916   return ResultTy;
6917 }
6918 
6919 /// Return the resulting type when the operands are both block pointers.
6920 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6921                                                           ExprResult &LHS,
6922                                                           ExprResult &RHS,
6923                                                           SourceLocation Loc) {
6924   QualType LHSTy = LHS.get()->getType();
6925   QualType RHSTy = RHS.get()->getType();
6926 
6927   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6928     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6929       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6930       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6931       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6932       return destType;
6933     }
6934     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6935       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6936       << RHS.get()->getSourceRange();
6937     return QualType();
6938   }
6939 
6940   // We have 2 block pointer types.
6941   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6942 }
6943 
6944 /// Return the resulting type when the operands are both pointers.
6945 static QualType
6946 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6947                                             ExprResult &RHS,
6948                                             SourceLocation Loc) {
6949   // get the pointer types
6950   QualType LHSTy = LHS.get()->getType();
6951   QualType RHSTy = RHS.get()->getType();
6952 
6953   // get the "pointed to" types
6954   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6955   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6956 
6957   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6958   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6959     // Figure out necessary qualifiers (C99 6.5.15p6)
6960     QualType destPointee
6961       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6962     QualType destType = S.Context.getPointerType(destPointee);
6963     // Add qualifiers if necessary.
6964     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6965     // Promote to void*.
6966     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6967     return destType;
6968   }
6969   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6970     QualType destPointee
6971       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6972     QualType destType = S.Context.getPointerType(destPointee);
6973     // Add qualifiers if necessary.
6974     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6975     // Promote to void*.
6976     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6977     return destType;
6978   }
6979 
6980   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6981 }
6982 
6983 /// Return false if the first expression is not an integer and the second
6984 /// expression is not a pointer, true otherwise.
6985 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6986                                         Expr* PointerExpr, SourceLocation Loc,
6987                                         bool IsIntFirstExpr) {
6988   if (!PointerExpr->getType()->isPointerType() ||
6989       !Int.get()->getType()->isIntegerType())
6990     return false;
6991 
6992   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6993   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6994 
6995   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6996     << Expr1->getType() << Expr2->getType()
6997     << Expr1->getSourceRange() << Expr2->getSourceRange();
6998   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6999                             CK_IntegralToPointer);
7000   return true;
7001 }
7002 
7003 /// Simple conversion between integer and floating point types.
7004 ///
7005 /// Used when handling the OpenCL conditional operator where the
7006 /// condition is a vector while the other operands are scalar.
7007 ///
7008 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7009 /// types are either integer or floating type. Between the two
7010 /// operands, the type with the higher rank is defined as the "result
7011 /// type". The other operand needs to be promoted to the same type. No
7012 /// other type promotion is allowed. We cannot use
7013 /// UsualArithmeticConversions() for this purpose, since it always
7014 /// promotes promotable types.
7015 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7016                                             ExprResult &RHS,
7017                                             SourceLocation QuestionLoc) {
7018   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7019   if (LHS.isInvalid())
7020     return QualType();
7021   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7022   if (RHS.isInvalid())
7023     return QualType();
7024 
7025   // For conversion purposes, we ignore any qualifiers.
7026   // For example, "const float" and "float" are equivalent.
7027   QualType LHSType =
7028     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7029   QualType RHSType =
7030     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7031 
7032   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7033     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7034       << LHSType << LHS.get()->getSourceRange();
7035     return QualType();
7036   }
7037 
7038   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7039     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7040       << RHSType << RHS.get()->getSourceRange();
7041     return QualType();
7042   }
7043 
7044   // If both types are identical, no conversion is needed.
7045   if (LHSType == RHSType)
7046     return LHSType;
7047 
7048   // Now handle "real" floating types (i.e. float, double, long double).
7049   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7050     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7051                                  /*IsCompAssign = */ false);
7052 
7053   // Finally, we have two differing integer types.
7054   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7055   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7056 }
7057 
7058 /// Convert scalar operands to a vector that matches the
7059 ///        condition in length.
7060 ///
7061 /// Used when handling the OpenCL conditional operator where the
7062 /// condition is a vector while the other operands are scalar.
7063 ///
7064 /// We first compute the "result type" for the scalar operands
7065 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7066 /// into a vector of that type where the length matches the condition
7067 /// vector type. s6.11.6 requires that the element types of the result
7068 /// and the condition must have the same number of bits.
7069 static QualType
7070 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7071                               QualType CondTy, SourceLocation QuestionLoc) {
7072   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7073   if (ResTy.isNull()) return QualType();
7074 
7075   const VectorType *CV = CondTy->getAs<VectorType>();
7076   assert(CV);
7077 
7078   // Determine the vector result type
7079   unsigned NumElements = CV->getNumElements();
7080   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7081 
7082   // Ensure that all types have the same number of bits
7083   if (S.Context.getTypeSize(CV->getElementType())
7084       != S.Context.getTypeSize(ResTy)) {
7085     // Since VectorTy is created internally, it does not pretty print
7086     // with an OpenCL name. Instead, we just print a description.
7087     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7088     SmallString<64> Str;
7089     llvm::raw_svector_ostream OS(Str);
7090     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7091     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7092       << CondTy << OS.str();
7093     return QualType();
7094   }
7095 
7096   // Convert operands to the vector result type
7097   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7098   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7099 
7100   return VectorTy;
7101 }
7102 
7103 /// Return false if this is a valid OpenCL condition vector
7104 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7105                                        SourceLocation QuestionLoc) {
7106   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7107   // integral type.
7108   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7109   assert(CondTy);
7110   QualType EleTy = CondTy->getElementType();
7111   if (EleTy->isIntegerType()) return false;
7112 
7113   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7114     << Cond->getType() << Cond->getSourceRange();
7115   return true;
7116 }
7117 
7118 /// Return false if the vector condition type and the vector
7119 ///        result type are compatible.
7120 ///
7121 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7122 /// number of elements, and their element types have the same number
7123 /// of bits.
7124 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7125                               SourceLocation QuestionLoc) {
7126   const VectorType *CV = CondTy->getAs<VectorType>();
7127   const VectorType *RV = VecResTy->getAs<VectorType>();
7128   assert(CV && RV);
7129 
7130   if (CV->getNumElements() != RV->getNumElements()) {
7131     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7132       << CondTy << VecResTy;
7133     return true;
7134   }
7135 
7136   QualType CVE = CV->getElementType();
7137   QualType RVE = RV->getElementType();
7138 
7139   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7140     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7141       << CondTy << VecResTy;
7142     return true;
7143   }
7144 
7145   return false;
7146 }
7147 
7148 /// Return the resulting type for the conditional operator in
7149 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7150 ///        s6.3.i) when the condition is a vector type.
7151 static QualType
7152 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7153                              ExprResult &LHS, ExprResult &RHS,
7154                              SourceLocation QuestionLoc) {
7155   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7156   if (Cond.isInvalid())
7157     return QualType();
7158   QualType CondTy = Cond.get()->getType();
7159 
7160   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7161     return QualType();
7162 
7163   // If either operand is a vector then find the vector type of the
7164   // result as specified in OpenCL v1.1 s6.3.i.
7165   if (LHS.get()->getType()->isVectorType() ||
7166       RHS.get()->getType()->isVectorType()) {
7167     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7168                                               /*isCompAssign*/false,
7169                                               /*AllowBothBool*/true,
7170                                               /*AllowBoolConversions*/false);
7171     if (VecResTy.isNull()) return QualType();
7172     // The result type must match the condition type as specified in
7173     // OpenCL v1.1 s6.11.6.
7174     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7175       return QualType();
7176     return VecResTy;
7177   }
7178 
7179   // Both operands are scalar.
7180   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7181 }
7182 
7183 /// Return true if the Expr is block type
7184 static bool checkBlockType(Sema &S, const Expr *E) {
7185   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7186     QualType Ty = CE->getCallee()->getType();
7187     if (Ty->isBlockPointerType()) {
7188       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7189       return true;
7190     }
7191   }
7192   return false;
7193 }
7194 
7195 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7196 /// In that case, LHS = cond.
7197 /// C99 6.5.15
7198 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7199                                         ExprResult &RHS, ExprValueKind &VK,
7200                                         ExprObjectKind &OK,
7201                                         SourceLocation QuestionLoc) {
7202 
7203   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7204   if (!LHSResult.isUsable()) return QualType();
7205   LHS = LHSResult;
7206 
7207   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7208   if (!RHSResult.isUsable()) return QualType();
7209   RHS = RHSResult;
7210 
7211   // C++ is sufficiently different to merit its own checker.
7212   if (getLangOpts().CPlusPlus)
7213     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7214 
7215   VK = VK_RValue;
7216   OK = OK_Ordinary;
7217 
7218   // The OpenCL operator with a vector condition is sufficiently
7219   // different to merit its own checker.
7220   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7221     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7222 
7223   // First, check the condition.
7224   Cond = UsualUnaryConversions(Cond.get());
7225   if (Cond.isInvalid())
7226     return QualType();
7227   if (checkCondition(*this, Cond.get(), QuestionLoc))
7228     return QualType();
7229 
7230   // Now check the two expressions.
7231   if (LHS.get()->getType()->isVectorType() ||
7232       RHS.get()->getType()->isVectorType())
7233     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7234                                /*AllowBothBool*/true,
7235                                /*AllowBoolConversions*/false);
7236 
7237   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7238   if (LHS.isInvalid() || RHS.isInvalid())
7239     return QualType();
7240 
7241   QualType LHSTy = LHS.get()->getType();
7242   QualType RHSTy = RHS.get()->getType();
7243 
7244   // Diagnose attempts to convert between __float128 and long double where
7245   // such conversions currently can't be handled.
7246   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7247     Diag(QuestionLoc,
7248          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7249       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7250     return QualType();
7251   }
7252 
7253   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7254   // selection operator (?:).
7255   if (getLangOpts().OpenCL &&
7256       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7257     return QualType();
7258   }
7259 
7260   // If both operands have arithmetic type, do the usual arithmetic conversions
7261   // to find a common type: C99 6.5.15p3,5.
7262   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7263     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7264     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7265 
7266     return ResTy;
7267   }
7268 
7269   // If both operands are the same structure or union type, the result is that
7270   // type.
7271   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7272     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7273       if (LHSRT->getDecl() == RHSRT->getDecl())
7274         // "If both the operands have structure or union type, the result has
7275         // that type."  This implies that CV qualifiers are dropped.
7276         return LHSTy.getUnqualifiedType();
7277     // FIXME: Type of conditional expression must be complete in C mode.
7278   }
7279 
7280   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7281   // The following || allows only one side to be void (a GCC-ism).
7282   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7283     return checkConditionalVoidType(*this, LHS, RHS);
7284   }
7285 
7286   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7287   // the type of the other operand."
7288   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7289   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7290 
7291   // All objective-c pointer type analysis is done here.
7292   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7293                                                         QuestionLoc);
7294   if (LHS.isInvalid() || RHS.isInvalid())
7295     return QualType();
7296   if (!compositeType.isNull())
7297     return compositeType;
7298 
7299 
7300   // Handle block pointer types.
7301   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7302     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7303                                                      QuestionLoc);
7304 
7305   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7306   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7307     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7308                                                        QuestionLoc);
7309 
7310   // GCC compatibility: soften pointer/integer mismatch.  Note that
7311   // null pointers have been filtered out by this point.
7312   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7313       /*IsIntFirstExpr=*/true))
7314     return RHSTy;
7315   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7316       /*IsIntFirstExpr=*/false))
7317     return LHSTy;
7318 
7319   // Emit a better diagnostic if one of the expressions is a null pointer
7320   // constant and the other is not a pointer type. In this case, the user most
7321   // likely forgot to take the address of the other expression.
7322   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7323     return QualType();
7324 
7325   // Otherwise, the operands are not compatible.
7326   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7327     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7328     << RHS.get()->getSourceRange();
7329   return QualType();
7330 }
7331 
7332 /// FindCompositeObjCPointerType - Helper method to find composite type of
7333 /// two objective-c pointer types of the two input expressions.
7334 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7335                                             SourceLocation QuestionLoc) {
7336   QualType LHSTy = LHS.get()->getType();
7337   QualType RHSTy = RHS.get()->getType();
7338 
7339   // Handle things like Class and struct objc_class*.  Here we case the result
7340   // to the pseudo-builtin, because that will be implicitly cast back to the
7341   // redefinition type if an attempt is made to access its fields.
7342   if (LHSTy->isObjCClassType() &&
7343       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7344     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7345     return LHSTy;
7346   }
7347   if (RHSTy->isObjCClassType() &&
7348       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7349     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7350     return RHSTy;
7351   }
7352   // And the same for struct objc_object* / id
7353   if (LHSTy->isObjCIdType() &&
7354       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7355     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7356     return LHSTy;
7357   }
7358   if (RHSTy->isObjCIdType() &&
7359       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7360     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7361     return RHSTy;
7362   }
7363   // And the same for struct objc_selector* / SEL
7364   if (Context.isObjCSelType(LHSTy) &&
7365       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7366     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7367     return LHSTy;
7368   }
7369   if (Context.isObjCSelType(RHSTy) &&
7370       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7371     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7372     return RHSTy;
7373   }
7374   // Check constraints for Objective-C object pointers types.
7375   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7376 
7377     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7378       // Two identical object pointer types are always compatible.
7379       return LHSTy;
7380     }
7381     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7382     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7383     QualType compositeType = LHSTy;
7384 
7385     // If both operands are interfaces and either operand can be
7386     // assigned to the other, use that type as the composite
7387     // type. This allows
7388     //   xxx ? (A*) a : (B*) b
7389     // where B is a subclass of A.
7390     //
7391     // Additionally, as for assignment, if either type is 'id'
7392     // allow silent coercion. Finally, if the types are
7393     // incompatible then make sure to use 'id' as the composite
7394     // type so the result is acceptable for sending messages to.
7395 
7396     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7397     // It could return the composite type.
7398     if (!(compositeType =
7399           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7400       // Nothing more to do.
7401     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7402       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7403     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7404       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7405     } else if ((LHSTy->isObjCQualifiedIdType() ||
7406                 RHSTy->isObjCQualifiedIdType()) &&
7407                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7408       // Need to handle "id<xx>" explicitly.
7409       // GCC allows qualified id and any Objective-C type to devolve to
7410       // id. Currently localizing to here until clear this should be
7411       // part of ObjCQualifiedIdTypesAreCompatible.
7412       compositeType = Context.getObjCIdType();
7413     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7414       compositeType = Context.getObjCIdType();
7415     } else {
7416       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7417       << LHSTy << RHSTy
7418       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7419       QualType incompatTy = Context.getObjCIdType();
7420       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7421       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7422       return incompatTy;
7423     }
7424     // The object pointer types are compatible.
7425     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7426     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7427     return compositeType;
7428   }
7429   // Check Objective-C object pointer types and 'void *'
7430   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7431     if (getLangOpts().ObjCAutoRefCount) {
7432       // ARC forbids the implicit conversion of object pointers to 'void *',
7433       // so these types are not compatible.
7434       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7435           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7436       LHS = RHS = true;
7437       return QualType();
7438     }
7439     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7440     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7441     QualType destPointee
7442     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7443     QualType destType = Context.getPointerType(destPointee);
7444     // Add qualifiers if necessary.
7445     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7446     // Promote to void*.
7447     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7448     return destType;
7449   }
7450   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7451     if (getLangOpts().ObjCAutoRefCount) {
7452       // ARC forbids the implicit conversion of object pointers to 'void *',
7453       // so these types are not compatible.
7454       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7455           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7456       LHS = RHS = true;
7457       return QualType();
7458     }
7459     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7460     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7461     QualType destPointee
7462     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7463     QualType destType = Context.getPointerType(destPointee);
7464     // Add qualifiers if necessary.
7465     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7466     // Promote to void*.
7467     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7468     return destType;
7469   }
7470   return QualType();
7471 }
7472 
7473 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7474 /// ParenRange in parentheses.
7475 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7476                                const PartialDiagnostic &Note,
7477                                SourceRange ParenRange) {
7478   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7479   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7480       EndLoc.isValid()) {
7481     Self.Diag(Loc, Note)
7482       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7483       << FixItHint::CreateInsertion(EndLoc, ")");
7484   } else {
7485     // We can't display the parentheses, so just show the bare note.
7486     Self.Diag(Loc, Note) << ParenRange;
7487   }
7488 }
7489 
7490 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7491   return BinaryOperator::isAdditiveOp(Opc) ||
7492          BinaryOperator::isMultiplicativeOp(Opc) ||
7493          BinaryOperator::isShiftOp(Opc);
7494 }
7495 
7496 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7497 /// expression, either using a built-in or overloaded operator,
7498 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7499 /// expression.
7500 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7501                                    Expr **RHSExprs) {
7502   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7503   E = E->IgnoreImpCasts();
7504   E = E->IgnoreConversionOperator();
7505   E = E->IgnoreImpCasts();
7506   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7507     E = MTE->GetTemporaryExpr();
7508     E = E->IgnoreImpCasts();
7509   }
7510 
7511   // Built-in binary operator.
7512   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7513     if (IsArithmeticOp(OP->getOpcode())) {
7514       *Opcode = OP->getOpcode();
7515       *RHSExprs = OP->getRHS();
7516       return true;
7517     }
7518   }
7519 
7520   // Overloaded operator.
7521   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7522     if (Call->getNumArgs() != 2)
7523       return false;
7524 
7525     // Make sure this is really a binary operator that is safe to pass into
7526     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7527     OverloadedOperatorKind OO = Call->getOperator();
7528     if (OO < OO_Plus || OO > OO_Arrow ||
7529         OO == OO_PlusPlus || OO == OO_MinusMinus)
7530       return false;
7531 
7532     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7533     if (IsArithmeticOp(OpKind)) {
7534       *Opcode = OpKind;
7535       *RHSExprs = Call->getArg(1);
7536       return true;
7537     }
7538   }
7539 
7540   return false;
7541 }
7542 
7543 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7544 /// or is a logical expression such as (x==y) which has int type, but is
7545 /// commonly interpreted as boolean.
7546 static bool ExprLooksBoolean(Expr *E) {
7547   E = E->IgnoreParenImpCasts();
7548 
7549   if (E->getType()->isBooleanType())
7550     return true;
7551   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7552     return OP->isComparisonOp() || OP->isLogicalOp();
7553   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7554     return OP->getOpcode() == UO_LNot;
7555   if (E->getType()->isPointerType())
7556     return true;
7557   // FIXME: What about overloaded operator calls returning "unspecified boolean
7558   // type"s (commonly pointer-to-members)?
7559 
7560   return false;
7561 }
7562 
7563 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7564 /// and binary operator are mixed in a way that suggests the programmer assumed
7565 /// the conditional operator has higher precedence, for example:
7566 /// "int x = a + someBinaryCondition ? 1 : 2".
7567 static void DiagnoseConditionalPrecedence(Sema &Self,
7568                                           SourceLocation OpLoc,
7569                                           Expr *Condition,
7570                                           Expr *LHSExpr,
7571                                           Expr *RHSExpr) {
7572   BinaryOperatorKind CondOpcode;
7573   Expr *CondRHS;
7574 
7575   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7576     return;
7577   if (!ExprLooksBoolean(CondRHS))
7578     return;
7579 
7580   // The condition is an arithmetic binary expression, with a right-
7581   // hand side that looks boolean, so warn.
7582 
7583   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7584       << Condition->getSourceRange()
7585       << BinaryOperator::getOpcodeStr(CondOpcode);
7586 
7587   SuggestParentheses(
7588       Self, OpLoc,
7589       Self.PDiag(diag::note_precedence_silence)
7590           << BinaryOperator::getOpcodeStr(CondOpcode),
7591       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7592 
7593   SuggestParentheses(Self, OpLoc,
7594                      Self.PDiag(diag::note_precedence_conditional_first),
7595                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7596 }
7597 
7598 /// Compute the nullability of a conditional expression.
7599 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7600                                               QualType LHSTy, QualType RHSTy,
7601                                               ASTContext &Ctx) {
7602   if (!ResTy->isAnyPointerType())
7603     return ResTy;
7604 
7605   auto GetNullability = [&Ctx](QualType Ty) {
7606     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7607     if (Kind)
7608       return *Kind;
7609     return NullabilityKind::Unspecified;
7610   };
7611 
7612   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7613   NullabilityKind MergedKind;
7614 
7615   // Compute nullability of a binary conditional expression.
7616   if (IsBin) {
7617     if (LHSKind == NullabilityKind::NonNull)
7618       MergedKind = NullabilityKind::NonNull;
7619     else
7620       MergedKind = RHSKind;
7621   // Compute nullability of a normal conditional expression.
7622   } else {
7623     if (LHSKind == NullabilityKind::Nullable ||
7624         RHSKind == NullabilityKind::Nullable)
7625       MergedKind = NullabilityKind::Nullable;
7626     else if (LHSKind == NullabilityKind::NonNull)
7627       MergedKind = RHSKind;
7628     else if (RHSKind == NullabilityKind::NonNull)
7629       MergedKind = LHSKind;
7630     else
7631       MergedKind = NullabilityKind::Unspecified;
7632   }
7633 
7634   // Return if ResTy already has the correct nullability.
7635   if (GetNullability(ResTy) == MergedKind)
7636     return ResTy;
7637 
7638   // Strip all nullability from ResTy.
7639   while (ResTy->getNullability(Ctx))
7640     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7641 
7642   // Create a new AttributedType with the new nullability kind.
7643   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7644   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7645 }
7646 
7647 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7648 /// in the case of a the GNU conditional expr extension.
7649 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7650                                     SourceLocation ColonLoc,
7651                                     Expr *CondExpr, Expr *LHSExpr,
7652                                     Expr *RHSExpr) {
7653   if (!getLangOpts().CPlusPlus) {
7654     // C cannot handle TypoExpr nodes in the condition because it
7655     // doesn't handle dependent types properly, so make sure any TypoExprs have
7656     // been dealt with before checking the operands.
7657     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7658     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7659     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7660 
7661     if (!CondResult.isUsable())
7662       return ExprError();
7663 
7664     if (LHSExpr) {
7665       if (!LHSResult.isUsable())
7666         return ExprError();
7667     }
7668 
7669     if (!RHSResult.isUsable())
7670       return ExprError();
7671 
7672     CondExpr = CondResult.get();
7673     LHSExpr = LHSResult.get();
7674     RHSExpr = RHSResult.get();
7675   }
7676 
7677   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7678   // was the condition.
7679   OpaqueValueExpr *opaqueValue = nullptr;
7680   Expr *commonExpr = nullptr;
7681   if (!LHSExpr) {
7682     commonExpr = CondExpr;
7683     // Lower out placeholder types first.  This is important so that we don't
7684     // try to capture a placeholder. This happens in few cases in C++; such
7685     // as Objective-C++'s dictionary subscripting syntax.
7686     if (commonExpr->hasPlaceholderType()) {
7687       ExprResult result = CheckPlaceholderExpr(commonExpr);
7688       if (!result.isUsable()) return ExprError();
7689       commonExpr = result.get();
7690     }
7691     // We usually want to apply unary conversions *before* saving, except
7692     // in the special case of a C++ l-value conditional.
7693     if (!(getLangOpts().CPlusPlus
7694           && !commonExpr->isTypeDependent()
7695           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7696           && commonExpr->isGLValue()
7697           && commonExpr->isOrdinaryOrBitFieldObject()
7698           && RHSExpr->isOrdinaryOrBitFieldObject()
7699           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7700       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7701       if (commonRes.isInvalid())
7702         return ExprError();
7703       commonExpr = commonRes.get();
7704     }
7705 
7706     // If the common expression is a class or array prvalue, materialize it
7707     // so that we can safely refer to it multiple times.
7708     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7709                                    commonExpr->getType()->isArrayType())) {
7710       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7711       if (MatExpr.isInvalid())
7712         return ExprError();
7713       commonExpr = MatExpr.get();
7714     }
7715 
7716     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7717                                                 commonExpr->getType(),
7718                                                 commonExpr->getValueKind(),
7719                                                 commonExpr->getObjectKind(),
7720                                                 commonExpr);
7721     LHSExpr = CondExpr = opaqueValue;
7722   }
7723 
7724   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7725   ExprValueKind VK = VK_RValue;
7726   ExprObjectKind OK = OK_Ordinary;
7727   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7728   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7729                                              VK, OK, QuestionLoc);
7730   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7731       RHS.isInvalid())
7732     return ExprError();
7733 
7734   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7735                                 RHS.get());
7736 
7737   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7738 
7739   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7740                                          Context);
7741 
7742   if (!commonExpr)
7743     return new (Context)
7744         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7745                             RHS.get(), result, VK, OK);
7746 
7747   return new (Context) BinaryConditionalOperator(
7748       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7749       ColonLoc, result, VK, OK);
7750 }
7751 
7752 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7753 // being closely modeled after the C99 spec:-). The odd characteristic of this
7754 // routine is it effectively iqnores the qualifiers on the top level pointee.
7755 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7756 // FIXME: add a couple examples in this comment.
7757 static Sema::AssignConvertType
7758 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7759   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7760   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7761 
7762   // get the "pointed to" type (ignoring qualifiers at the top level)
7763   const Type *lhptee, *rhptee;
7764   Qualifiers lhq, rhq;
7765   std::tie(lhptee, lhq) =
7766       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7767   std::tie(rhptee, rhq) =
7768       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7769 
7770   Sema::AssignConvertType ConvTy = Sema::Compatible;
7771 
7772   // C99 6.5.16.1p1: This following citation is common to constraints
7773   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7774   // qualifiers of the type *pointed to* by the right;
7775 
7776   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7777   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7778       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7779     // Ignore lifetime for further calculation.
7780     lhq.removeObjCLifetime();
7781     rhq.removeObjCLifetime();
7782   }
7783 
7784   if (!lhq.compatiblyIncludes(rhq)) {
7785     // Treat address-space mismatches as fatal.
7786     if (!lhq.isAddressSpaceSupersetOf(rhq))
7787       return Sema::IncompatiblePointerDiscardsQualifiers;
7788 
7789     // It's okay to add or remove GC or lifetime qualifiers when converting to
7790     // and from void*.
7791     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7792                         .compatiblyIncludes(
7793                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7794              && (lhptee->isVoidType() || rhptee->isVoidType()))
7795       ; // keep old
7796 
7797     // Treat lifetime mismatches as fatal.
7798     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7799       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7800 
7801     // For GCC/MS compatibility, other qualifier mismatches are treated
7802     // as still compatible in C.
7803     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7804   }
7805 
7806   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7807   // incomplete type and the other is a pointer to a qualified or unqualified
7808   // version of void...
7809   if (lhptee->isVoidType()) {
7810     if (rhptee->isIncompleteOrObjectType())
7811       return ConvTy;
7812 
7813     // As an extension, we allow cast to/from void* to function pointer.
7814     assert(rhptee->isFunctionType());
7815     return Sema::FunctionVoidPointer;
7816   }
7817 
7818   if (rhptee->isVoidType()) {
7819     if (lhptee->isIncompleteOrObjectType())
7820       return ConvTy;
7821 
7822     // As an extension, we allow cast to/from void* to function pointer.
7823     assert(lhptee->isFunctionType());
7824     return Sema::FunctionVoidPointer;
7825   }
7826 
7827   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7828   // unqualified versions of compatible types, ...
7829   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7830   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7831     // Check if the pointee types are compatible ignoring the sign.
7832     // We explicitly check for char so that we catch "char" vs
7833     // "unsigned char" on systems where "char" is unsigned.
7834     if (lhptee->isCharType())
7835       ltrans = S.Context.UnsignedCharTy;
7836     else if (lhptee->hasSignedIntegerRepresentation())
7837       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7838 
7839     if (rhptee->isCharType())
7840       rtrans = S.Context.UnsignedCharTy;
7841     else if (rhptee->hasSignedIntegerRepresentation())
7842       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7843 
7844     if (ltrans == rtrans) {
7845       // Types are compatible ignoring the sign. Qualifier incompatibility
7846       // takes priority over sign incompatibility because the sign
7847       // warning can be disabled.
7848       if (ConvTy != Sema::Compatible)
7849         return ConvTy;
7850 
7851       return Sema::IncompatiblePointerSign;
7852     }
7853 
7854     // If we are a multi-level pointer, it's possible that our issue is simply
7855     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7856     // the eventual target type is the same and the pointers have the same
7857     // level of indirection, this must be the issue.
7858     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7859       do {
7860         std::tie(lhptee, lhq) =
7861           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7862         std::tie(rhptee, rhq) =
7863           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7864 
7865         // Inconsistent address spaces at this point is invalid, even if the
7866         // address spaces would be compatible.
7867         // FIXME: This doesn't catch address space mismatches for pointers of
7868         // different nesting levels, like:
7869         //   __local int *** a;
7870         //   int ** b = a;
7871         // It's not clear how to actually determine when such pointers are
7872         // invalidly incompatible.
7873         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7874           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7875 
7876       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7877 
7878       if (lhptee == rhptee)
7879         return Sema::IncompatibleNestedPointerQualifiers;
7880     }
7881 
7882     // General pointer incompatibility takes priority over qualifiers.
7883     return Sema::IncompatiblePointer;
7884   }
7885   if (!S.getLangOpts().CPlusPlus &&
7886       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7887     return Sema::IncompatiblePointer;
7888   return ConvTy;
7889 }
7890 
7891 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7892 /// block pointer types are compatible or whether a block and normal pointer
7893 /// are compatible. It is more restrict than comparing two function pointer
7894 // types.
7895 static Sema::AssignConvertType
7896 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7897                                     QualType RHSType) {
7898   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7899   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7900 
7901   QualType lhptee, rhptee;
7902 
7903   // get the "pointed to" type (ignoring qualifiers at the top level)
7904   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7905   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7906 
7907   // In C++, the types have to match exactly.
7908   if (S.getLangOpts().CPlusPlus)
7909     return Sema::IncompatibleBlockPointer;
7910 
7911   Sema::AssignConvertType ConvTy = Sema::Compatible;
7912 
7913   // For blocks we enforce that qualifiers are identical.
7914   Qualifiers LQuals = lhptee.getLocalQualifiers();
7915   Qualifiers RQuals = rhptee.getLocalQualifiers();
7916   if (S.getLangOpts().OpenCL) {
7917     LQuals.removeAddressSpace();
7918     RQuals.removeAddressSpace();
7919   }
7920   if (LQuals != RQuals)
7921     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7922 
7923   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7924   // assignment.
7925   // The current behavior is similar to C++ lambdas. A block might be
7926   // assigned to a variable iff its return type and parameters are compatible
7927   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7928   // an assignment. Presumably it should behave in way that a function pointer
7929   // assignment does in C, so for each parameter and return type:
7930   //  * CVR and address space of LHS should be a superset of CVR and address
7931   //  space of RHS.
7932   //  * unqualified types should be compatible.
7933   if (S.getLangOpts().OpenCL) {
7934     if (!S.Context.typesAreBlockPointerCompatible(
7935             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7936             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7937       return Sema::IncompatibleBlockPointer;
7938   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7939     return Sema::IncompatibleBlockPointer;
7940 
7941   return ConvTy;
7942 }
7943 
7944 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7945 /// for assignment compatibility.
7946 static Sema::AssignConvertType
7947 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7948                                    QualType RHSType) {
7949   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7950   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7951 
7952   if (LHSType->isObjCBuiltinType()) {
7953     // Class is not compatible with ObjC object pointers.
7954     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7955         !RHSType->isObjCQualifiedClassType())
7956       return Sema::IncompatiblePointer;
7957     return Sema::Compatible;
7958   }
7959   if (RHSType->isObjCBuiltinType()) {
7960     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7961         !LHSType->isObjCQualifiedClassType())
7962       return Sema::IncompatiblePointer;
7963     return Sema::Compatible;
7964   }
7965   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7966   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7967 
7968   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7969       // make an exception for id<P>
7970       !LHSType->isObjCQualifiedIdType())
7971     return Sema::CompatiblePointerDiscardsQualifiers;
7972 
7973   if (S.Context.typesAreCompatible(LHSType, RHSType))
7974     return Sema::Compatible;
7975   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7976     return Sema::IncompatibleObjCQualifiedId;
7977   return Sema::IncompatiblePointer;
7978 }
7979 
7980 Sema::AssignConvertType
7981 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7982                                  QualType LHSType, QualType RHSType) {
7983   // Fake up an opaque expression.  We don't actually care about what
7984   // cast operations are required, so if CheckAssignmentConstraints
7985   // adds casts to this they'll be wasted, but fortunately that doesn't
7986   // usually happen on valid code.
7987   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7988   ExprResult RHSPtr = &RHSExpr;
7989   CastKind K;
7990 
7991   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7992 }
7993 
7994 /// This helper function returns true if QT is a vector type that has element
7995 /// type ElementType.
7996 static bool isVector(QualType QT, QualType ElementType) {
7997   if (const VectorType *VT = QT->getAs<VectorType>())
7998     return VT->getElementType() == ElementType;
7999   return false;
8000 }
8001 
8002 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8003 /// has code to accommodate several GCC extensions when type checking
8004 /// pointers. Here are some objectionable examples that GCC considers warnings:
8005 ///
8006 ///  int a, *pint;
8007 ///  short *pshort;
8008 ///  struct foo *pfoo;
8009 ///
8010 ///  pint = pshort; // warning: assignment from incompatible pointer type
8011 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8012 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8013 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8014 ///
8015 /// As a result, the code for dealing with pointers is more complex than the
8016 /// C99 spec dictates.
8017 ///
8018 /// Sets 'Kind' for any result kind except Incompatible.
8019 Sema::AssignConvertType
8020 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8021                                  CastKind &Kind, bool ConvertRHS) {
8022   QualType RHSType = RHS.get()->getType();
8023   QualType OrigLHSType = LHSType;
8024 
8025   // Get canonical types.  We're not formatting these types, just comparing
8026   // them.
8027   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8028   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8029 
8030   // Common case: no conversion required.
8031   if (LHSType == RHSType) {
8032     Kind = CK_NoOp;
8033     return Compatible;
8034   }
8035 
8036   // If we have an atomic type, try a non-atomic assignment, then just add an
8037   // atomic qualification step.
8038   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8039     Sema::AssignConvertType result =
8040       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8041     if (result != Compatible)
8042       return result;
8043     if (Kind != CK_NoOp && ConvertRHS)
8044       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8045     Kind = CK_NonAtomicToAtomic;
8046     return Compatible;
8047   }
8048 
8049   // If the left-hand side is a reference type, then we are in a
8050   // (rare!) case where we've allowed the use of references in C,
8051   // e.g., as a parameter type in a built-in function. In this case,
8052   // just make sure that the type referenced is compatible with the
8053   // right-hand side type. The caller is responsible for adjusting
8054   // LHSType so that the resulting expression does not have reference
8055   // type.
8056   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8057     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8058       Kind = CK_LValueBitCast;
8059       return Compatible;
8060     }
8061     return Incompatible;
8062   }
8063 
8064   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8065   // to the same ExtVector type.
8066   if (LHSType->isExtVectorType()) {
8067     if (RHSType->isExtVectorType())
8068       return Incompatible;
8069     if (RHSType->isArithmeticType()) {
8070       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8071       if (ConvertRHS)
8072         RHS = prepareVectorSplat(LHSType, RHS.get());
8073       Kind = CK_VectorSplat;
8074       return Compatible;
8075     }
8076   }
8077 
8078   // Conversions to or from vector type.
8079   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8080     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8081       // Allow assignments of an AltiVec vector type to an equivalent GCC
8082       // vector type and vice versa
8083       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8084         Kind = CK_BitCast;
8085         return Compatible;
8086       }
8087 
8088       // If we are allowing lax vector conversions, and LHS and RHS are both
8089       // vectors, the total size only needs to be the same. This is a bitcast;
8090       // no bits are changed but the result type is different.
8091       if (isLaxVectorConversion(RHSType, LHSType)) {
8092         Kind = CK_BitCast;
8093         return IncompatibleVectors;
8094       }
8095     }
8096 
8097     // When the RHS comes from another lax conversion (e.g. binops between
8098     // scalars and vectors) the result is canonicalized as a vector. When the
8099     // LHS is also a vector, the lax is allowed by the condition above. Handle
8100     // the case where LHS is a scalar.
8101     if (LHSType->isScalarType()) {
8102       const VectorType *VecType = RHSType->getAs<VectorType>();
8103       if (VecType && VecType->getNumElements() == 1 &&
8104           isLaxVectorConversion(RHSType, LHSType)) {
8105         ExprResult *VecExpr = &RHS;
8106         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8107         Kind = CK_BitCast;
8108         return Compatible;
8109       }
8110     }
8111 
8112     return Incompatible;
8113   }
8114 
8115   // Diagnose attempts to convert between __float128 and long double where
8116   // such conversions currently can't be handled.
8117   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8118     return Incompatible;
8119 
8120   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8121   // discards the imaginary part.
8122   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8123       !LHSType->getAs<ComplexType>())
8124     return Incompatible;
8125 
8126   // Arithmetic conversions.
8127   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8128       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8129     if (ConvertRHS)
8130       Kind = PrepareScalarCast(RHS, LHSType);
8131     return Compatible;
8132   }
8133 
8134   // Conversions to normal pointers.
8135   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8136     // U* -> T*
8137     if (isa<PointerType>(RHSType)) {
8138       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8139       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8140       if (AddrSpaceL != AddrSpaceR)
8141         Kind = CK_AddressSpaceConversion;
8142       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8143         Kind = CK_NoOp;
8144       else
8145         Kind = CK_BitCast;
8146       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8147     }
8148 
8149     // int -> T*
8150     if (RHSType->isIntegerType()) {
8151       Kind = CK_IntegralToPointer; // FIXME: null?
8152       return IntToPointer;
8153     }
8154 
8155     // C pointers are not compatible with ObjC object pointers,
8156     // with two exceptions:
8157     if (isa<ObjCObjectPointerType>(RHSType)) {
8158       //  - conversions to void*
8159       if (LHSPointer->getPointeeType()->isVoidType()) {
8160         Kind = CK_BitCast;
8161         return Compatible;
8162       }
8163 
8164       //  - conversions from 'Class' to the redefinition type
8165       if (RHSType->isObjCClassType() &&
8166           Context.hasSameType(LHSType,
8167                               Context.getObjCClassRedefinitionType())) {
8168         Kind = CK_BitCast;
8169         return Compatible;
8170       }
8171 
8172       Kind = CK_BitCast;
8173       return IncompatiblePointer;
8174     }
8175 
8176     // U^ -> void*
8177     if (RHSType->getAs<BlockPointerType>()) {
8178       if (LHSPointer->getPointeeType()->isVoidType()) {
8179         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8180         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8181                                 ->getPointeeType()
8182                                 .getAddressSpace();
8183         Kind =
8184             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8185         return Compatible;
8186       }
8187     }
8188 
8189     return Incompatible;
8190   }
8191 
8192   // Conversions to block pointers.
8193   if (isa<BlockPointerType>(LHSType)) {
8194     // U^ -> T^
8195     if (RHSType->isBlockPointerType()) {
8196       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8197                               ->getPointeeType()
8198                               .getAddressSpace();
8199       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8200                               ->getPointeeType()
8201                               .getAddressSpace();
8202       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8203       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8204     }
8205 
8206     // int or null -> T^
8207     if (RHSType->isIntegerType()) {
8208       Kind = CK_IntegralToPointer; // FIXME: null
8209       return IntToBlockPointer;
8210     }
8211 
8212     // id -> T^
8213     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8214       Kind = CK_AnyPointerToBlockPointerCast;
8215       return Compatible;
8216     }
8217 
8218     // void* -> T^
8219     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8220       if (RHSPT->getPointeeType()->isVoidType()) {
8221         Kind = CK_AnyPointerToBlockPointerCast;
8222         return Compatible;
8223       }
8224 
8225     return Incompatible;
8226   }
8227 
8228   // Conversions to Objective-C pointers.
8229   if (isa<ObjCObjectPointerType>(LHSType)) {
8230     // A* -> B*
8231     if (RHSType->isObjCObjectPointerType()) {
8232       Kind = CK_BitCast;
8233       Sema::AssignConvertType result =
8234         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8235       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8236           result == Compatible &&
8237           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8238         result = IncompatibleObjCWeakRef;
8239       return result;
8240     }
8241 
8242     // int or null -> A*
8243     if (RHSType->isIntegerType()) {
8244       Kind = CK_IntegralToPointer; // FIXME: null
8245       return IntToPointer;
8246     }
8247 
8248     // In general, C pointers are not compatible with ObjC object pointers,
8249     // with two exceptions:
8250     if (isa<PointerType>(RHSType)) {
8251       Kind = CK_CPointerToObjCPointerCast;
8252 
8253       //  - conversions from 'void*'
8254       if (RHSType->isVoidPointerType()) {
8255         return Compatible;
8256       }
8257 
8258       //  - conversions to 'Class' from its redefinition type
8259       if (LHSType->isObjCClassType() &&
8260           Context.hasSameType(RHSType,
8261                               Context.getObjCClassRedefinitionType())) {
8262         return Compatible;
8263       }
8264 
8265       return IncompatiblePointer;
8266     }
8267 
8268     // Only under strict condition T^ is compatible with an Objective-C pointer.
8269     if (RHSType->isBlockPointerType() &&
8270         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8271       if (ConvertRHS)
8272         maybeExtendBlockObject(RHS);
8273       Kind = CK_BlockPointerToObjCPointerCast;
8274       return Compatible;
8275     }
8276 
8277     return Incompatible;
8278   }
8279 
8280   // Conversions from pointers that are not covered by the above.
8281   if (isa<PointerType>(RHSType)) {
8282     // T* -> _Bool
8283     if (LHSType == Context.BoolTy) {
8284       Kind = CK_PointerToBoolean;
8285       return Compatible;
8286     }
8287 
8288     // T* -> int
8289     if (LHSType->isIntegerType()) {
8290       Kind = CK_PointerToIntegral;
8291       return PointerToInt;
8292     }
8293 
8294     return Incompatible;
8295   }
8296 
8297   // Conversions from Objective-C pointers that are not covered by the above.
8298   if (isa<ObjCObjectPointerType>(RHSType)) {
8299     // T* -> _Bool
8300     if (LHSType == Context.BoolTy) {
8301       Kind = CK_PointerToBoolean;
8302       return Compatible;
8303     }
8304 
8305     // T* -> int
8306     if (LHSType->isIntegerType()) {
8307       Kind = CK_PointerToIntegral;
8308       return PointerToInt;
8309     }
8310 
8311     return Incompatible;
8312   }
8313 
8314   // struct A -> struct B
8315   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8316     if (Context.typesAreCompatible(LHSType, RHSType)) {
8317       Kind = CK_NoOp;
8318       return Compatible;
8319     }
8320   }
8321 
8322   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8323     Kind = CK_IntToOCLSampler;
8324     return Compatible;
8325   }
8326 
8327   return Incompatible;
8328 }
8329 
8330 /// Constructs a transparent union from an expression that is
8331 /// used to initialize the transparent union.
8332 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8333                                       ExprResult &EResult, QualType UnionType,
8334                                       FieldDecl *Field) {
8335   // Build an initializer list that designates the appropriate member
8336   // of the transparent union.
8337   Expr *E = EResult.get();
8338   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8339                                                    E, SourceLocation());
8340   Initializer->setType(UnionType);
8341   Initializer->setInitializedFieldInUnion(Field);
8342 
8343   // Build a compound literal constructing a value of the transparent
8344   // union type from this initializer list.
8345   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8346   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8347                                         VK_RValue, Initializer, false);
8348 }
8349 
8350 Sema::AssignConvertType
8351 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8352                                                ExprResult &RHS) {
8353   QualType RHSType = RHS.get()->getType();
8354 
8355   // If the ArgType is a Union type, we want to handle a potential
8356   // transparent_union GCC extension.
8357   const RecordType *UT = ArgType->getAsUnionType();
8358   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8359     return Incompatible;
8360 
8361   // The field to initialize within the transparent union.
8362   RecordDecl *UD = UT->getDecl();
8363   FieldDecl *InitField = nullptr;
8364   // It's compatible if the expression matches any of the fields.
8365   for (auto *it : UD->fields()) {
8366     if (it->getType()->isPointerType()) {
8367       // If the transparent union contains a pointer type, we allow:
8368       // 1) void pointer
8369       // 2) null pointer constant
8370       if (RHSType->isPointerType())
8371         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8372           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8373           InitField = it;
8374           break;
8375         }
8376 
8377       if (RHS.get()->isNullPointerConstant(Context,
8378                                            Expr::NPC_ValueDependentIsNull)) {
8379         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8380                                 CK_NullToPointer);
8381         InitField = it;
8382         break;
8383       }
8384     }
8385 
8386     CastKind Kind;
8387     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8388           == Compatible) {
8389       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8390       InitField = it;
8391       break;
8392     }
8393   }
8394 
8395   if (!InitField)
8396     return Incompatible;
8397 
8398   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8399   return Compatible;
8400 }
8401 
8402 Sema::AssignConvertType
8403 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8404                                        bool Diagnose,
8405                                        bool DiagnoseCFAudited,
8406                                        bool ConvertRHS) {
8407   // We need to be able to tell the caller whether we diagnosed a problem, if
8408   // they ask us to issue diagnostics.
8409   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8410 
8411   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8412   // we can't avoid *all* modifications at the moment, so we need some somewhere
8413   // to put the updated value.
8414   ExprResult LocalRHS = CallerRHS;
8415   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8416 
8417   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8418     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8419       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8420           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8421         Diag(RHS.get()->getExprLoc(),
8422              diag::warn_noderef_to_dereferenceable_pointer)
8423             << RHS.get()->getSourceRange();
8424       }
8425     }
8426   }
8427 
8428   if (getLangOpts().CPlusPlus) {
8429     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8430       // C++ 5.17p3: If the left operand is not of class type, the
8431       // expression is implicitly converted (C++ 4) to the
8432       // cv-unqualified type of the left operand.
8433       QualType RHSType = RHS.get()->getType();
8434       if (Diagnose) {
8435         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8436                                         AA_Assigning);
8437       } else {
8438         ImplicitConversionSequence ICS =
8439             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8440                                   /*SuppressUserConversions=*/false,
8441                                   /*AllowExplicit=*/false,
8442                                   /*InOverloadResolution=*/false,
8443                                   /*CStyle=*/false,
8444                                   /*AllowObjCWritebackConversion=*/false);
8445         if (ICS.isFailure())
8446           return Incompatible;
8447         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8448                                         ICS, AA_Assigning);
8449       }
8450       if (RHS.isInvalid())
8451         return Incompatible;
8452       Sema::AssignConvertType result = Compatible;
8453       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8454           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8455         result = IncompatibleObjCWeakRef;
8456       return result;
8457     }
8458 
8459     // FIXME: Currently, we fall through and treat C++ classes like C
8460     // structures.
8461     // FIXME: We also fall through for atomics; not sure what should
8462     // happen there, though.
8463   } else if (RHS.get()->getType() == Context.OverloadTy) {
8464     // As a set of extensions to C, we support overloading on functions. These
8465     // functions need to be resolved here.
8466     DeclAccessPair DAP;
8467     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8468             RHS.get(), LHSType, /*Complain=*/false, DAP))
8469       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8470     else
8471       return Incompatible;
8472   }
8473 
8474   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8475   // a null pointer constant.
8476   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8477        LHSType->isBlockPointerType()) &&
8478       RHS.get()->isNullPointerConstant(Context,
8479                                        Expr::NPC_ValueDependentIsNull)) {
8480     if (Diagnose || ConvertRHS) {
8481       CastKind Kind;
8482       CXXCastPath Path;
8483       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8484                              /*IgnoreBaseAccess=*/false, Diagnose);
8485       if (ConvertRHS)
8486         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8487     }
8488     return Compatible;
8489   }
8490 
8491   // OpenCL queue_t type assignment.
8492   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8493                                  Context, Expr::NPC_ValueDependentIsNull)) {
8494     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8495     return Compatible;
8496   }
8497 
8498   // This check seems unnatural, however it is necessary to ensure the proper
8499   // conversion of functions/arrays. If the conversion were done for all
8500   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8501   // expressions that suppress this implicit conversion (&, sizeof).
8502   //
8503   // Suppress this for references: C++ 8.5.3p5.
8504   if (!LHSType->isReferenceType()) {
8505     // FIXME: We potentially allocate here even if ConvertRHS is false.
8506     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8507     if (RHS.isInvalid())
8508       return Incompatible;
8509   }
8510   CastKind Kind;
8511   Sema::AssignConvertType result =
8512     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8513 
8514   // C99 6.5.16.1p2: The value of the right operand is converted to the
8515   // type of the assignment expression.
8516   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8517   // so that we can use references in built-in functions even in C.
8518   // The getNonReferenceType() call makes sure that the resulting expression
8519   // does not have reference type.
8520   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8521     QualType Ty = LHSType.getNonLValueExprType(Context);
8522     Expr *E = RHS.get();
8523 
8524     // Check for various Objective-C errors. If we are not reporting
8525     // diagnostics and just checking for errors, e.g., during overload
8526     // resolution, return Incompatible to indicate the failure.
8527     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8528         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8529                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8530       if (!Diagnose)
8531         return Incompatible;
8532     }
8533     if (getLangOpts().ObjC &&
8534         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8535                                            E->getType(), E, Diagnose) ||
8536          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8537       if (!Diagnose)
8538         return Incompatible;
8539       // Replace the expression with a corrected version and continue so we
8540       // can find further errors.
8541       RHS = E;
8542       return Compatible;
8543     }
8544 
8545     if (ConvertRHS)
8546       RHS = ImpCastExprToType(E, Ty, Kind);
8547   }
8548 
8549   return result;
8550 }
8551 
8552 namespace {
8553 /// The original operand to an operator, prior to the application of the usual
8554 /// arithmetic conversions and converting the arguments of a builtin operator
8555 /// candidate.
8556 struct OriginalOperand {
8557   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8558     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8559       Op = MTE->GetTemporaryExpr();
8560     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8561       Op = BTE->getSubExpr();
8562     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8563       Orig = ICE->getSubExprAsWritten();
8564       Conversion = ICE->getConversionFunction();
8565     }
8566   }
8567 
8568   QualType getType() const { return Orig->getType(); }
8569 
8570   Expr *Orig;
8571   NamedDecl *Conversion;
8572 };
8573 }
8574 
8575 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8576                                ExprResult &RHS) {
8577   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8578 
8579   Diag(Loc, diag::err_typecheck_invalid_operands)
8580     << OrigLHS.getType() << OrigRHS.getType()
8581     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8582 
8583   // If a user-defined conversion was applied to either of the operands prior
8584   // to applying the built-in operator rules, tell the user about it.
8585   if (OrigLHS.Conversion) {
8586     Diag(OrigLHS.Conversion->getLocation(),
8587          diag::note_typecheck_invalid_operands_converted)
8588       << 0 << LHS.get()->getType();
8589   }
8590   if (OrigRHS.Conversion) {
8591     Diag(OrigRHS.Conversion->getLocation(),
8592          diag::note_typecheck_invalid_operands_converted)
8593       << 1 << RHS.get()->getType();
8594   }
8595 
8596   return QualType();
8597 }
8598 
8599 // Diagnose cases where a scalar was implicitly converted to a vector and
8600 // diagnose the underlying types. Otherwise, diagnose the error
8601 // as invalid vector logical operands for non-C++ cases.
8602 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8603                                             ExprResult &RHS) {
8604   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8605   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8606 
8607   bool LHSNatVec = LHSType->isVectorType();
8608   bool RHSNatVec = RHSType->isVectorType();
8609 
8610   if (!(LHSNatVec && RHSNatVec)) {
8611     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8612     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8613     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8614         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8615         << Vector->getSourceRange();
8616     return QualType();
8617   }
8618 
8619   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8620       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8621       << RHS.get()->getSourceRange();
8622 
8623   return QualType();
8624 }
8625 
8626 /// Try to convert a value of non-vector type to a vector type by converting
8627 /// the type to the element type of the vector and then performing a splat.
8628 /// If the language is OpenCL, we only use conversions that promote scalar
8629 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8630 /// for float->int.
8631 ///
8632 /// OpenCL V2.0 6.2.6.p2:
8633 /// An error shall occur if any scalar operand type has greater rank
8634 /// than the type of the vector element.
8635 ///
8636 /// \param scalar - if non-null, actually perform the conversions
8637 /// \return true if the operation fails (but without diagnosing the failure)
8638 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8639                                      QualType scalarTy,
8640                                      QualType vectorEltTy,
8641                                      QualType vectorTy,
8642                                      unsigned &DiagID) {
8643   // The conversion to apply to the scalar before splatting it,
8644   // if necessary.
8645   CastKind scalarCast = CK_NoOp;
8646 
8647   if (vectorEltTy->isIntegralType(S.Context)) {
8648     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8649         (scalarTy->isIntegerType() &&
8650          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8651       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8652       return true;
8653     }
8654     if (!scalarTy->isIntegralType(S.Context))
8655       return true;
8656     scalarCast = CK_IntegralCast;
8657   } else if (vectorEltTy->isRealFloatingType()) {
8658     if (scalarTy->isRealFloatingType()) {
8659       if (S.getLangOpts().OpenCL &&
8660           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8661         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8662         return true;
8663       }
8664       scalarCast = CK_FloatingCast;
8665     }
8666     else if (scalarTy->isIntegralType(S.Context))
8667       scalarCast = CK_IntegralToFloating;
8668     else
8669       return true;
8670   } else {
8671     return true;
8672   }
8673 
8674   // Adjust scalar if desired.
8675   if (scalar) {
8676     if (scalarCast != CK_NoOp)
8677       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8678     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8679   }
8680   return false;
8681 }
8682 
8683 /// Convert vector E to a vector with the same number of elements but different
8684 /// element type.
8685 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8686   const auto *VecTy = E->getType()->getAs<VectorType>();
8687   assert(VecTy && "Expression E must be a vector");
8688   QualType NewVecTy = S.Context.getVectorType(ElementType,
8689                                               VecTy->getNumElements(),
8690                                               VecTy->getVectorKind());
8691 
8692   // Look through the implicit cast. Return the subexpression if its type is
8693   // NewVecTy.
8694   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8695     if (ICE->getSubExpr()->getType() == NewVecTy)
8696       return ICE->getSubExpr();
8697 
8698   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8699   return S.ImpCastExprToType(E, NewVecTy, Cast);
8700 }
8701 
8702 /// Test if a (constant) integer Int can be casted to another integer type
8703 /// IntTy without losing precision.
8704 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8705                                       QualType OtherIntTy) {
8706   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8707 
8708   // Reject cases where the value of the Int is unknown as that would
8709   // possibly cause truncation, but accept cases where the scalar can be
8710   // demoted without loss of precision.
8711   Expr::EvalResult EVResult;
8712   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8713   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8714   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8715   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8716 
8717   if (CstInt) {
8718     // If the scalar is constant and is of a higher order and has more active
8719     // bits that the vector element type, reject it.
8720     llvm::APSInt Result = EVResult.Val.getInt();
8721     unsigned NumBits = IntSigned
8722                            ? (Result.isNegative() ? Result.getMinSignedBits()
8723                                                   : Result.getActiveBits())
8724                            : Result.getActiveBits();
8725     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8726       return true;
8727 
8728     // If the signedness of the scalar type and the vector element type
8729     // differs and the number of bits is greater than that of the vector
8730     // element reject it.
8731     return (IntSigned != OtherIntSigned &&
8732             NumBits > S.Context.getIntWidth(OtherIntTy));
8733   }
8734 
8735   // Reject cases where the value of the scalar is not constant and it's
8736   // order is greater than that of the vector element type.
8737   return (Order < 0);
8738 }
8739 
8740 /// Test if a (constant) integer Int can be casted to floating point type
8741 /// FloatTy without losing precision.
8742 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8743                                      QualType FloatTy) {
8744   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8745 
8746   // Determine if the integer constant can be expressed as a floating point
8747   // number of the appropriate type.
8748   Expr::EvalResult EVResult;
8749   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8750 
8751   uint64_t Bits = 0;
8752   if (CstInt) {
8753     // Reject constants that would be truncated if they were converted to
8754     // the floating point type. Test by simple to/from conversion.
8755     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8756     //        could be avoided if there was a convertFromAPInt method
8757     //        which could signal back if implicit truncation occurred.
8758     llvm::APSInt Result = EVResult.Val.getInt();
8759     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8760     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8761                            llvm::APFloat::rmTowardZero);
8762     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8763                              !IntTy->hasSignedIntegerRepresentation());
8764     bool Ignored = false;
8765     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8766                            &Ignored);
8767     if (Result != ConvertBack)
8768       return true;
8769   } else {
8770     // Reject types that cannot be fully encoded into the mantissa of
8771     // the float.
8772     Bits = S.Context.getTypeSize(IntTy);
8773     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8774         S.Context.getFloatTypeSemantics(FloatTy));
8775     if (Bits > FloatPrec)
8776       return true;
8777   }
8778 
8779   return false;
8780 }
8781 
8782 /// Attempt to convert and splat Scalar into a vector whose types matches
8783 /// Vector following GCC conversion rules. The rule is that implicit
8784 /// conversion can occur when Scalar can be casted to match Vector's element
8785 /// type without causing truncation of Scalar.
8786 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8787                                         ExprResult *Vector) {
8788   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8789   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8790   const VectorType *VT = VectorTy->getAs<VectorType>();
8791 
8792   assert(!isa<ExtVectorType>(VT) &&
8793          "ExtVectorTypes should not be handled here!");
8794 
8795   QualType VectorEltTy = VT->getElementType();
8796 
8797   // Reject cases where the vector element type or the scalar element type are
8798   // not integral or floating point types.
8799   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8800     return true;
8801 
8802   // The conversion to apply to the scalar before splatting it,
8803   // if necessary.
8804   CastKind ScalarCast = CK_NoOp;
8805 
8806   // Accept cases where the vector elements are integers and the scalar is
8807   // an integer.
8808   // FIXME: Notionally if the scalar was a floating point value with a precise
8809   //        integral representation, we could cast it to an appropriate integer
8810   //        type and then perform the rest of the checks here. GCC will perform
8811   //        this conversion in some cases as determined by the input language.
8812   //        We should accept it on a language independent basis.
8813   if (VectorEltTy->isIntegralType(S.Context) &&
8814       ScalarTy->isIntegralType(S.Context) &&
8815       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8816 
8817     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8818       return true;
8819 
8820     ScalarCast = CK_IntegralCast;
8821   } else if (VectorEltTy->isRealFloatingType()) {
8822     if (ScalarTy->isRealFloatingType()) {
8823 
8824       // Reject cases where the scalar type is not a constant and has a higher
8825       // Order than the vector element type.
8826       llvm::APFloat Result(0.0);
8827       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8828       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8829       if (!CstScalar && Order < 0)
8830         return true;
8831 
8832       // If the scalar cannot be safely casted to the vector element type,
8833       // reject it.
8834       if (CstScalar) {
8835         bool Truncated = false;
8836         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8837                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8838         if (Truncated)
8839           return true;
8840       }
8841 
8842       ScalarCast = CK_FloatingCast;
8843     } else if (ScalarTy->isIntegralType(S.Context)) {
8844       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8845         return true;
8846 
8847       ScalarCast = CK_IntegralToFloating;
8848     } else
8849       return true;
8850   }
8851 
8852   // Adjust scalar if desired.
8853   if (Scalar) {
8854     if (ScalarCast != CK_NoOp)
8855       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8856     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8857   }
8858   return false;
8859 }
8860 
8861 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8862                                    SourceLocation Loc, bool IsCompAssign,
8863                                    bool AllowBothBool,
8864                                    bool AllowBoolConversions) {
8865   if (!IsCompAssign) {
8866     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8867     if (LHS.isInvalid())
8868       return QualType();
8869   }
8870   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8871   if (RHS.isInvalid())
8872     return QualType();
8873 
8874   // For conversion purposes, we ignore any qualifiers.
8875   // For example, "const float" and "float" are equivalent.
8876   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8877   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8878 
8879   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8880   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8881   assert(LHSVecType || RHSVecType);
8882 
8883   // AltiVec-style "vector bool op vector bool" combinations are allowed
8884   // for some operators but not others.
8885   if (!AllowBothBool &&
8886       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8887       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8888     return InvalidOperands(Loc, LHS, RHS);
8889 
8890   // If the vector types are identical, return.
8891   if (Context.hasSameType(LHSType, RHSType))
8892     return LHSType;
8893 
8894   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8895   if (LHSVecType && RHSVecType &&
8896       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8897     if (isa<ExtVectorType>(LHSVecType)) {
8898       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8899       return LHSType;
8900     }
8901 
8902     if (!IsCompAssign)
8903       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8904     return RHSType;
8905   }
8906 
8907   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8908   // can be mixed, with the result being the non-bool type.  The non-bool
8909   // operand must have integer element type.
8910   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8911       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8912       (Context.getTypeSize(LHSVecType->getElementType()) ==
8913        Context.getTypeSize(RHSVecType->getElementType()))) {
8914     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8915         LHSVecType->getElementType()->isIntegerType() &&
8916         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8917       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8918       return LHSType;
8919     }
8920     if (!IsCompAssign &&
8921         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8922         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8923         RHSVecType->getElementType()->isIntegerType()) {
8924       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8925       return RHSType;
8926     }
8927   }
8928 
8929   // If there's a vector type and a scalar, try to convert the scalar to
8930   // the vector element type and splat.
8931   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8932   if (!RHSVecType) {
8933     if (isa<ExtVectorType>(LHSVecType)) {
8934       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8935                                     LHSVecType->getElementType(), LHSType,
8936                                     DiagID))
8937         return LHSType;
8938     } else {
8939       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8940         return LHSType;
8941     }
8942   }
8943   if (!LHSVecType) {
8944     if (isa<ExtVectorType>(RHSVecType)) {
8945       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8946                                     LHSType, RHSVecType->getElementType(),
8947                                     RHSType, DiagID))
8948         return RHSType;
8949     } else {
8950       if (LHS.get()->getValueKind() == VK_LValue ||
8951           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8952         return RHSType;
8953     }
8954   }
8955 
8956   // FIXME: The code below also handles conversion between vectors and
8957   // non-scalars, we should break this down into fine grained specific checks
8958   // and emit proper diagnostics.
8959   QualType VecType = LHSVecType ? LHSType : RHSType;
8960   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8961   QualType OtherType = LHSVecType ? RHSType : LHSType;
8962   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8963   if (isLaxVectorConversion(OtherType, VecType)) {
8964     // If we're allowing lax vector conversions, only the total (data) size
8965     // needs to be the same. For non compound assignment, if one of the types is
8966     // scalar, the result is always the vector type.
8967     if (!IsCompAssign) {
8968       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8969       return VecType;
8970     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8971     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8972     // type. Note that this is already done by non-compound assignments in
8973     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8974     // <1 x T> -> T. The result is also a vector type.
8975     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8976                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8977       ExprResult *RHSExpr = &RHS;
8978       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8979       return VecType;
8980     }
8981   }
8982 
8983   // Okay, the expression is invalid.
8984 
8985   // If there's a non-vector, non-real operand, diagnose that.
8986   if ((!RHSVecType && !RHSType->isRealType()) ||
8987       (!LHSVecType && !LHSType->isRealType())) {
8988     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8989       << LHSType << RHSType
8990       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8991     return QualType();
8992   }
8993 
8994   // OpenCL V1.1 6.2.6.p1:
8995   // If the operands are of more than one vector type, then an error shall
8996   // occur. Implicit conversions between vector types are not permitted, per
8997   // section 6.2.1.
8998   if (getLangOpts().OpenCL &&
8999       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9000       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9001     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9002                                                            << RHSType;
9003     return QualType();
9004   }
9005 
9006 
9007   // If there is a vector type that is not a ExtVector and a scalar, we reach
9008   // this point if scalar could not be converted to the vector's element type
9009   // without truncation.
9010   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9011       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9012     QualType Scalar = LHSVecType ? RHSType : LHSType;
9013     QualType Vector = LHSVecType ? LHSType : RHSType;
9014     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9015     Diag(Loc,
9016          diag::err_typecheck_vector_not_convertable_implict_truncation)
9017         << ScalarOrVector << Scalar << Vector;
9018 
9019     return QualType();
9020   }
9021 
9022   // Otherwise, use the generic diagnostic.
9023   Diag(Loc, DiagID)
9024     << LHSType << RHSType
9025     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9026   return QualType();
9027 }
9028 
9029 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9030 // expression.  These are mainly cases where the null pointer is used as an
9031 // integer instead of a pointer.
9032 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9033                                 SourceLocation Loc, bool IsCompare) {
9034   // The canonical way to check for a GNU null is with isNullPointerConstant,
9035   // but we use a bit of a hack here for speed; this is a relatively
9036   // hot path, and isNullPointerConstant is slow.
9037   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9038   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9039 
9040   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9041 
9042   // Avoid analyzing cases where the result will either be invalid (and
9043   // diagnosed as such) or entirely valid and not something to warn about.
9044   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9045       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9046     return;
9047 
9048   // Comparison operations would not make sense with a null pointer no matter
9049   // what the other expression is.
9050   if (!IsCompare) {
9051     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9052         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9053         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9054     return;
9055   }
9056 
9057   // The rest of the operations only make sense with a null pointer
9058   // if the other expression is a pointer.
9059   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9060       NonNullType->canDecayToPointerType())
9061     return;
9062 
9063   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9064       << LHSNull /* LHS is NULL */ << NonNullType
9065       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9066 }
9067 
9068 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
9069                                           SourceLocation Loc) {
9070   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9071   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9072   if (!LUE || !RUE)
9073     return;
9074   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9075       RUE->getKind() != UETT_SizeOf)
9076     return;
9077 
9078   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9079   QualType LHSTy = LHSArg->getType();
9080   QualType RHSTy;
9081 
9082   if (RUE->isArgumentType())
9083     RHSTy = RUE->getArgumentType();
9084   else
9085     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9086 
9087   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9088     return;
9089   if (LHSTy->getPointeeType().getCanonicalType() != RHSTy.getCanonicalType())
9090     return;
9091 
9092   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9093   if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9094     if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9095       S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9096           << LHSArgDecl;
9097   }
9098 }
9099 
9100 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9101                                                ExprResult &RHS,
9102                                                SourceLocation Loc, bool IsDiv) {
9103   // Check for division/remainder by zero.
9104   Expr::EvalResult RHSValue;
9105   if (!RHS.get()->isValueDependent() &&
9106       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9107       RHSValue.Val.getInt() == 0)
9108     S.DiagRuntimeBehavior(Loc, RHS.get(),
9109                           S.PDiag(diag::warn_remainder_division_by_zero)
9110                             << IsDiv << RHS.get()->getSourceRange());
9111 }
9112 
9113 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9114                                            SourceLocation Loc,
9115                                            bool IsCompAssign, bool IsDiv) {
9116   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9117 
9118   if (LHS.get()->getType()->isVectorType() ||
9119       RHS.get()->getType()->isVectorType())
9120     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9121                                /*AllowBothBool*/getLangOpts().AltiVec,
9122                                /*AllowBoolConversions*/false);
9123 
9124   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9125   if (LHS.isInvalid() || RHS.isInvalid())
9126     return QualType();
9127 
9128 
9129   if (compType.isNull() || !compType->isArithmeticType())
9130     return InvalidOperands(Loc, LHS, RHS);
9131   if (IsDiv) {
9132     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9133     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9134   }
9135   return compType;
9136 }
9137 
9138 QualType Sema::CheckRemainderOperands(
9139   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9140   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9141 
9142   if (LHS.get()->getType()->isVectorType() ||
9143       RHS.get()->getType()->isVectorType()) {
9144     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9145         RHS.get()->getType()->hasIntegerRepresentation())
9146       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9147                                  /*AllowBothBool*/getLangOpts().AltiVec,
9148                                  /*AllowBoolConversions*/false);
9149     return InvalidOperands(Loc, LHS, RHS);
9150   }
9151 
9152   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9153   if (LHS.isInvalid() || RHS.isInvalid())
9154     return QualType();
9155 
9156   if (compType.isNull() || !compType->isIntegerType())
9157     return InvalidOperands(Loc, LHS, RHS);
9158   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9159   return compType;
9160 }
9161 
9162 /// Diagnose invalid arithmetic on two void pointers.
9163 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9164                                                 Expr *LHSExpr, Expr *RHSExpr) {
9165   S.Diag(Loc, S.getLangOpts().CPlusPlus
9166                 ? diag::err_typecheck_pointer_arith_void_type
9167                 : diag::ext_gnu_void_ptr)
9168     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9169                             << RHSExpr->getSourceRange();
9170 }
9171 
9172 /// Diagnose invalid arithmetic on a void pointer.
9173 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9174                                             Expr *Pointer) {
9175   S.Diag(Loc, S.getLangOpts().CPlusPlus
9176                 ? diag::err_typecheck_pointer_arith_void_type
9177                 : diag::ext_gnu_void_ptr)
9178     << 0 /* one pointer */ << Pointer->getSourceRange();
9179 }
9180 
9181 /// Diagnose invalid arithmetic on a null pointer.
9182 ///
9183 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9184 /// idiom, which we recognize as a GNU extension.
9185 ///
9186 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9187                                             Expr *Pointer, bool IsGNUIdiom) {
9188   if (IsGNUIdiom)
9189     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9190       << Pointer->getSourceRange();
9191   else
9192     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9193       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9194 }
9195 
9196 /// Diagnose invalid arithmetic on two function pointers.
9197 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9198                                                     Expr *LHS, Expr *RHS) {
9199   assert(LHS->getType()->isAnyPointerType());
9200   assert(RHS->getType()->isAnyPointerType());
9201   S.Diag(Loc, S.getLangOpts().CPlusPlus
9202                 ? diag::err_typecheck_pointer_arith_function_type
9203                 : diag::ext_gnu_ptr_func_arith)
9204     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9205     // We only show the second type if it differs from the first.
9206     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9207                                                    RHS->getType())
9208     << RHS->getType()->getPointeeType()
9209     << LHS->getSourceRange() << RHS->getSourceRange();
9210 }
9211 
9212 /// Diagnose invalid arithmetic on a function pointer.
9213 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9214                                                 Expr *Pointer) {
9215   assert(Pointer->getType()->isAnyPointerType());
9216   S.Diag(Loc, S.getLangOpts().CPlusPlus
9217                 ? diag::err_typecheck_pointer_arith_function_type
9218                 : diag::ext_gnu_ptr_func_arith)
9219     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9220     << 0 /* one pointer, so only one type */
9221     << Pointer->getSourceRange();
9222 }
9223 
9224 /// Emit error if Operand is incomplete pointer type
9225 ///
9226 /// \returns True if pointer has incomplete type
9227 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9228                                                  Expr *Operand) {
9229   QualType ResType = Operand->getType();
9230   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9231     ResType = ResAtomicType->getValueType();
9232 
9233   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9234   QualType PointeeTy = ResType->getPointeeType();
9235   return S.RequireCompleteType(Loc, PointeeTy,
9236                                diag::err_typecheck_arithmetic_incomplete_type,
9237                                PointeeTy, Operand->getSourceRange());
9238 }
9239 
9240 /// Check the validity of an arithmetic pointer operand.
9241 ///
9242 /// If the operand has pointer type, this code will check for pointer types
9243 /// which are invalid in arithmetic operations. These will be diagnosed
9244 /// appropriately, including whether or not the use is supported as an
9245 /// extension.
9246 ///
9247 /// \returns True when the operand is valid to use (even if as an extension).
9248 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9249                                             Expr *Operand) {
9250   QualType ResType = Operand->getType();
9251   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9252     ResType = ResAtomicType->getValueType();
9253 
9254   if (!ResType->isAnyPointerType()) return true;
9255 
9256   QualType PointeeTy = ResType->getPointeeType();
9257   if (PointeeTy->isVoidType()) {
9258     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9259     return !S.getLangOpts().CPlusPlus;
9260   }
9261   if (PointeeTy->isFunctionType()) {
9262     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9263     return !S.getLangOpts().CPlusPlus;
9264   }
9265 
9266   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9267 
9268   return true;
9269 }
9270 
9271 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9272 /// operands.
9273 ///
9274 /// This routine will diagnose any invalid arithmetic on pointer operands much
9275 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9276 /// for emitting a single diagnostic even for operations where both LHS and RHS
9277 /// are (potentially problematic) pointers.
9278 ///
9279 /// \returns True when the operand is valid to use (even if as an extension).
9280 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9281                                                 Expr *LHSExpr, Expr *RHSExpr) {
9282   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9283   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9284   if (!isLHSPointer && !isRHSPointer) return true;
9285 
9286   QualType LHSPointeeTy, RHSPointeeTy;
9287   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9288   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9289 
9290   // if both are pointers check if operation is valid wrt address spaces
9291   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9292     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9293     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9294     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9295       S.Diag(Loc,
9296              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9297           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9298           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9299       return false;
9300     }
9301   }
9302 
9303   // Check for arithmetic on pointers to incomplete types.
9304   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9305   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9306   if (isLHSVoidPtr || isRHSVoidPtr) {
9307     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9308     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9309     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9310 
9311     return !S.getLangOpts().CPlusPlus;
9312   }
9313 
9314   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9315   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9316   if (isLHSFuncPtr || isRHSFuncPtr) {
9317     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9318     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9319                                                                 RHSExpr);
9320     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9321 
9322     return !S.getLangOpts().CPlusPlus;
9323   }
9324 
9325   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9326     return false;
9327   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9328     return false;
9329 
9330   return true;
9331 }
9332 
9333 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9334 /// literal.
9335 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9336                                   Expr *LHSExpr, Expr *RHSExpr) {
9337   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9338   Expr* IndexExpr = RHSExpr;
9339   if (!StrExpr) {
9340     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9341     IndexExpr = LHSExpr;
9342   }
9343 
9344   bool IsStringPlusInt = StrExpr &&
9345       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9346   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9347     return;
9348 
9349   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9350   Self.Diag(OpLoc, diag::warn_string_plus_int)
9351       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9352 
9353   // Only print a fixit for "str" + int, not for int + "str".
9354   if (IndexExpr == RHSExpr) {
9355     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9356     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9357         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9358         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9359         << FixItHint::CreateInsertion(EndLoc, "]");
9360   } else
9361     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9362 }
9363 
9364 /// Emit a warning when adding a char literal to a string.
9365 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9366                                    Expr *LHSExpr, Expr *RHSExpr) {
9367   const Expr *StringRefExpr = LHSExpr;
9368   const CharacterLiteral *CharExpr =
9369       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9370 
9371   if (!CharExpr) {
9372     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9373     StringRefExpr = RHSExpr;
9374   }
9375 
9376   if (!CharExpr || !StringRefExpr)
9377     return;
9378 
9379   const QualType StringType = StringRefExpr->getType();
9380 
9381   // Return if not a PointerType.
9382   if (!StringType->isAnyPointerType())
9383     return;
9384 
9385   // Return if not a CharacterType.
9386   if (!StringType->getPointeeType()->isAnyCharacterType())
9387     return;
9388 
9389   ASTContext &Ctx = Self.getASTContext();
9390   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9391 
9392   const QualType CharType = CharExpr->getType();
9393   if (!CharType->isAnyCharacterType() &&
9394       CharType->isIntegerType() &&
9395       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9396     Self.Diag(OpLoc, diag::warn_string_plus_char)
9397         << DiagRange << Ctx.CharTy;
9398   } else {
9399     Self.Diag(OpLoc, diag::warn_string_plus_char)
9400         << DiagRange << CharExpr->getType();
9401   }
9402 
9403   // Only print a fixit for str + char, not for char + str.
9404   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9405     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9406     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9407         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9408         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9409         << FixItHint::CreateInsertion(EndLoc, "]");
9410   } else {
9411     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9412   }
9413 }
9414 
9415 /// Emit error when two pointers are incompatible.
9416 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9417                                            Expr *LHSExpr, Expr *RHSExpr) {
9418   assert(LHSExpr->getType()->isAnyPointerType());
9419   assert(RHSExpr->getType()->isAnyPointerType());
9420   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9421     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9422     << RHSExpr->getSourceRange();
9423 }
9424 
9425 // C99 6.5.6
9426 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9427                                      SourceLocation Loc, BinaryOperatorKind Opc,
9428                                      QualType* CompLHSTy) {
9429   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9430 
9431   if (LHS.get()->getType()->isVectorType() ||
9432       RHS.get()->getType()->isVectorType()) {
9433     QualType compType = CheckVectorOperands(
9434         LHS, RHS, Loc, CompLHSTy,
9435         /*AllowBothBool*/getLangOpts().AltiVec,
9436         /*AllowBoolConversions*/getLangOpts().ZVector);
9437     if (CompLHSTy) *CompLHSTy = compType;
9438     return compType;
9439   }
9440 
9441   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9442   if (LHS.isInvalid() || RHS.isInvalid())
9443     return QualType();
9444 
9445   // Diagnose "string literal" '+' int and string '+' "char literal".
9446   if (Opc == BO_Add) {
9447     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9448     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9449   }
9450 
9451   // handle the common case first (both operands are arithmetic).
9452   if (!compType.isNull() && compType->isArithmeticType()) {
9453     if (CompLHSTy) *CompLHSTy = compType;
9454     return compType;
9455   }
9456 
9457   // Type-checking.  Ultimately the pointer's going to be in PExp;
9458   // note that we bias towards the LHS being the pointer.
9459   Expr *PExp = LHS.get(), *IExp = RHS.get();
9460 
9461   bool isObjCPointer;
9462   if (PExp->getType()->isPointerType()) {
9463     isObjCPointer = false;
9464   } else if (PExp->getType()->isObjCObjectPointerType()) {
9465     isObjCPointer = true;
9466   } else {
9467     std::swap(PExp, IExp);
9468     if (PExp->getType()->isPointerType()) {
9469       isObjCPointer = false;
9470     } else if (PExp->getType()->isObjCObjectPointerType()) {
9471       isObjCPointer = true;
9472     } else {
9473       return InvalidOperands(Loc, LHS, RHS);
9474     }
9475   }
9476   assert(PExp->getType()->isAnyPointerType());
9477 
9478   if (!IExp->getType()->isIntegerType())
9479     return InvalidOperands(Loc, LHS, RHS);
9480 
9481   // Adding to a null pointer results in undefined behavior.
9482   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9483           Context, Expr::NPC_ValueDependentIsNotNull)) {
9484     // In C++ adding zero to a null pointer is defined.
9485     Expr::EvalResult KnownVal;
9486     if (!getLangOpts().CPlusPlus ||
9487         (!IExp->isValueDependent() &&
9488          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9489           KnownVal.Val.getInt() != 0))) {
9490       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9491       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9492           Context, BO_Add, PExp, IExp);
9493       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9494     }
9495   }
9496 
9497   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9498     return QualType();
9499 
9500   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9501     return QualType();
9502 
9503   // Check array bounds for pointer arithemtic
9504   CheckArrayAccess(PExp, IExp);
9505 
9506   if (CompLHSTy) {
9507     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9508     if (LHSTy.isNull()) {
9509       LHSTy = LHS.get()->getType();
9510       if (LHSTy->isPromotableIntegerType())
9511         LHSTy = Context.getPromotedIntegerType(LHSTy);
9512     }
9513     *CompLHSTy = LHSTy;
9514   }
9515 
9516   return PExp->getType();
9517 }
9518 
9519 // C99 6.5.6
9520 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9521                                         SourceLocation Loc,
9522                                         QualType* CompLHSTy) {
9523   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9524 
9525   if (LHS.get()->getType()->isVectorType() ||
9526       RHS.get()->getType()->isVectorType()) {
9527     QualType compType = CheckVectorOperands(
9528         LHS, RHS, Loc, CompLHSTy,
9529         /*AllowBothBool*/getLangOpts().AltiVec,
9530         /*AllowBoolConversions*/getLangOpts().ZVector);
9531     if (CompLHSTy) *CompLHSTy = compType;
9532     return compType;
9533   }
9534 
9535   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9536   if (LHS.isInvalid() || RHS.isInvalid())
9537     return QualType();
9538 
9539   // Enforce type constraints: C99 6.5.6p3.
9540 
9541   // Handle the common case first (both operands are arithmetic).
9542   if (!compType.isNull() && compType->isArithmeticType()) {
9543     if (CompLHSTy) *CompLHSTy = compType;
9544     return compType;
9545   }
9546 
9547   // Either ptr - int   or   ptr - ptr.
9548   if (LHS.get()->getType()->isAnyPointerType()) {
9549     QualType lpointee = LHS.get()->getType()->getPointeeType();
9550 
9551     // Diagnose bad cases where we step over interface counts.
9552     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9553         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9554       return QualType();
9555 
9556     // The result type of a pointer-int computation is the pointer type.
9557     if (RHS.get()->getType()->isIntegerType()) {
9558       // Subtracting from a null pointer should produce a warning.
9559       // The last argument to the diagnose call says this doesn't match the
9560       // GNU int-to-pointer idiom.
9561       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9562                                            Expr::NPC_ValueDependentIsNotNull)) {
9563         // In C++ adding zero to a null pointer is defined.
9564         Expr::EvalResult KnownVal;
9565         if (!getLangOpts().CPlusPlus ||
9566             (!RHS.get()->isValueDependent() &&
9567              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9568               KnownVal.Val.getInt() != 0))) {
9569           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9570         }
9571       }
9572 
9573       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9574         return QualType();
9575 
9576       // Check array bounds for pointer arithemtic
9577       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9578                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9579 
9580       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9581       return LHS.get()->getType();
9582     }
9583 
9584     // Handle pointer-pointer subtractions.
9585     if (const PointerType *RHSPTy
9586           = RHS.get()->getType()->getAs<PointerType>()) {
9587       QualType rpointee = RHSPTy->getPointeeType();
9588 
9589       if (getLangOpts().CPlusPlus) {
9590         // Pointee types must be the same: C++ [expr.add]
9591         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9592           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9593         }
9594       } else {
9595         // Pointee types must be compatible C99 6.5.6p3
9596         if (!Context.typesAreCompatible(
9597                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9598                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9599           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9600           return QualType();
9601         }
9602       }
9603 
9604       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9605                                                LHS.get(), RHS.get()))
9606         return QualType();
9607 
9608       // FIXME: Add warnings for nullptr - ptr.
9609 
9610       // The pointee type may have zero size.  As an extension, a structure or
9611       // union may have zero size or an array may have zero length.  In this
9612       // case subtraction does not make sense.
9613       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9614         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9615         if (ElementSize.isZero()) {
9616           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9617             << rpointee.getUnqualifiedType()
9618             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9619         }
9620       }
9621 
9622       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9623       return Context.getPointerDiffType();
9624     }
9625   }
9626 
9627   return InvalidOperands(Loc, LHS, RHS);
9628 }
9629 
9630 static bool isScopedEnumerationType(QualType T) {
9631   if (const EnumType *ET = T->getAs<EnumType>())
9632     return ET->getDecl()->isScoped();
9633   return false;
9634 }
9635 
9636 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9637                                    SourceLocation Loc, BinaryOperatorKind Opc,
9638                                    QualType LHSType) {
9639   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9640   // so skip remaining warnings as we don't want to modify values within Sema.
9641   if (S.getLangOpts().OpenCL)
9642     return;
9643 
9644   // Check right/shifter operand
9645   Expr::EvalResult RHSResult;
9646   if (RHS.get()->isValueDependent() ||
9647       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9648     return;
9649   llvm::APSInt Right = RHSResult.Val.getInt();
9650 
9651   if (Right.isNegative()) {
9652     S.DiagRuntimeBehavior(Loc, RHS.get(),
9653                           S.PDiag(diag::warn_shift_negative)
9654                             << RHS.get()->getSourceRange());
9655     return;
9656   }
9657   llvm::APInt LeftBits(Right.getBitWidth(),
9658                        S.Context.getTypeSize(LHS.get()->getType()));
9659   if (Right.uge(LeftBits)) {
9660     S.DiagRuntimeBehavior(Loc, RHS.get(),
9661                           S.PDiag(diag::warn_shift_gt_typewidth)
9662                             << RHS.get()->getSourceRange());
9663     return;
9664   }
9665   if (Opc != BO_Shl)
9666     return;
9667 
9668   // When left shifting an ICE which is signed, we can check for overflow which
9669   // according to C++ standards prior to C++2a has undefined behavior
9670   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9671   // more than the maximum value representable in the result type, so never
9672   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9673   // expression is still probably a bug.)
9674   Expr::EvalResult LHSResult;
9675   if (LHS.get()->isValueDependent() ||
9676       LHSType->hasUnsignedIntegerRepresentation() ||
9677       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9678     return;
9679   llvm::APSInt Left = LHSResult.Val.getInt();
9680 
9681   // If LHS does not have a signed type and non-negative value
9682   // then, the behavior is undefined before C++2a. Warn about it.
9683   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9684       !S.getLangOpts().CPlusPlus2a) {
9685     S.DiagRuntimeBehavior(Loc, LHS.get(),
9686                           S.PDiag(diag::warn_shift_lhs_negative)
9687                             << LHS.get()->getSourceRange());
9688     return;
9689   }
9690 
9691   llvm::APInt ResultBits =
9692       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9693   if (LeftBits.uge(ResultBits))
9694     return;
9695   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9696   Result = Result.shl(Right);
9697 
9698   // Print the bit representation of the signed integer as an unsigned
9699   // hexadecimal number.
9700   SmallString<40> HexResult;
9701   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9702 
9703   // If we are only missing a sign bit, this is less likely to result in actual
9704   // bugs -- if the result is cast back to an unsigned type, it will have the
9705   // expected value. Thus we place this behind a different warning that can be
9706   // turned off separately if needed.
9707   if (LeftBits == ResultBits - 1) {
9708     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9709         << HexResult << LHSType
9710         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9711     return;
9712   }
9713 
9714   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9715     << HexResult.str() << Result.getMinSignedBits() << LHSType
9716     << Left.getBitWidth() << LHS.get()->getSourceRange()
9717     << RHS.get()->getSourceRange();
9718 }
9719 
9720 /// Return the resulting type when a vector is shifted
9721 ///        by a scalar or vector shift amount.
9722 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9723                                  SourceLocation Loc, bool IsCompAssign) {
9724   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9725   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9726       !LHS.get()->getType()->isVectorType()) {
9727     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9728       << RHS.get()->getType() << LHS.get()->getType()
9729       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9730     return QualType();
9731   }
9732 
9733   if (!IsCompAssign) {
9734     LHS = S.UsualUnaryConversions(LHS.get());
9735     if (LHS.isInvalid()) return QualType();
9736   }
9737 
9738   RHS = S.UsualUnaryConversions(RHS.get());
9739   if (RHS.isInvalid()) return QualType();
9740 
9741   QualType LHSType = LHS.get()->getType();
9742   // Note that LHS might be a scalar because the routine calls not only in
9743   // OpenCL case.
9744   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9745   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9746 
9747   // Note that RHS might not be a vector.
9748   QualType RHSType = RHS.get()->getType();
9749   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9750   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9751 
9752   // The operands need to be integers.
9753   if (!LHSEleType->isIntegerType()) {
9754     S.Diag(Loc, diag::err_typecheck_expect_int)
9755       << LHS.get()->getType() << LHS.get()->getSourceRange();
9756     return QualType();
9757   }
9758 
9759   if (!RHSEleType->isIntegerType()) {
9760     S.Diag(Loc, diag::err_typecheck_expect_int)
9761       << RHS.get()->getType() << RHS.get()->getSourceRange();
9762     return QualType();
9763   }
9764 
9765   if (!LHSVecTy) {
9766     assert(RHSVecTy);
9767     if (IsCompAssign)
9768       return RHSType;
9769     if (LHSEleType != RHSEleType) {
9770       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9771       LHSEleType = RHSEleType;
9772     }
9773     QualType VecTy =
9774         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9775     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9776     LHSType = VecTy;
9777   } else if (RHSVecTy) {
9778     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9779     // are applied component-wise. So if RHS is a vector, then ensure
9780     // that the number of elements is the same as LHS...
9781     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9782       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9783         << LHS.get()->getType() << RHS.get()->getType()
9784         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9785       return QualType();
9786     }
9787     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9788       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9789       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9790       if (LHSBT != RHSBT &&
9791           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9792         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9793             << LHS.get()->getType() << RHS.get()->getType()
9794             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9795       }
9796     }
9797   } else {
9798     // ...else expand RHS to match the number of elements in LHS.
9799     QualType VecTy =
9800       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9801     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9802   }
9803 
9804   return LHSType;
9805 }
9806 
9807 // C99 6.5.7
9808 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9809                                   SourceLocation Loc, BinaryOperatorKind Opc,
9810                                   bool IsCompAssign) {
9811   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9812 
9813   // Vector shifts promote their scalar inputs to vector type.
9814   if (LHS.get()->getType()->isVectorType() ||
9815       RHS.get()->getType()->isVectorType()) {
9816     if (LangOpts.ZVector) {
9817       // The shift operators for the z vector extensions work basically
9818       // like general shifts, except that neither the LHS nor the RHS is
9819       // allowed to be a "vector bool".
9820       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9821         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9822           return InvalidOperands(Loc, LHS, RHS);
9823       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9824         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9825           return InvalidOperands(Loc, LHS, RHS);
9826     }
9827     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9828   }
9829 
9830   // Shifts don't perform usual arithmetic conversions, they just do integer
9831   // promotions on each operand. C99 6.5.7p3
9832 
9833   // For the LHS, do usual unary conversions, but then reset them away
9834   // if this is a compound assignment.
9835   ExprResult OldLHS = LHS;
9836   LHS = UsualUnaryConversions(LHS.get());
9837   if (LHS.isInvalid())
9838     return QualType();
9839   QualType LHSType = LHS.get()->getType();
9840   if (IsCompAssign) LHS = OldLHS;
9841 
9842   // The RHS is simpler.
9843   RHS = UsualUnaryConversions(RHS.get());
9844   if (RHS.isInvalid())
9845     return QualType();
9846   QualType RHSType = RHS.get()->getType();
9847 
9848   // C99 6.5.7p2: Each of the operands shall have integer type.
9849   if (!LHSType->hasIntegerRepresentation() ||
9850       !RHSType->hasIntegerRepresentation())
9851     return InvalidOperands(Loc, LHS, RHS);
9852 
9853   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9854   // hasIntegerRepresentation() above instead of this.
9855   if (isScopedEnumerationType(LHSType) ||
9856       isScopedEnumerationType(RHSType)) {
9857     return InvalidOperands(Loc, LHS, RHS);
9858   }
9859   // Sanity-check shift operands
9860   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9861 
9862   // "The type of the result is that of the promoted left operand."
9863   return LHSType;
9864 }
9865 
9866 /// If two different enums are compared, raise a warning.
9867 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9868                                 Expr *RHS) {
9869   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9870   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9871 
9872   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9873   if (!LHSEnumType)
9874     return;
9875   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9876   if (!RHSEnumType)
9877     return;
9878 
9879   // Ignore anonymous enums.
9880   if (!LHSEnumType->getDecl()->getIdentifier() &&
9881       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9882     return;
9883   if (!RHSEnumType->getDecl()->getIdentifier() &&
9884       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9885     return;
9886 
9887   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9888     return;
9889 
9890   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9891       << LHSStrippedType << RHSStrippedType
9892       << LHS->getSourceRange() << RHS->getSourceRange();
9893 }
9894 
9895 /// Diagnose bad pointer comparisons.
9896 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9897                                               ExprResult &LHS, ExprResult &RHS,
9898                                               bool IsError) {
9899   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9900                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9901     << LHS.get()->getType() << RHS.get()->getType()
9902     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9903 }
9904 
9905 /// Returns false if the pointers are converted to a composite type,
9906 /// true otherwise.
9907 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9908                                            ExprResult &LHS, ExprResult &RHS) {
9909   // C++ [expr.rel]p2:
9910   //   [...] Pointer conversions (4.10) and qualification
9911   //   conversions (4.4) are performed on pointer operands (or on
9912   //   a pointer operand and a null pointer constant) to bring
9913   //   them to their composite pointer type. [...]
9914   //
9915   // C++ [expr.eq]p1 uses the same notion for (in)equality
9916   // comparisons of pointers.
9917 
9918   QualType LHSType = LHS.get()->getType();
9919   QualType RHSType = RHS.get()->getType();
9920   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9921          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9922 
9923   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9924   if (T.isNull()) {
9925     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9926         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9927       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9928     else
9929       S.InvalidOperands(Loc, LHS, RHS);
9930     return true;
9931   }
9932 
9933   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9934   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9935   return false;
9936 }
9937 
9938 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9939                                                     ExprResult &LHS,
9940                                                     ExprResult &RHS,
9941                                                     bool IsError) {
9942   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9943                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9944     << LHS.get()->getType() << RHS.get()->getType()
9945     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9946 }
9947 
9948 static bool isObjCObjectLiteral(ExprResult &E) {
9949   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9950   case Stmt::ObjCArrayLiteralClass:
9951   case Stmt::ObjCDictionaryLiteralClass:
9952   case Stmt::ObjCStringLiteralClass:
9953   case Stmt::ObjCBoxedExprClass:
9954     return true;
9955   default:
9956     // Note that ObjCBoolLiteral is NOT an object literal!
9957     return false;
9958   }
9959 }
9960 
9961 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9962   const ObjCObjectPointerType *Type =
9963     LHS->getType()->getAs<ObjCObjectPointerType>();
9964 
9965   // If this is not actually an Objective-C object, bail out.
9966   if (!Type)
9967     return false;
9968 
9969   // Get the LHS object's interface type.
9970   QualType InterfaceType = Type->getPointeeType();
9971 
9972   // If the RHS isn't an Objective-C object, bail out.
9973   if (!RHS->getType()->isObjCObjectPointerType())
9974     return false;
9975 
9976   // Try to find the -isEqual: method.
9977   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9978   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9979                                                       InterfaceType,
9980                                                       /*IsInstance=*/true);
9981   if (!Method) {
9982     if (Type->isObjCIdType()) {
9983       // For 'id', just check the global pool.
9984       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9985                                                   /*receiverId=*/true);
9986     } else {
9987       // Check protocols.
9988       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9989                                              /*IsInstance=*/true);
9990     }
9991   }
9992 
9993   if (!Method)
9994     return false;
9995 
9996   QualType T = Method->parameters()[0]->getType();
9997   if (!T->isObjCObjectPointerType())
9998     return false;
9999 
10000   QualType R = Method->getReturnType();
10001   if (!R->isScalarType())
10002     return false;
10003 
10004   return true;
10005 }
10006 
10007 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10008   FromE = FromE->IgnoreParenImpCasts();
10009   switch (FromE->getStmtClass()) {
10010     default:
10011       break;
10012     case Stmt::ObjCStringLiteralClass:
10013       // "string literal"
10014       return LK_String;
10015     case Stmt::ObjCArrayLiteralClass:
10016       // "array literal"
10017       return LK_Array;
10018     case Stmt::ObjCDictionaryLiteralClass:
10019       // "dictionary literal"
10020       return LK_Dictionary;
10021     case Stmt::BlockExprClass:
10022       return LK_Block;
10023     case Stmt::ObjCBoxedExprClass: {
10024       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10025       switch (Inner->getStmtClass()) {
10026         case Stmt::IntegerLiteralClass:
10027         case Stmt::FloatingLiteralClass:
10028         case Stmt::CharacterLiteralClass:
10029         case Stmt::ObjCBoolLiteralExprClass:
10030         case Stmt::CXXBoolLiteralExprClass:
10031           // "numeric literal"
10032           return LK_Numeric;
10033         case Stmt::ImplicitCastExprClass: {
10034           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10035           // Boolean literals can be represented by implicit casts.
10036           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10037             return LK_Numeric;
10038           break;
10039         }
10040         default:
10041           break;
10042       }
10043       return LK_Boxed;
10044     }
10045   }
10046   return LK_None;
10047 }
10048 
10049 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10050                                           ExprResult &LHS, ExprResult &RHS,
10051                                           BinaryOperator::Opcode Opc){
10052   Expr *Literal;
10053   Expr *Other;
10054   if (isObjCObjectLiteral(LHS)) {
10055     Literal = LHS.get();
10056     Other = RHS.get();
10057   } else {
10058     Literal = RHS.get();
10059     Other = LHS.get();
10060   }
10061 
10062   // Don't warn on comparisons against nil.
10063   Other = Other->IgnoreParenCasts();
10064   if (Other->isNullPointerConstant(S.getASTContext(),
10065                                    Expr::NPC_ValueDependentIsNotNull))
10066     return;
10067 
10068   // This should be kept in sync with warn_objc_literal_comparison.
10069   // LK_String should always be after the other literals, since it has its own
10070   // warning flag.
10071   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10072   assert(LiteralKind != Sema::LK_Block);
10073   if (LiteralKind == Sema::LK_None) {
10074     llvm_unreachable("Unknown Objective-C object literal kind");
10075   }
10076 
10077   if (LiteralKind == Sema::LK_String)
10078     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10079       << Literal->getSourceRange();
10080   else
10081     S.Diag(Loc, diag::warn_objc_literal_comparison)
10082       << LiteralKind << Literal->getSourceRange();
10083 
10084   if (BinaryOperator::isEqualityOp(Opc) &&
10085       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10086     SourceLocation Start = LHS.get()->getBeginLoc();
10087     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10088     CharSourceRange OpRange =
10089       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10090 
10091     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10092       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10093       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10094       << FixItHint::CreateInsertion(End, "]");
10095   }
10096 }
10097 
10098 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10099 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10100                                            ExprResult &RHS, SourceLocation Loc,
10101                                            BinaryOperatorKind Opc) {
10102   // Check that left hand side is !something.
10103   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10104   if (!UO || UO->getOpcode() != UO_LNot) return;
10105 
10106   // Only check if the right hand side is non-bool arithmetic type.
10107   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10108 
10109   // Make sure that the something in !something is not bool.
10110   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10111   if (SubExpr->isKnownToHaveBooleanValue()) return;
10112 
10113   // Emit warning.
10114   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10115   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10116       << Loc << IsBitwiseOp;
10117 
10118   // First note suggest !(x < y)
10119   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10120   SourceLocation FirstClose = RHS.get()->getEndLoc();
10121   FirstClose = S.getLocForEndOfToken(FirstClose);
10122   if (FirstClose.isInvalid())
10123     FirstOpen = SourceLocation();
10124   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10125       << IsBitwiseOp
10126       << FixItHint::CreateInsertion(FirstOpen, "(")
10127       << FixItHint::CreateInsertion(FirstClose, ")");
10128 
10129   // Second note suggests (!x) < y
10130   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10131   SourceLocation SecondClose = LHS.get()->getEndLoc();
10132   SecondClose = S.getLocForEndOfToken(SecondClose);
10133   if (SecondClose.isInvalid())
10134     SecondOpen = SourceLocation();
10135   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10136       << FixItHint::CreateInsertion(SecondOpen, "(")
10137       << FixItHint::CreateInsertion(SecondClose, ")");
10138 }
10139 
10140 // Get the decl for a simple expression: a reference to a variable,
10141 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10142 static ValueDecl *getCompareDecl(Expr *E) {
10143   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10144     return DR->getDecl();
10145   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10146     if (Ivar->isFreeIvar())
10147       return Ivar->getDecl();
10148   }
10149   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10150     if (Mem->isImplicitAccess())
10151       return Mem->getMemberDecl();
10152   }
10153   return nullptr;
10154 }
10155 
10156 /// Diagnose some forms of syntactically-obvious tautological comparison.
10157 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10158                                            Expr *LHS, Expr *RHS,
10159                                            BinaryOperatorKind Opc) {
10160   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10161   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10162 
10163   QualType LHSType = LHS->getType();
10164   QualType RHSType = RHS->getType();
10165   if (LHSType->hasFloatingRepresentation() ||
10166       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10167       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10168       S.inTemplateInstantiation())
10169     return;
10170 
10171   // Comparisons between two array types are ill-formed for operator<=>, so
10172   // we shouldn't emit any additional warnings about it.
10173   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10174     return;
10175 
10176   // For non-floating point types, check for self-comparisons of the form
10177   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10178   // often indicate logic errors in the program.
10179   //
10180   // NOTE: Don't warn about comparison expressions resulting from macro
10181   // expansion. Also don't warn about comparisons which are only self
10182   // comparisons within a template instantiation. The warnings should catch
10183   // obvious cases in the definition of the template anyways. The idea is to
10184   // warn when the typed comparison operator will always evaluate to the same
10185   // result.
10186   ValueDecl *DL = getCompareDecl(LHSStripped);
10187   ValueDecl *DR = getCompareDecl(RHSStripped);
10188 
10189   // Used for indexing into %select in warn_comparison_always
10190   enum {
10191     AlwaysConstant,
10192     AlwaysTrue,
10193     AlwaysFalse,
10194     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10195   };
10196   if (DL && DR && declaresSameEntity(DL, DR)) {
10197     unsigned Result;
10198     switch (Opc) {
10199     case BO_EQ: case BO_LE: case BO_GE:
10200       Result = AlwaysTrue;
10201       break;
10202     case BO_NE: case BO_LT: case BO_GT:
10203       Result = AlwaysFalse;
10204       break;
10205     case BO_Cmp:
10206       Result = AlwaysEqual;
10207       break;
10208     default:
10209       Result = AlwaysConstant;
10210       break;
10211     }
10212     S.DiagRuntimeBehavior(Loc, nullptr,
10213                           S.PDiag(diag::warn_comparison_always)
10214                               << 0 /*self-comparison*/
10215                               << Result);
10216   } else if (DL && DR &&
10217              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10218              !DL->isWeak() && !DR->isWeak()) {
10219     // What is it always going to evaluate to?
10220     unsigned Result;
10221     switch(Opc) {
10222     case BO_EQ: // e.g. array1 == array2
10223       Result = AlwaysFalse;
10224       break;
10225     case BO_NE: // e.g. array1 != array2
10226       Result = AlwaysTrue;
10227       break;
10228     default: // e.g. array1 <= array2
10229       // The best we can say is 'a constant'
10230       Result = AlwaysConstant;
10231       break;
10232     }
10233     S.DiagRuntimeBehavior(Loc, nullptr,
10234                           S.PDiag(diag::warn_comparison_always)
10235                               << 1 /*array comparison*/
10236                               << Result);
10237   }
10238 
10239   if (isa<CastExpr>(LHSStripped))
10240     LHSStripped = LHSStripped->IgnoreParenCasts();
10241   if (isa<CastExpr>(RHSStripped))
10242     RHSStripped = RHSStripped->IgnoreParenCasts();
10243 
10244   // Warn about comparisons against a string constant (unless the other
10245   // operand is null); the user probably wants strcmp.
10246   Expr *LiteralString = nullptr;
10247   Expr *LiteralStringStripped = nullptr;
10248   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10249       !RHSStripped->isNullPointerConstant(S.Context,
10250                                           Expr::NPC_ValueDependentIsNull)) {
10251     LiteralString = LHS;
10252     LiteralStringStripped = LHSStripped;
10253   } else if ((isa<StringLiteral>(RHSStripped) ||
10254               isa<ObjCEncodeExpr>(RHSStripped)) &&
10255              !LHSStripped->isNullPointerConstant(S.Context,
10256                                           Expr::NPC_ValueDependentIsNull)) {
10257     LiteralString = RHS;
10258     LiteralStringStripped = RHSStripped;
10259   }
10260 
10261   if (LiteralString) {
10262     S.DiagRuntimeBehavior(Loc, nullptr,
10263                           S.PDiag(diag::warn_stringcompare)
10264                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10265                               << LiteralString->getSourceRange());
10266   }
10267 }
10268 
10269 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10270   switch (CK) {
10271   default: {
10272 #ifndef NDEBUG
10273     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10274                  << "\n";
10275 #endif
10276     llvm_unreachable("unhandled cast kind");
10277   }
10278   case CK_UserDefinedConversion:
10279     return ICK_Identity;
10280   case CK_LValueToRValue:
10281     return ICK_Lvalue_To_Rvalue;
10282   case CK_ArrayToPointerDecay:
10283     return ICK_Array_To_Pointer;
10284   case CK_FunctionToPointerDecay:
10285     return ICK_Function_To_Pointer;
10286   case CK_IntegralCast:
10287     return ICK_Integral_Conversion;
10288   case CK_FloatingCast:
10289     return ICK_Floating_Conversion;
10290   case CK_IntegralToFloating:
10291   case CK_FloatingToIntegral:
10292     return ICK_Floating_Integral;
10293   case CK_IntegralComplexCast:
10294   case CK_FloatingComplexCast:
10295   case CK_FloatingComplexToIntegralComplex:
10296   case CK_IntegralComplexToFloatingComplex:
10297     return ICK_Complex_Conversion;
10298   case CK_FloatingComplexToReal:
10299   case CK_FloatingRealToComplex:
10300   case CK_IntegralComplexToReal:
10301   case CK_IntegralRealToComplex:
10302     return ICK_Complex_Real;
10303   }
10304 }
10305 
10306 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10307                                              QualType FromType,
10308                                              SourceLocation Loc) {
10309   // Check for a narrowing implicit conversion.
10310   StandardConversionSequence SCS;
10311   SCS.setAsIdentityConversion();
10312   SCS.setToType(0, FromType);
10313   SCS.setToType(1, ToType);
10314   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10315     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10316 
10317   APValue PreNarrowingValue;
10318   QualType PreNarrowingType;
10319   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10320                                PreNarrowingType,
10321                                /*IgnoreFloatToIntegralConversion*/ true)) {
10322   case NK_Dependent_Narrowing:
10323     // Implicit conversion to a narrower type, but the expression is
10324     // value-dependent so we can't tell whether it's actually narrowing.
10325   case NK_Not_Narrowing:
10326     return false;
10327 
10328   case NK_Constant_Narrowing:
10329     // Implicit conversion to a narrower type, and the value is not a constant
10330     // expression.
10331     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10332         << /*Constant*/ 1
10333         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10334     return true;
10335 
10336   case NK_Variable_Narrowing:
10337     // Implicit conversion to a narrower type, and the value is not a constant
10338     // expression.
10339   case NK_Type_Narrowing:
10340     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10341         << /*Constant*/ 0 << FromType << ToType;
10342     // TODO: It's not a constant expression, but what if the user intended it
10343     // to be? Can we produce notes to help them figure out why it isn't?
10344     return true;
10345   }
10346   llvm_unreachable("unhandled case in switch");
10347 }
10348 
10349 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10350                                                          ExprResult &LHS,
10351                                                          ExprResult &RHS,
10352                                                          SourceLocation Loc) {
10353   using CCT = ComparisonCategoryType;
10354 
10355   QualType LHSType = LHS.get()->getType();
10356   QualType RHSType = RHS.get()->getType();
10357   // Dig out the original argument type and expression before implicit casts
10358   // were applied. These are the types/expressions we need to check the
10359   // [expr.spaceship] requirements against.
10360   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10361   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10362   QualType LHSStrippedType = LHSStripped.get()->getType();
10363   QualType RHSStrippedType = RHSStripped.get()->getType();
10364 
10365   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10366   // other is not, the program is ill-formed.
10367   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10368     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10369     return QualType();
10370   }
10371 
10372   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10373                     RHSStrippedType->isEnumeralType();
10374   if (NumEnumArgs == 1) {
10375     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10376     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10377     if (OtherTy->hasFloatingRepresentation()) {
10378       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10379       return QualType();
10380     }
10381   }
10382   if (NumEnumArgs == 2) {
10383     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10384     // type E, the operator yields the result of converting the operands
10385     // to the underlying type of E and applying <=> to the converted operands.
10386     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10387       S.InvalidOperands(Loc, LHS, RHS);
10388       return QualType();
10389     }
10390     QualType IntType =
10391         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10392     assert(IntType->isArithmeticType());
10393 
10394     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10395     // promote the boolean type, and all other promotable integer types, to
10396     // avoid this.
10397     if (IntType->isPromotableIntegerType())
10398       IntType = S.Context.getPromotedIntegerType(IntType);
10399 
10400     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10401     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10402     LHSType = RHSType = IntType;
10403   }
10404 
10405   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10406   // usual arithmetic conversions are applied to the operands.
10407   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10408   if (LHS.isInvalid() || RHS.isInvalid())
10409     return QualType();
10410   if (Type.isNull())
10411     return S.InvalidOperands(Loc, LHS, RHS);
10412   assert(Type->isArithmeticType() || Type->isEnumeralType());
10413 
10414   bool HasNarrowing = checkThreeWayNarrowingConversion(
10415       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10416   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10417                                                    RHS.get()->getBeginLoc());
10418   if (HasNarrowing)
10419     return QualType();
10420 
10421   assert(!Type.isNull() && "composite type for <=> has not been set");
10422 
10423   auto TypeKind = [&]() {
10424     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10425       if (CT->getElementType()->hasFloatingRepresentation())
10426         return CCT::WeakEquality;
10427       return CCT::StrongEquality;
10428     }
10429     if (Type->isIntegralOrEnumerationType())
10430       return CCT::StrongOrdering;
10431     if (Type->hasFloatingRepresentation())
10432       return CCT::PartialOrdering;
10433     llvm_unreachable("other types are unimplemented");
10434   }();
10435 
10436   return S.CheckComparisonCategoryType(TypeKind, Loc);
10437 }
10438 
10439 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10440                                                  ExprResult &RHS,
10441                                                  SourceLocation Loc,
10442                                                  BinaryOperatorKind Opc) {
10443   if (Opc == BO_Cmp)
10444     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10445 
10446   // C99 6.5.8p3 / C99 6.5.9p4
10447   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10448   if (LHS.isInvalid() || RHS.isInvalid())
10449     return QualType();
10450   if (Type.isNull())
10451     return S.InvalidOperands(Loc, LHS, RHS);
10452   assert(Type->isArithmeticType() || Type->isEnumeralType());
10453 
10454   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10455 
10456   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10457     return S.InvalidOperands(Loc, LHS, RHS);
10458 
10459   // Check for comparisons of floating point operands using != and ==.
10460   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10461     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10462 
10463   // The result of comparisons is 'bool' in C++, 'int' in C.
10464   return S.Context.getLogicalOperationType();
10465 }
10466 
10467 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10468   if (!NullE.get()->getType()->isAnyPointerType())
10469     return;
10470   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10471   if (!E.get()->getType()->isAnyPointerType() &&
10472       E.get()->isNullPointerConstant(Context,
10473                                      Expr::NPC_ValueDependentIsNotNull) ==
10474         Expr::NPCK_ZeroExpression) {
10475     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10476       if (CL->getValue() == 0)
10477         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10478             << NullValue
10479             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10480                                             NullValue ? "NULL" : "(void *)0");
10481     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10482         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10483         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10484         if (T == Context.CharTy)
10485           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10486               << NullValue
10487               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10488                                               NullValue ? "NULL" : "(void *)0");
10489       }
10490   }
10491 }
10492 
10493 // C99 6.5.8, C++ [expr.rel]
10494 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10495                                     SourceLocation Loc,
10496                                     BinaryOperatorKind Opc) {
10497   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10498   bool IsThreeWay = Opc == BO_Cmp;
10499   auto IsAnyPointerType = [](ExprResult E) {
10500     QualType Ty = E.get()->getType();
10501     return Ty->isPointerType() || Ty->isMemberPointerType();
10502   };
10503 
10504   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10505   // type, array-to-pointer, ..., conversions are performed on both operands to
10506   // bring them to their composite type.
10507   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10508   // any type-related checks.
10509   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10510     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10511     if (LHS.isInvalid())
10512       return QualType();
10513     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10514     if (RHS.isInvalid())
10515       return QualType();
10516   } else {
10517     LHS = DefaultLvalueConversion(LHS.get());
10518     if (LHS.isInvalid())
10519       return QualType();
10520     RHS = DefaultLvalueConversion(RHS.get());
10521     if (RHS.isInvalid())
10522       return QualType();
10523   }
10524 
10525   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10526   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10527     CheckPtrComparisonWithNullChar(LHS, RHS);
10528     CheckPtrComparisonWithNullChar(RHS, LHS);
10529   }
10530 
10531   // Handle vector comparisons separately.
10532   if (LHS.get()->getType()->isVectorType() ||
10533       RHS.get()->getType()->isVectorType())
10534     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10535 
10536   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10537   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10538 
10539   QualType LHSType = LHS.get()->getType();
10540   QualType RHSType = RHS.get()->getType();
10541   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10542       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10543     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10544 
10545   const Expr::NullPointerConstantKind LHSNullKind =
10546       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10547   const Expr::NullPointerConstantKind RHSNullKind =
10548       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10549   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10550   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10551 
10552   auto computeResultTy = [&]() {
10553     if (Opc != BO_Cmp)
10554       return Context.getLogicalOperationType();
10555     assert(getLangOpts().CPlusPlus);
10556     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10557 
10558     QualType CompositeTy = LHS.get()->getType();
10559     assert(!CompositeTy->isReferenceType());
10560 
10561     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10562       return CheckComparisonCategoryType(Kind, Loc);
10563     };
10564 
10565     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10566     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10567     // result is of type std::strong_equality
10568     if (CompositeTy->isFunctionPointerType() ||
10569         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10570       // FIXME: consider making the function pointer case produce
10571       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10572       // and direction polls
10573       return buildResultTy(ComparisonCategoryType::StrongEquality);
10574 
10575     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10576     // pointer type, p <=> q is of type std::strong_ordering.
10577     if (CompositeTy->isPointerType()) {
10578       // P0946R0: Comparisons between a null pointer constant and an object
10579       // pointer result in std::strong_equality
10580       if (LHSIsNull != RHSIsNull)
10581         return buildResultTy(ComparisonCategoryType::StrongEquality);
10582       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10583     }
10584     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10585     // TODO: Extend support for operator<=> to ObjC types.
10586     return InvalidOperands(Loc, LHS, RHS);
10587   };
10588 
10589 
10590   if (!IsRelational && LHSIsNull != RHSIsNull) {
10591     bool IsEquality = Opc == BO_EQ;
10592     if (RHSIsNull)
10593       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10594                                    RHS.get()->getSourceRange());
10595     else
10596       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10597                                    LHS.get()->getSourceRange());
10598   }
10599 
10600   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10601       (RHSType->isIntegerType() && !RHSIsNull)) {
10602     // Skip normal pointer conversion checks in this case; we have better
10603     // diagnostics for this below.
10604   } else if (getLangOpts().CPlusPlus) {
10605     // Equality comparison of a function pointer to a void pointer is invalid,
10606     // but we allow it as an extension.
10607     // FIXME: If we really want to allow this, should it be part of composite
10608     // pointer type computation so it works in conditionals too?
10609     if (!IsRelational &&
10610         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10611          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10612       // This is a gcc extension compatibility comparison.
10613       // In a SFINAE context, we treat this as a hard error to maintain
10614       // conformance with the C++ standard.
10615       diagnoseFunctionPointerToVoidComparison(
10616           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10617 
10618       if (isSFINAEContext())
10619         return QualType();
10620 
10621       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10622       return computeResultTy();
10623     }
10624 
10625     // C++ [expr.eq]p2:
10626     //   If at least one operand is a pointer [...] bring them to their
10627     //   composite pointer type.
10628     // C++ [expr.spaceship]p6
10629     //  If at least one of the operands is of pointer type, [...] bring them
10630     //  to their composite pointer type.
10631     // C++ [expr.rel]p2:
10632     //   If both operands are pointers, [...] bring them to their composite
10633     //   pointer type.
10634     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10635             (IsRelational ? 2 : 1) &&
10636         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10637                                          RHSType->isObjCObjectPointerType()))) {
10638       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10639         return QualType();
10640       return computeResultTy();
10641     }
10642   } else if (LHSType->isPointerType() &&
10643              RHSType->isPointerType()) { // C99 6.5.8p2
10644     // All of the following pointer-related warnings are GCC extensions, except
10645     // when handling null pointer constants.
10646     QualType LCanPointeeTy =
10647       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10648     QualType RCanPointeeTy =
10649       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10650 
10651     // C99 6.5.9p2 and C99 6.5.8p2
10652     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10653                                    RCanPointeeTy.getUnqualifiedType())) {
10654       // Valid unless a relational comparison of function pointers
10655       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10656         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10657           << LHSType << RHSType << LHS.get()->getSourceRange()
10658           << RHS.get()->getSourceRange();
10659       }
10660     } else if (!IsRelational &&
10661                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10662       // Valid unless comparison between non-null pointer and function pointer
10663       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10664           && !LHSIsNull && !RHSIsNull)
10665         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10666                                                 /*isError*/false);
10667     } else {
10668       // Invalid
10669       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10670     }
10671     if (LCanPointeeTy != RCanPointeeTy) {
10672       // Treat NULL constant as a special case in OpenCL.
10673       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10674         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10675         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10676           Diag(Loc,
10677                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10678               << LHSType << RHSType << 0 /* comparison */
10679               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10680         }
10681       }
10682       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10683       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10684       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10685                                                : CK_BitCast;
10686       if (LHSIsNull && !RHSIsNull)
10687         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10688       else
10689         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10690     }
10691     return computeResultTy();
10692   }
10693 
10694   if (getLangOpts().CPlusPlus) {
10695     // C++ [expr.eq]p4:
10696     //   Two operands of type std::nullptr_t or one operand of type
10697     //   std::nullptr_t and the other a null pointer constant compare equal.
10698     if (!IsRelational && LHSIsNull && RHSIsNull) {
10699       if (LHSType->isNullPtrType()) {
10700         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10701         return computeResultTy();
10702       }
10703       if (RHSType->isNullPtrType()) {
10704         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10705         return computeResultTy();
10706       }
10707     }
10708 
10709     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10710     // These aren't covered by the composite pointer type rules.
10711     if (!IsRelational && RHSType->isNullPtrType() &&
10712         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10713       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10714       return computeResultTy();
10715     }
10716     if (!IsRelational && LHSType->isNullPtrType() &&
10717         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10718       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10719       return computeResultTy();
10720     }
10721 
10722     if (IsRelational &&
10723         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10724          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10725       // HACK: Relational comparison of nullptr_t against a pointer type is
10726       // invalid per DR583, but we allow it within std::less<> and friends,
10727       // since otherwise common uses of it break.
10728       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10729       // friends to have std::nullptr_t overload candidates.
10730       DeclContext *DC = CurContext;
10731       if (isa<FunctionDecl>(DC))
10732         DC = DC->getParent();
10733       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10734         if (CTSD->isInStdNamespace() &&
10735             llvm::StringSwitch<bool>(CTSD->getName())
10736                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10737                 .Default(false)) {
10738           if (RHSType->isNullPtrType())
10739             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10740           else
10741             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10742           return computeResultTy();
10743         }
10744       }
10745     }
10746 
10747     // C++ [expr.eq]p2:
10748     //   If at least one operand is a pointer to member, [...] bring them to
10749     //   their composite pointer type.
10750     if (!IsRelational &&
10751         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10752       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10753         return QualType();
10754       else
10755         return computeResultTy();
10756     }
10757   }
10758 
10759   // Handle block pointer types.
10760   if (!IsRelational && LHSType->isBlockPointerType() &&
10761       RHSType->isBlockPointerType()) {
10762     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10763     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10764 
10765     if (!LHSIsNull && !RHSIsNull &&
10766         !Context.typesAreCompatible(lpointee, rpointee)) {
10767       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10768         << LHSType << RHSType << LHS.get()->getSourceRange()
10769         << RHS.get()->getSourceRange();
10770     }
10771     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10772     return computeResultTy();
10773   }
10774 
10775   // Allow block pointers to be compared with null pointer constants.
10776   if (!IsRelational
10777       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10778           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10779     if (!LHSIsNull && !RHSIsNull) {
10780       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10781              ->getPointeeType()->isVoidType())
10782             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10783                 ->getPointeeType()->isVoidType())))
10784         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10785           << LHSType << RHSType << LHS.get()->getSourceRange()
10786           << RHS.get()->getSourceRange();
10787     }
10788     if (LHSIsNull && !RHSIsNull)
10789       LHS = ImpCastExprToType(LHS.get(), RHSType,
10790                               RHSType->isPointerType() ? CK_BitCast
10791                                 : CK_AnyPointerToBlockPointerCast);
10792     else
10793       RHS = ImpCastExprToType(RHS.get(), LHSType,
10794                               LHSType->isPointerType() ? CK_BitCast
10795                                 : CK_AnyPointerToBlockPointerCast);
10796     return computeResultTy();
10797   }
10798 
10799   if (LHSType->isObjCObjectPointerType() ||
10800       RHSType->isObjCObjectPointerType()) {
10801     const PointerType *LPT = LHSType->getAs<PointerType>();
10802     const PointerType *RPT = RHSType->getAs<PointerType>();
10803     if (LPT || RPT) {
10804       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10805       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10806 
10807       if (!LPtrToVoid && !RPtrToVoid &&
10808           !Context.typesAreCompatible(LHSType, RHSType)) {
10809         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10810                                           /*isError*/false);
10811       }
10812       if (LHSIsNull && !RHSIsNull) {
10813         Expr *E = LHS.get();
10814         if (getLangOpts().ObjCAutoRefCount)
10815           CheckObjCConversion(SourceRange(), RHSType, E,
10816                               CCK_ImplicitConversion);
10817         LHS = ImpCastExprToType(E, RHSType,
10818                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10819       }
10820       else {
10821         Expr *E = RHS.get();
10822         if (getLangOpts().ObjCAutoRefCount)
10823           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10824                               /*Diagnose=*/true,
10825                               /*DiagnoseCFAudited=*/false, Opc);
10826         RHS = ImpCastExprToType(E, LHSType,
10827                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10828       }
10829       return computeResultTy();
10830     }
10831     if (LHSType->isObjCObjectPointerType() &&
10832         RHSType->isObjCObjectPointerType()) {
10833       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10834         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10835                                           /*isError*/false);
10836       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10837         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10838 
10839       if (LHSIsNull && !RHSIsNull)
10840         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10841       else
10842         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10843       return computeResultTy();
10844     }
10845 
10846     if (!IsRelational && LHSType->isBlockPointerType() &&
10847         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10848       LHS = ImpCastExprToType(LHS.get(), RHSType,
10849                               CK_BlockPointerToObjCPointerCast);
10850       return computeResultTy();
10851     } else if (!IsRelational &&
10852                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10853                RHSType->isBlockPointerType()) {
10854       RHS = ImpCastExprToType(RHS.get(), LHSType,
10855                               CK_BlockPointerToObjCPointerCast);
10856       return computeResultTy();
10857     }
10858   }
10859   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10860       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10861     unsigned DiagID = 0;
10862     bool isError = false;
10863     if (LangOpts.DebuggerSupport) {
10864       // Under a debugger, allow the comparison of pointers to integers,
10865       // since users tend to want to compare addresses.
10866     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10867                (RHSIsNull && RHSType->isIntegerType())) {
10868       if (IsRelational) {
10869         isError = getLangOpts().CPlusPlus;
10870         DiagID =
10871           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10872                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10873       }
10874     } else if (getLangOpts().CPlusPlus) {
10875       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10876       isError = true;
10877     } else if (IsRelational)
10878       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10879     else
10880       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10881 
10882     if (DiagID) {
10883       Diag(Loc, DiagID)
10884         << LHSType << RHSType << LHS.get()->getSourceRange()
10885         << RHS.get()->getSourceRange();
10886       if (isError)
10887         return QualType();
10888     }
10889 
10890     if (LHSType->isIntegerType())
10891       LHS = ImpCastExprToType(LHS.get(), RHSType,
10892                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10893     else
10894       RHS = ImpCastExprToType(RHS.get(), LHSType,
10895                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10896     return computeResultTy();
10897   }
10898 
10899   // Handle block pointers.
10900   if (!IsRelational && RHSIsNull
10901       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10902     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10903     return computeResultTy();
10904   }
10905   if (!IsRelational && LHSIsNull
10906       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10907     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10908     return computeResultTy();
10909   }
10910 
10911   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10912     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10913       return computeResultTy();
10914     }
10915 
10916     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10917       return computeResultTy();
10918     }
10919 
10920     if (LHSIsNull && RHSType->isQueueT()) {
10921       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10922       return computeResultTy();
10923     }
10924 
10925     if (LHSType->isQueueT() && RHSIsNull) {
10926       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10927       return computeResultTy();
10928     }
10929   }
10930 
10931   return InvalidOperands(Loc, LHS, RHS);
10932 }
10933 
10934 // Return a signed ext_vector_type that is of identical size and number of
10935 // elements. For floating point vectors, return an integer type of identical
10936 // size and number of elements. In the non ext_vector_type case, search from
10937 // the largest type to the smallest type to avoid cases where long long == long,
10938 // where long gets picked over long long.
10939 QualType Sema::GetSignedVectorType(QualType V) {
10940   const VectorType *VTy = V->getAs<VectorType>();
10941   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10942 
10943   if (isa<ExtVectorType>(VTy)) {
10944     if (TypeSize == Context.getTypeSize(Context.CharTy))
10945       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10946     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10947       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10948     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10949       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10950     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10951       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10952     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10953            "Unhandled vector element size in vector compare");
10954     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10955   }
10956 
10957   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10958     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10959                                  VectorType::GenericVector);
10960   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10961     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10962                                  VectorType::GenericVector);
10963   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10964     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10965                                  VectorType::GenericVector);
10966   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10967     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10968                                  VectorType::GenericVector);
10969   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10970          "Unhandled vector element size in vector compare");
10971   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10972                                VectorType::GenericVector);
10973 }
10974 
10975 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10976 /// operates on extended vector types.  Instead of producing an IntTy result,
10977 /// like a scalar comparison, a vector comparison produces a vector of integer
10978 /// types.
10979 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10980                                           SourceLocation Loc,
10981                                           BinaryOperatorKind Opc) {
10982   // Check to make sure we're operating on vectors of the same type and width,
10983   // Allowing one side to be a scalar of element type.
10984   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10985                               /*AllowBothBool*/true,
10986                               /*AllowBoolConversions*/getLangOpts().ZVector);
10987   if (vType.isNull())
10988     return vType;
10989 
10990   QualType LHSType = LHS.get()->getType();
10991 
10992   // If AltiVec, the comparison results in a numeric type, i.e.
10993   // bool for C++, int for C
10994   if (getLangOpts().AltiVec &&
10995       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10996     return Context.getLogicalOperationType();
10997 
10998   // For non-floating point types, check for self-comparisons of the form
10999   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11000   // often indicate logic errors in the program.
11001   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11002 
11003   // Check for comparisons of floating point operands using != and ==.
11004   if (BinaryOperator::isEqualityOp(Opc) &&
11005       LHSType->hasFloatingRepresentation()) {
11006     assert(RHS.get()->getType()->hasFloatingRepresentation());
11007     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11008   }
11009 
11010   // Return a signed type for the vector.
11011   return GetSignedVectorType(vType);
11012 }
11013 
11014 static void diagnoseXorMisusedAsPow(Sema &S, ExprResult &LHS, ExprResult &RHS,
11015                                     SourceLocation Loc) {
11016   // Do not diagnose macros.
11017   if (Loc.isMacroID())
11018     return;
11019 
11020   bool Negative = false;
11021   const auto *LHSInt = dyn_cast<IntegerLiteral>(LHS.get());
11022   const auto *RHSInt = dyn_cast<IntegerLiteral>(RHS.get());
11023 
11024   if (!LHSInt)
11025     return;
11026   if (!RHSInt) {
11027     // Check negative literals.
11028     if (const auto *UO = dyn_cast<UnaryOperator>(RHS.get())) {
11029       if (UO->getOpcode() != UO_Minus)
11030         return;
11031       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11032       if (!RHSInt)
11033         return;
11034       Negative = true;
11035     } else {
11036       return;
11037     }
11038   }
11039 
11040   if (LHSInt->getValue().getBitWidth() != RHSInt->getValue().getBitWidth())
11041     return;
11042 
11043   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11044       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11045   llvm::StringRef ExprStr =
11046       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11047 
11048   CharSourceRange XorRange =
11049       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11050   llvm::StringRef XorStr =
11051       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11052   // Do not diagnose if xor keyword/macro is used.
11053   if (XorStr == "xor")
11054     return;
11055 
11056   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11057   const llvm::APInt &RightSideValue = RHSInt->getValue();
11058   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11059 
11060   std::string LHSStr = Lexer::getSourceText(
11061       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11062       S.getSourceManager(), S.getLangOpts());
11063   std::string RHSStr = Lexer::getSourceText(
11064       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11065       S.getSourceManager(), S.getLangOpts());
11066 
11067   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11068   if (Negative) {
11069     RightSideIntValue = -RightSideIntValue;
11070     RHSStr = "-" + RHSStr;
11071   }
11072 
11073   StringRef LHSStrRef = LHSStr;
11074   StringRef RHSStrRef = RHSStr;
11075   // Do not diagnose binary, hexadecimal, octal literals.
11076   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11077       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11078       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11079       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11080       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11081       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")))
11082     return;
11083 
11084   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11085     std::string SuggestedExpr = "1 << " + RHSStr;
11086     bool Overflow = false;
11087     llvm::APInt One = (LeftSideValue - 1);
11088     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11089     if (Overflow) {
11090       if (RightSideIntValue < 64)
11091         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11092             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11093             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11094       else
11095          // TODO: 2 ^ 64 - 1
11096         return;
11097     } else {
11098       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11099           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11100           << PowValue.toString(10, true)
11101           << FixItHint::CreateReplacement(
11102                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11103     }
11104 
11105     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr);
11106   } else if (LeftSideValue == 10) {
11107     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11108     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11109         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11110         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11111     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr);
11112   }
11113 }
11114 
11115 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11116                                           SourceLocation Loc) {
11117   // Ensure that either both operands are of the same vector type, or
11118   // one operand is of a vector type and the other is of its element type.
11119   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11120                                        /*AllowBothBool*/true,
11121                                        /*AllowBoolConversions*/false);
11122   if (vType.isNull())
11123     return InvalidOperands(Loc, LHS, RHS);
11124   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11125       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11126     return InvalidOperands(Loc, LHS, RHS);
11127   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11128   //        usage of the logical operators && and || with vectors in C. This
11129   //        check could be notionally dropped.
11130   if (!getLangOpts().CPlusPlus &&
11131       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11132     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11133 
11134   return GetSignedVectorType(LHS.get()->getType());
11135 }
11136 
11137 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11138                                            SourceLocation Loc,
11139                                            BinaryOperatorKind Opc) {
11140   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11141 
11142   bool IsCompAssign =
11143       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11144 
11145   if (LHS.get()->getType()->isVectorType() ||
11146       RHS.get()->getType()->isVectorType()) {
11147     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11148         RHS.get()->getType()->hasIntegerRepresentation())
11149       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11150                         /*AllowBothBool*/true,
11151                         /*AllowBoolConversions*/getLangOpts().ZVector);
11152     return InvalidOperands(Loc, LHS, RHS);
11153   }
11154 
11155   if (Opc == BO_And)
11156     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11157 
11158   if (Opc == BO_Xor)
11159     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11160 
11161   ExprResult LHSResult = LHS, RHSResult = RHS;
11162   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11163                                                  IsCompAssign);
11164   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11165     return QualType();
11166   LHS = LHSResult.get();
11167   RHS = RHSResult.get();
11168 
11169   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11170     return compType;
11171   return InvalidOperands(Loc, LHS, RHS);
11172 }
11173 
11174 // C99 6.5.[13,14]
11175 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11176                                            SourceLocation Loc,
11177                                            BinaryOperatorKind Opc) {
11178   // Check vector operands differently.
11179   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11180     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11181 
11182   // Diagnose cases where the user write a logical and/or but probably meant a
11183   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11184   // is a constant.
11185   if (LHS.get()->getType()->isIntegerType() &&
11186       !LHS.get()->getType()->isBooleanType() &&
11187       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11188       // Don't warn in macros or template instantiations.
11189       !Loc.isMacroID() && !inTemplateInstantiation()) {
11190     // If the RHS can be constant folded, and if it constant folds to something
11191     // that isn't 0 or 1 (which indicate a potential logical operation that
11192     // happened to fold to true/false) then warn.
11193     // Parens on the RHS are ignored.
11194     Expr::EvalResult EVResult;
11195     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11196       llvm::APSInt Result = EVResult.Val.getInt();
11197       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11198            !RHS.get()->getExprLoc().isMacroID()) ||
11199           (Result != 0 && Result != 1)) {
11200         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11201           << RHS.get()->getSourceRange()
11202           << (Opc == BO_LAnd ? "&&" : "||");
11203         // Suggest replacing the logical operator with the bitwise version
11204         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11205             << (Opc == BO_LAnd ? "&" : "|")
11206             << FixItHint::CreateReplacement(SourceRange(
11207                                                  Loc, getLocForEndOfToken(Loc)),
11208                                             Opc == BO_LAnd ? "&" : "|");
11209         if (Opc == BO_LAnd)
11210           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11211           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11212               << FixItHint::CreateRemoval(
11213                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11214                                  RHS.get()->getEndLoc()));
11215       }
11216     }
11217   }
11218 
11219   if (!Context.getLangOpts().CPlusPlus) {
11220     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11221     // not operate on the built-in scalar and vector float types.
11222     if (Context.getLangOpts().OpenCL &&
11223         Context.getLangOpts().OpenCLVersion < 120) {
11224       if (LHS.get()->getType()->isFloatingType() ||
11225           RHS.get()->getType()->isFloatingType())
11226         return InvalidOperands(Loc, LHS, RHS);
11227     }
11228 
11229     LHS = UsualUnaryConversions(LHS.get());
11230     if (LHS.isInvalid())
11231       return QualType();
11232 
11233     RHS = UsualUnaryConversions(RHS.get());
11234     if (RHS.isInvalid())
11235       return QualType();
11236 
11237     if (!LHS.get()->getType()->isScalarType() ||
11238         !RHS.get()->getType()->isScalarType())
11239       return InvalidOperands(Loc, LHS, RHS);
11240 
11241     return Context.IntTy;
11242   }
11243 
11244   // The following is safe because we only use this method for
11245   // non-overloadable operands.
11246 
11247   // C++ [expr.log.and]p1
11248   // C++ [expr.log.or]p1
11249   // The operands are both contextually converted to type bool.
11250   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11251   if (LHSRes.isInvalid())
11252     return InvalidOperands(Loc, LHS, RHS);
11253   LHS = LHSRes;
11254 
11255   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11256   if (RHSRes.isInvalid())
11257     return InvalidOperands(Loc, LHS, RHS);
11258   RHS = RHSRes;
11259 
11260   // C++ [expr.log.and]p2
11261   // C++ [expr.log.or]p2
11262   // The result is a bool.
11263   return Context.BoolTy;
11264 }
11265 
11266 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11267   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11268   if (!ME) return false;
11269   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11270   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11271       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11272   if (!Base) return false;
11273   return Base->getMethodDecl() != nullptr;
11274 }
11275 
11276 /// Is the given expression (which must be 'const') a reference to a
11277 /// variable which was originally non-const, but which has become
11278 /// 'const' due to being captured within a block?
11279 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11280 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11281   assert(E->isLValue() && E->getType().isConstQualified());
11282   E = E->IgnoreParens();
11283 
11284   // Must be a reference to a declaration from an enclosing scope.
11285   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11286   if (!DRE) return NCCK_None;
11287   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11288 
11289   // The declaration must be a variable which is not declared 'const'.
11290   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11291   if (!var) return NCCK_None;
11292   if (var->getType().isConstQualified()) return NCCK_None;
11293   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11294 
11295   // Decide whether the first capture was for a block or a lambda.
11296   DeclContext *DC = S.CurContext, *Prev = nullptr;
11297   // Decide whether the first capture was for a block or a lambda.
11298   while (DC) {
11299     // For init-capture, it is possible that the variable belongs to the
11300     // template pattern of the current context.
11301     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11302       if (var->isInitCapture() &&
11303           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11304         break;
11305     if (DC == var->getDeclContext())
11306       break;
11307     Prev = DC;
11308     DC = DC->getParent();
11309   }
11310   // Unless we have an init-capture, we've gone one step too far.
11311   if (!var->isInitCapture())
11312     DC = Prev;
11313   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11314 }
11315 
11316 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11317   Ty = Ty.getNonReferenceType();
11318   if (IsDereference && Ty->isPointerType())
11319     Ty = Ty->getPointeeType();
11320   return !Ty.isConstQualified();
11321 }
11322 
11323 // Update err_typecheck_assign_const and note_typecheck_assign_const
11324 // when this enum is changed.
11325 enum {
11326   ConstFunction,
11327   ConstVariable,
11328   ConstMember,
11329   ConstMethod,
11330   NestedConstMember,
11331   ConstUnknown,  // Keep as last element
11332 };
11333 
11334 /// Emit the "read-only variable not assignable" error and print notes to give
11335 /// more information about why the variable is not assignable, such as pointing
11336 /// to the declaration of a const variable, showing that a method is const, or
11337 /// that the function is returning a const reference.
11338 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11339                                     SourceLocation Loc) {
11340   SourceRange ExprRange = E->getSourceRange();
11341 
11342   // Only emit one error on the first const found.  All other consts will emit
11343   // a note to the error.
11344   bool DiagnosticEmitted = false;
11345 
11346   // Track if the current expression is the result of a dereference, and if the
11347   // next checked expression is the result of a dereference.
11348   bool IsDereference = false;
11349   bool NextIsDereference = false;
11350 
11351   // Loop to process MemberExpr chains.
11352   while (true) {
11353     IsDereference = NextIsDereference;
11354 
11355     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11356     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11357       NextIsDereference = ME->isArrow();
11358       const ValueDecl *VD = ME->getMemberDecl();
11359       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11360         // Mutable fields can be modified even if the class is const.
11361         if (Field->isMutable()) {
11362           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11363           break;
11364         }
11365 
11366         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11367           if (!DiagnosticEmitted) {
11368             S.Diag(Loc, diag::err_typecheck_assign_const)
11369                 << ExprRange << ConstMember << false /*static*/ << Field
11370                 << Field->getType();
11371             DiagnosticEmitted = true;
11372           }
11373           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11374               << ConstMember << false /*static*/ << Field << Field->getType()
11375               << Field->getSourceRange();
11376         }
11377         E = ME->getBase();
11378         continue;
11379       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11380         if (VDecl->getType().isConstQualified()) {
11381           if (!DiagnosticEmitted) {
11382             S.Diag(Loc, diag::err_typecheck_assign_const)
11383                 << ExprRange << ConstMember << true /*static*/ << VDecl
11384                 << VDecl->getType();
11385             DiagnosticEmitted = true;
11386           }
11387           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11388               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11389               << VDecl->getSourceRange();
11390         }
11391         // Static fields do not inherit constness from parents.
11392         break;
11393       }
11394       break; // End MemberExpr
11395     } else if (const ArraySubscriptExpr *ASE =
11396                    dyn_cast<ArraySubscriptExpr>(E)) {
11397       E = ASE->getBase()->IgnoreParenImpCasts();
11398       continue;
11399     } else if (const ExtVectorElementExpr *EVE =
11400                    dyn_cast<ExtVectorElementExpr>(E)) {
11401       E = EVE->getBase()->IgnoreParenImpCasts();
11402       continue;
11403     }
11404     break;
11405   }
11406 
11407   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11408     // Function calls
11409     const FunctionDecl *FD = CE->getDirectCallee();
11410     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11411       if (!DiagnosticEmitted) {
11412         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11413                                                       << ConstFunction << FD;
11414         DiagnosticEmitted = true;
11415       }
11416       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11417              diag::note_typecheck_assign_const)
11418           << ConstFunction << FD << FD->getReturnType()
11419           << FD->getReturnTypeSourceRange();
11420     }
11421   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11422     // Point to variable declaration.
11423     if (const ValueDecl *VD = DRE->getDecl()) {
11424       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11425         if (!DiagnosticEmitted) {
11426           S.Diag(Loc, diag::err_typecheck_assign_const)
11427               << ExprRange << ConstVariable << VD << VD->getType();
11428           DiagnosticEmitted = true;
11429         }
11430         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11431             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11432       }
11433     }
11434   } else if (isa<CXXThisExpr>(E)) {
11435     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11436       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11437         if (MD->isConst()) {
11438           if (!DiagnosticEmitted) {
11439             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11440                                                           << ConstMethod << MD;
11441             DiagnosticEmitted = true;
11442           }
11443           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11444               << ConstMethod << MD << MD->getSourceRange();
11445         }
11446       }
11447     }
11448   }
11449 
11450   if (DiagnosticEmitted)
11451     return;
11452 
11453   // Can't determine a more specific message, so display the generic error.
11454   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11455 }
11456 
11457 enum OriginalExprKind {
11458   OEK_Variable,
11459   OEK_Member,
11460   OEK_LValue
11461 };
11462 
11463 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11464                                          const RecordType *Ty,
11465                                          SourceLocation Loc, SourceRange Range,
11466                                          OriginalExprKind OEK,
11467                                          bool &DiagnosticEmitted) {
11468   std::vector<const RecordType *> RecordTypeList;
11469   RecordTypeList.push_back(Ty);
11470   unsigned NextToCheckIndex = 0;
11471   // We walk the record hierarchy breadth-first to ensure that we print
11472   // diagnostics in field nesting order.
11473   while (RecordTypeList.size() > NextToCheckIndex) {
11474     bool IsNested = NextToCheckIndex > 0;
11475     for (const FieldDecl *Field :
11476          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11477       // First, check every field for constness.
11478       QualType FieldTy = Field->getType();
11479       if (FieldTy.isConstQualified()) {
11480         if (!DiagnosticEmitted) {
11481           S.Diag(Loc, diag::err_typecheck_assign_const)
11482               << Range << NestedConstMember << OEK << VD
11483               << IsNested << Field;
11484           DiagnosticEmitted = true;
11485         }
11486         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11487             << NestedConstMember << IsNested << Field
11488             << FieldTy << Field->getSourceRange();
11489       }
11490 
11491       // Then we append it to the list to check next in order.
11492       FieldTy = FieldTy.getCanonicalType();
11493       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11494         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11495           RecordTypeList.push_back(FieldRecTy);
11496       }
11497     }
11498     ++NextToCheckIndex;
11499   }
11500 }
11501 
11502 /// Emit an error for the case where a record we are trying to assign to has a
11503 /// const-qualified field somewhere in its hierarchy.
11504 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11505                                          SourceLocation Loc) {
11506   QualType Ty = E->getType();
11507   assert(Ty->isRecordType() && "lvalue was not record?");
11508   SourceRange Range = E->getSourceRange();
11509   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11510   bool DiagEmitted = false;
11511 
11512   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11513     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11514             Range, OEK_Member, DiagEmitted);
11515   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11516     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11517             Range, OEK_Variable, DiagEmitted);
11518   else
11519     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11520             Range, OEK_LValue, DiagEmitted);
11521   if (!DiagEmitted)
11522     DiagnoseConstAssignment(S, E, Loc);
11523 }
11524 
11525 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11526 /// emit an error and return true.  If so, return false.
11527 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11528   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11529 
11530   S.CheckShadowingDeclModification(E, Loc);
11531 
11532   SourceLocation OrigLoc = Loc;
11533   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11534                                                               &Loc);
11535   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11536     IsLV = Expr::MLV_InvalidMessageExpression;
11537   if (IsLV == Expr::MLV_Valid)
11538     return false;
11539 
11540   unsigned DiagID = 0;
11541   bool NeedType = false;
11542   switch (IsLV) { // C99 6.5.16p2
11543   case Expr::MLV_ConstQualified:
11544     // Use a specialized diagnostic when we're assigning to an object
11545     // from an enclosing function or block.
11546     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11547       if (NCCK == NCCK_Block)
11548         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11549       else
11550         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11551       break;
11552     }
11553 
11554     // In ARC, use some specialized diagnostics for occasions where we
11555     // infer 'const'.  These are always pseudo-strong variables.
11556     if (S.getLangOpts().ObjCAutoRefCount) {
11557       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11558       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11559         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11560 
11561         // Use the normal diagnostic if it's pseudo-__strong but the
11562         // user actually wrote 'const'.
11563         if (var->isARCPseudoStrong() &&
11564             (!var->getTypeSourceInfo() ||
11565              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11566           // There are three pseudo-strong cases:
11567           //  - self
11568           ObjCMethodDecl *method = S.getCurMethodDecl();
11569           if (method && var == method->getSelfDecl()) {
11570             DiagID = method->isClassMethod()
11571               ? diag::err_typecheck_arc_assign_self_class_method
11572               : diag::err_typecheck_arc_assign_self;
11573 
11574           //  - Objective-C externally_retained attribute.
11575           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11576                      isa<ParmVarDecl>(var)) {
11577             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11578 
11579           //  - fast enumeration variables
11580           } else {
11581             DiagID = diag::err_typecheck_arr_assign_enumeration;
11582           }
11583 
11584           SourceRange Assign;
11585           if (Loc != OrigLoc)
11586             Assign = SourceRange(OrigLoc, OrigLoc);
11587           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11588           // We need to preserve the AST regardless, so migration tool
11589           // can do its job.
11590           return false;
11591         }
11592       }
11593     }
11594 
11595     // If none of the special cases above are triggered, then this is a
11596     // simple const assignment.
11597     if (DiagID == 0) {
11598       DiagnoseConstAssignment(S, E, Loc);
11599       return true;
11600     }
11601 
11602     break;
11603   case Expr::MLV_ConstAddrSpace:
11604     DiagnoseConstAssignment(S, E, Loc);
11605     return true;
11606   case Expr::MLV_ConstQualifiedField:
11607     DiagnoseRecursiveConstFields(S, E, Loc);
11608     return true;
11609   case Expr::MLV_ArrayType:
11610   case Expr::MLV_ArrayTemporary:
11611     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11612     NeedType = true;
11613     break;
11614   case Expr::MLV_NotObjectType:
11615     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11616     NeedType = true;
11617     break;
11618   case Expr::MLV_LValueCast:
11619     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11620     break;
11621   case Expr::MLV_Valid:
11622     llvm_unreachable("did not take early return for MLV_Valid");
11623   case Expr::MLV_InvalidExpression:
11624   case Expr::MLV_MemberFunction:
11625   case Expr::MLV_ClassTemporary:
11626     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11627     break;
11628   case Expr::MLV_IncompleteType:
11629   case Expr::MLV_IncompleteVoidType:
11630     return S.RequireCompleteType(Loc, E->getType(),
11631              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11632   case Expr::MLV_DuplicateVectorComponents:
11633     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11634     break;
11635   case Expr::MLV_NoSetterProperty:
11636     llvm_unreachable("readonly properties should be processed differently");
11637   case Expr::MLV_InvalidMessageExpression:
11638     DiagID = diag::err_readonly_message_assignment;
11639     break;
11640   case Expr::MLV_SubObjCPropertySetting:
11641     DiagID = diag::err_no_subobject_property_setting;
11642     break;
11643   }
11644 
11645   SourceRange Assign;
11646   if (Loc != OrigLoc)
11647     Assign = SourceRange(OrigLoc, OrigLoc);
11648   if (NeedType)
11649     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11650   else
11651     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11652   return true;
11653 }
11654 
11655 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11656                                          SourceLocation Loc,
11657                                          Sema &Sema) {
11658   if (Sema.inTemplateInstantiation())
11659     return;
11660   if (Sema.isUnevaluatedContext())
11661     return;
11662   if (Loc.isInvalid() || Loc.isMacroID())
11663     return;
11664   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11665     return;
11666 
11667   // C / C++ fields
11668   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11669   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11670   if (ML && MR) {
11671     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11672       return;
11673     const ValueDecl *LHSDecl =
11674         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11675     const ValueDecl *RHSDecl =
11676         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11677     if (LHSDecl != RHSDecl)
11678       return;
11679     if (LHSDecl->getType().isVolatileQualified())
11680       return;
11681     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11682       if (RefTy->getPointeeType().isVolatileQualified())
11683         return;
11684 
11685     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11686   }
11687 
11688   // Objective-C instance variables
11689   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11690   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11691   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11692     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11693     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11694     if (RL && RR && RL->getDecl() == RR->getDecl())
11695       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11696   }
11697 }
11698 
11699 // C99 6.5.16.1
11700 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11701                                        SourceLocation Loc,
11702                                        QualType CompoundType) {
11703   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11704 
11705   // Verify that LHS is a modifiable lvalue, and emit error if not.
11706   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11707     return QualType();
11708 
11709   QualType LHSType = LHSExpr->getType();
11710   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11711                                              CompoundType;
11712   // OpenCL v1.2 s6.1.1.1 p2:
11713   // The half data type can only be used to declare a pointer to a buffer that
11714   // contains half values
11715   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11716     LHSType->isHalfType()) {
11717     Diag(Loc, diag::err_opencl_half_load_store) << 1
11718         << LHSType.getUnqualifiedType();
11719     return QualType();
11720   }
11721 
11722   AssignConvertType ConvTy;
11723   if (CompoundType.isNull()) {
11724     Expr *RHSCheck = RHS.get();
11725 
11726     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11727 
11728     QualType LHSTy(LHSType);
11729     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11730     if (RHS.isInvalid())
11731       return QualType();
11732     // Special case of NSObject attributes on c-style pointer types.
11733     if (ConvTy == IncompatiblePointer &&
11734         ((Context.isObjCNSObjectType(LHSType) &&
11735           RHSType->isObjCObjectPointerType()) ||
11736          (Context.isObjCNSObjectType(RHSType) &&
11737           LHSType->isObjCObjectPointerType())))
11738       ConvTy = Compatible;
11739 
11740     if (ConvTy == Compatible &&
11741         LHSType->isObjCObjectType())
11742         Diag(Loc, diag::err_objc_object_assignment)
11743           << LHSType;
11744 
11745     // If the RHS is a unary plus or minus, check to see if they = and + are
11746     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11747     // instead of "x += 4".
11748     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11749       RHSCheck = ICE->getSubExpr();
11750     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11751       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11752           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11753           // Only if the two operators are exactly adjacent.
11754           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11755           // And there is a space or other character before the subexpr of the
11756           // unary +/-.  We don't want to warn on "x=-1".
11757           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11758           UO->getSubExpr()->getBeginLoc().isFileID()) {
11759         Diag(Loc, diag::warn_not_compound_assign)
11760           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11761           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11762       }
11763     }
11764 
11765     if (ConvTy == Compatible) {
11766       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11767         // Warn about retain cycles where a block captures the LHS, but
11768         // not if the LHS is a simple variable into which the block is
11769         // being stored...unless that variable can be captured by reference!
11770         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11771         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11772         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11773           checkRetainCycles(LHSExpr, RHS.get());
11774       }
11775 
11776       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11777           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11778         // It is safe to assign a weak reference into a strong variable.
11779         // Although this code can still have problems:
11780         //   id x = self.weakProp;
11781         //   id y = self.weakProp;
11782         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11783         // paths through the function. This should be revisited if
11784         // -Wrepeated-use-of-weak is made flow-sensitive.
11785         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11786         // variable, which will be valid for the current autorelease scope.
11787         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11788                              RHS.get()->getBeginLoc()))
11789           getCurFunction()->markSafeWeakUse(RHS.get());
11790 
11791       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11792         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11793       }
11794     }
11795   } else {
11796     // Compound assignment "x += y"
11797     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11798   }
11799 
11800   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11801                                RHS.get(), AA_Assigning))
11802     return QualType();
11803 
11804   CheckForNullPointerDereference(*this, LHSExpr);
11805 
11806   // C99 6.5.16p3: The type of an assignment expression is the type of the
11807   // left operand unless the left operand has qualified type, in which case
11808   // it is the unqualified version of the type of the left operand.
11809   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11810   // is converted to the type of the assignment expression (above).
11811   // C++ 5.17p1: the type of the assignment expression is that of its left
11812   // operand.
11813   return (getLangOpts().CPlusPlus
11814           ? LHSType : LHSType.getUnqualifiedType());
11815 }
11816 
11817 // Only ignore explicit casts to void.
11818 static bool IgnoreCommaOperand(const Expr *E) {
11819   E = E->IgnoreParens();
11820 
11821   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11822     if (CE->getCastKind() == CK_ToVoid) {
11823       return true;
11824     }
11825 
11826     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11827     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11828         CE->getSubExpr()->getType()->isDependentType()) {
11829       return true;
11830     }
11831   }
11832 
11833   return false;
11834 }
11835 
11836 // Look for instances where it is likely the comma operator is confused with
11837 // another operator.  There is a whitelist of acceptable expressions for the
11838 // left hand side of the comma operator, otherwise emit a warning.
11839 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11840   // No warnings in macros
11841   if (Loc.isMacroID())
11842     return;
11843 
11844   // Don't warn in template instantiations.
11845   if (inTemplateInstantiation())
11846     return;
11847 
11848   // Scope isn't fine-grained enough to whitelist the specific cases, so
11849   // instead, skip more than needed, then call back into here with the
11850   // CommaVisitor in SemaStmt.cpp.
11851   // The whitelisted locations are the initialization and increment portions
11852   // of a for loop.  The additional checks are on the condition of
11853   // if statements, do/while loops, and for loops.
11854   // Differences in scope flags for C89 mode requires the extra logic.
11855   const unsigned ForIncrementFlags =
11856       getLangOpts().C99 || getLangOpts().CPlusPlus
11857           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11858           : Scope::ContinueScope | Scope::BreakScope;
11859   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11860   const unsigned ScopeFlags = getCurScope()->getFlags();
11861   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11862       (ScopeFlags & ForInitFlags) == ForInitFlags)
11863     return;
11864 
11865   // If there are multiple comma operators used together, get the RHS of the
11866   // of the comma operator as the LHS.
11867   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11868     if (BO->getOpcode() != BO_Comma)
11869       break;
11870     LHS = BO->getRHS();
11871   }
11872 
11873   // Only allow some expressions on LHS to not warn.
11874   if (IgnoreCommaOperand(LHS))
11875     return;
11876 
11877   Diag(Loc, diag::warn_comma_operator);
11878   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11879       << LHS->getSourceRange()
11880       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11881                                     LangOpts.CPlusPlus ? "static_cast<void>("
11882                                                        : "(void)(")
11883       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11884                                     ")");
11885 }
11886 
11887 // C99 6.5.17
11888 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11889                                    SourceLocation Loc) {
11890   LHS = S.CheckPlaceholderExpr(LHS.get());
11891   RHS = S.CheckPlaceholderExpr(RHS.get());
11892   if (LHS.isInvalid() || RHS.isInvalid())
11893     return QualType();
11894 
11895   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11896   // operands, but not unary promotions.
11897   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11898 
11899   // So we treat the LHS as a ignored value, and in C++ we allow the
11900   // containing site to determine what should be done with the RHS.
11901   LHS = S.IgnoredValueConversions(LHS.get());
11902   if (LHS.isInvalid())
11903     return QualType();
11904 
11905   S.DiagnoseUnusedExprResult(LHS.get());
11906 
11907   if (!S.getLangOpts().CPlusPlus) {
11908     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11909     if (RHS.isInvalid())
11910       return QualType();
11911     if (!RHS.get()->getType()->isVoidType())
11912       S.RequireCompleteType(Loc, RHS.get()->getType(),
11913                             diag::err_incomplete_type);
11914   }
11915 
11916   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11917     S.DiagnoseCommaOperator(LHS.get(), Loc);
11918 
11919   return RHS.get()->getType();
11920 }
11921 
11922 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11923 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11924 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11925                                                ExprValueKind &VK,
11926                                                ExprObjectKind &OK,
11927                                                SourceLocation OpLoc,
11928                                                bool IsInc, bool IsPrefix) {
11929   if (Op->isTypeDependent())
11930     return S.Context.DependentTy;
11931 
11932   QualType ResType = Op->getType();
11933   // Atomic types can be used for increment / decrement where the non-atomic
11934   // versions can, so ignore the _Atomic() specifier for the purpose of
11935   // checking.
11936   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11937     ResType = ResAtomicType->getValueType();
11938 
11939   assert(!ResType.isNull() && "no type for increment/decrement expression");
11940 
11941   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11942     // Decrement of bool is not allowed.
11943     if (!IsInc) {
11944       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11945       return QualType();
11946     }
11947     // Increment of bool sets it to true, but is deprecated.
11948     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11949                                               : diag::warn_increment_bool)
11950       << Op->getSourceRange();
11951   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11952     // Error on enum increments and decrements in C++ mode
11953     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11954     return QualType();
11955   } else if (ResType->isRealType()) {
11956     // OK!
11957   } else if (ResType->isPointerType()) {
11958     // C99 6.5.2.4p2, 6.5.6p2
11959     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11960       return QualType();
11961   } else if (ResType->isObjCObjectPointerType()) {
11962     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11963     // Otherwise, we just need a complete type.
11964     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11965         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11966       return QualType();
11967   } else if (ResType->isAnyComplexType()) {
11968     // C99 does not support ++/-- on complex types, we allow as an extension.
11969     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11970       << ResType << Op->getSourceRange();
11971   } else if (ResType->isPlaceholderType()) {
11972     ExprResult PR = S.CheckPlaceholderExpr(Op);
11973     if (PR.isInvalid()) return QualType();
11974     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11975                                           IsInc, IsPrefix);
11976   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11977     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11978   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11979              (ResType->getAs<VectorType>()->getVectorKind() !=
11980               VectorType::AltiVecBool)) {
11981     // The z vector extensions allow ++ and -- for non-bool vectors.
11982   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11983             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11984     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11985   } else {
11986     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11987       << ResType << int(IsInc) << Op->getSourceRange();
11988     return QualType();
11989   }
11990   // At this point, we know we have a real, complex or pointer type.
11991   // Now make sure the operand is a modifiable lvalue.
11992   if (CheckForModifiableLvalue(Op, OpLoc, S))
11993     return QualType();
11994   // In C++, a prefix increment is the same type as the operand. Otherwise
11995   // (in C or with postfix), the increment is the unqualified type of the
11996   // operand.
11997   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11998     VK = VK_LValue;
11999     OK = Op->getObjectKind();
12000     return ResType;
12001   } else {
12002     VK = VK_RValue;
12003     return ResType.getUnqualifiedType();
12004   }
12005 }
12006 
12007 
12008 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12009 /// This routine allows us to typecheck complex/recursive expressions
12010 /// where the declaration is needed for type checking. We only need to
12011 /// handle cases when the expression references a function designator
12012 /// or is an lvalue. Here are some examples:
12013 ///  - &(x) => x
12014 ///  - &*****f => f for f a function designator.
12015 ///  - &s.xx => s
12016 ///  - &s.zz[1].yy -> s, if zz is an array
12017 ///  - *(x + 1) -> x, if x is an array
12018 ///  - &"123"[2] -> 0
12019 ///  - & __real__ x -> x
12020 static ValueDecl *getPrimaryDecl(Expr *E) {
12021   switch (E->getStmtClass()) {
12022   case Stmt::DeclRefExprClass:
12023     return cast<DeclRefExpr>(E)->getDecl();
12024   case Stmt::MemberExprClass:
12025     // If this is an arrow operator, the address is an offset from
12026     // the base's value, so the object the base refers to is
12027     // irrelevant.
12028     if (cast<MemberExpr>(E)->isArrow())
12029       return nullptr;
12030     // Otherwise, the expression refers to a part of the base
12031     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12032   case Stmt::ArraySubscriptExprClass: {
12033     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12034     // promotion of register arrays earlier.
12035     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12036     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12037       if (ICE->getSubExpr()->getType()->isArrayType())
12038         return getPrimaryDecl(ICE->getSubExpr());
12039     }
12040     return nullptr;
12041   }
12042   case Stmt::UnaryOperatorClass: {
12043     UnaryOperator *UO = cast<UnaryOperator>(E);
12044 
12045     switch(UO->getOpcode()) {
12046     case UO_Real:
12047     case UO_Imag:
12048     case UO_Extension:
12049       return getPrimaryDecl(UO->getSubExpr());
12050     default:
12051       return nullptr;
12052     }
12053   }
12054   case Stmt::ParenExprClass:
12055     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12056   case Stmt::ImplicitCastExprClass:
12057     // If the result of an implicit cast is an l-value, we care about
12058     // the sub-expression; otherwise, the result here doesn't matter.
12059     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12060   default:
12061     return nullptr;
12062   }
12063 }
12064 
12065 namespace {
12066   enum {
12067     AO_Bit_Field = 0,
12068     AO_Vector_Element = 1,
12069     AO_Property_Expansion = 2,
12070     AO_Register_Variable = 3,
12071     AO_No_Error = 4
12072   };
12073 }
12074 /// Diagnose invalid operand for address of operations.
12075 ///
12076 /// \param Type The type of operand which cannot have its address taken.
12077 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12078                                          Expr *E, unsigned Type) {
12079   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12080 }
12081 
12082 /// CheckAddressOfOperand - The operand of & must be either a function
12083 /// designator or an lvalue designating an object. If it is an lvalue, the
12084 /// object cannot be declared with storage class register or be a bit field.
12085 /// Note: The usual conversions are *not* applied to the operand of the &
12086 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12087 /// In C++, the operand might be an overloaded function name, in which case
12088 /// we allow the '&' but retain the overloaded-function type.
12089 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12090   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12091     if (PTy->getKind() == BuiltinType::Overload) {
12092       Expr *E = OrigOp.get()->IgnoreParens();
12093       if (!isa<OverloadExpr>(E)) {
12094         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12095         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12096           << OrigOp.get()->getSourceRange();
12097         return QualType();
12098       }
12099 
12100       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12101       if (isa<UnresolvedMemberExpr>(Ovl))
12102         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12103           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12104             << OrigOp.get()->getSourceRange();
12105           return QualType();
12106         }
12107 
12108       return Context.OverloadTy;
12109     }
12110 
12111     if (PTy->getKind() == BuiltinType::UnknownAny)
12112       return Context.UnknownAnyTy;
12113 
12114     if (PTy->getKind() == BuiltinType::BoundMember) {
12115       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12116         << OrigOp.get()->getSourceRange();
12117       return QualType();
12118     }
12119 
12120     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12121     if (OrigOp.isInvalid()) return QualType();
12122   }
12123 
12124   if (OrigOp.get()->isTypeDependent())
12125     return Context.DependentTy;
12126 
12127   assert(!OrigOp.get()->getType()->isPlaceholderType());
12128 
12129   // Make sure to ignore parentheses in subsequent checks
12130   Expr *op = OrigOp.get()->IgnoreParens();
12131 
12132   // In OpenCL captures for blocks called as lambda functions
12133   // are located in the private address space. Blocks used in
12134   // enqueue_kernel can be located in a different address space
12135   // depending on a vendor implementation. Thus preventing
12136   // taking an address of the capture to avoid invalid AS casts.
12137   if (LangOpts.OpenCL) {
12138     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12139     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12140       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12141       return QualType();
12142     }
12143   }
12144 
12145   if (getLangOpts().C99) {
12146     // Implement C99-only parts of addressof rules.
12147     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12148       if (uOp->getOpcode() == UO_Deref)
12149         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12150         // (assuming the deref expression is valid).
12151         return uOp->getSubExpr()->getType();
12152     }
12153     // Technically, there should be a check for array subscript
12154     // expressions here, but the result of one is always an lvalue anyway.
12155   }
12156   ValueDecl *dcl = getPrimaryDecl(op);
12157 
12158   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12159     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12160                                            op->getBeginLoc()))
12161       return QualType();
12162 
12163   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12164   unsigned AddressOfError = AO_No_Error;
12165 
12166   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12167     bool sfinae = (bool)isSFINAEContext();
12168     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12169                                   : diag::ext_typecheck_addrof_temporary)
12170       << op->getType() << op->getSourceRange();
12171     if (sfinae)
12172       return QualType();
12173     // Materialize the temporary as an lvalue so that we can take its address.
12174     OrigOp = op =
12175         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12176   } else if (isa<ObjCSelectorExpr>(op)) {
12177     return Context.getPointerType(op->getType());
12178   } else if (lval == Expr::LV_MemberFunction) {
12179     // If it's an instance method, make a member pointer.
12180     // The expression must have exactly the form &A::foo.
12181 
12182     // If the underlying expression isn't a decl ref, give up.
12183     if (!isa<DeclRefExpr>(op)) {
12184       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12185         << OrigOp.get()->getSourceRange();
12186       return QualType();
12187     }
12188     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12189     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12190 
12191     // The id-expression was parenthesized.
12192     if (OrigOp.get() != DRE) {
12193       Diag(OpLoc, diag::err_parens_pointer_member_function)
12194         << OrigOp.get()->getSourceRange();
12195 
12196     // The method was named without a qualifier.
12197     } else if (!DRE->getQualifier()) {
12198       if (MD->getParent()->getName().empty())
12199         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12200           << op->getSourceRange();
12201       else {
12202         SmallString<32> Str;
12203         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12204         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12205           << op->getSourceRange()
12206           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12207       }
12208     }
12209 
12210     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12211     if (isa<CXXDestructorDecl>(MD))
12212       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12213 
12214     QualType MPTy = Context.getMemberPointerType(
12215         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12216     // Under the MS ABI, lock down the inheritance model now.
12217     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12218       (void)isCompleteType(OpLoc, MPTy);
12219     return MPTy;
12220   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12221     // C99 6.5.3.2p1
12222     // The operand must be either an l-value or a function designator
12223     if (!op->getType()->isFunctionType()) {
12224       // Use a special diagnostic for loads from property references.
12225       if (isa<PseudoObjectExpr>(op)) {
12226         AddressOfError = AO_Property_Expansion;
12227       } else {
12228         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12229           << op->getType() << op->getSourceRange();
12230         return QualType();
12231       }
12232     }
12233   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12234     // The operand cannot be a bit-field
12235     AddressOfError = AO_Bit_Field;
12236   } else if (op->getObjectKind() == OK_VectorComponent) {
12237     // The operand cannot be an element of a vector
12238     AddressOfError = AO_Vector_Element;
12239   } else if (dcl) { // C99 6.5.3.2p1
12240     // We have an lvalue with a decl. Make sure the decl is not declared
12241     // with the register storage-class specifier.
12242     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12243       // in C++ it is not error to take address of a register
12244       // variable (c++03 7.1.1P3)
12245       if (vd->getStorageClass() == SC_Register &&
12246           !getLangOpts().CPlusPlus) {
12247         AddressOfError = AO_Register_Variable;
12248       }
12249     } else if (isa<MSPropertyDecl>(dcl)) {
12250       AddressOfError = AO_Property_Expansion;
12251     } else if (isa<FunctionTemplateDecl>(dcl)) {
12252       return Context.OverloadTy;
12253     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12254       // Okay: we can take the address of a field.
12255       // Could be a pointer to member, though, if there is an explicit
12256       // scope qualifier for the class.
12257       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12258         DeclContext *Ctx = dcl->getDeclContext();
12259         if (Ctx && Ctx->isRecord()) {
12260           if (dcl->getType()->isReferenceType()) {
12261             Diag(OpLoc,
12262                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12263               << dcl->getDeclName() << dcl->getType();
12264             return QualType();
12265           }
12266 
12267           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12268             Ctx = Ctx->getParent();
12269 
12270           QualType MPTy = Context.getMemberPointerType(
12271               op->getType(),
12272               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12273           // Under the MS ABI, lock down the inheritance model now.
12274           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12275             (void)isCompleteType(OpLoc, MPTy);
12276           return MPTy;
12277         }
12278       }
12279     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12280                !isa<BindingDecl>(dcl))
12281       llvm_unreachable("Unknown/unexpected decl type");
12282   }
12283 
12284   if (AddressOfError != AO_No_Error) {
12285     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12286     return QualType();
12287   }
12288 
12289   if (lval == Expr::LV_IncompleteVoidType) {
12290     // Taking the address of a void variable is technically illegal, but we
12291     // allow it in cases which are otherwise valid.
12292     // Example: "extern void x; void* y = &x;".
12293     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12294   }
12295 
12296   // If the operand has type "type", the result has type "pointer to type".
12297   if (op->getType()->isObjCObjectType())
12298     return Context.getObjCObjectPointerType(op->getType());
12299 
12300   CheckAddressOfPackedMember(op);
12301 
12302   return Context.getPointerType(op->getType());
12303 }
12304 
12305 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12306   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12307   if (!DRE)
12308     return;
12309   const Decl *D = DRE->getDecl();
12310   if (!D)
12311     return;
12312   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12313   if (!Param)
12314     return;
12315   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12316     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12317       return;
12318   if (FunctionScopeInfo *FD = S.getCurFunction())
12319     if (!FD->ModifiedNonNullParams.count(Param))
12320       FD->ModifiedNonNullParams.insert(Param);
12321 }
12322 
12323 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12324 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12325                                         SourceLocation OpLoc) {
12326   if (Op->isTypeDependent())
12327     return S.Context.DependentTy;
12328 
12329   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12330   if (ConvResult.isInvalid())
12331     return QualType();
12332   Op = ConvResult.get();
12333   QualType OpTy = Op->getType();
12334   QualType Result;
12335 
12336   if (isa<CXXReinterpretCastExpr>(Op)) {
12337     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12338     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12339                                      Op->getSourceRange());
12340   }
12341 
12342   if (const PointerType *PT = OpTy->getAs<PointerType>())
12343   {
12344     Result = PT->getPointeeType();
12345   }
12346   else if (const ObjCObjectPointerType *OPT =
12347              OpTy->getAs<ObjCObjectPointerType>())
12348     Result = OPT->getPointeeType();
12349   else {
12350     ExprResult PR = S.CheckPlaceholderExpr(Op);
12351     if (PR.isInvalid()) return QualType();
12352     if (PR.get() != Op)
12353       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12354   }
12355 
12356   if (Result.isNull()) {
12357     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12358       << OpTy << Op->getSourceRange();
12359     return QualType();
12360   }
12361 
12362   // Note that per both C89 and C99, indirection is always legal, even if Result
12363   // is an incomplete type or void.  It would be possible to warn about
12364   // dereferencing a void pointer, but it's completely well-defined, and such a
12365   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12366   // for pointers to 'void' but is fine for any other pointer type:
12367   //
12368   // C++ [expr.unary.op]p1:
12369   //   [...] the expression to which [the unary * operator] is applied shall
12370   //   be a pointer to an object type, or a pointer to a function type
12371   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12372     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12373       << OpTy << Op->getSourceRange();
12374 
12375   // Dereferences are usually l-values...
12376   VK = VK_LValue;
12377 
12378   // ...except that certain expressions are never l-values in C.
12379   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12380     VK = VK_RValue;
12381 
12382   return Result;
12383 }
12384 
12385 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12386   BinaryOperatorKind Opc;
12387   switch (Kind) {
12388   default: llvm_unreachable("Unknown binop!");
12389   case tok::periodstar:           Opc = BO_PtrMemD; break;
12390   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12391   case tok::star:                 Opc = BO_Mul; break;
12392   case tok::slash:                Opc = BO_Div; break;
12393   case tok::percent:              Opc = BO_Rem; break;
12394   case tok::plus:                 Opc = BO_Add; break;
12395   case tok::minus:                Opc = BO_Sub; break;
12396   case tok::lessless:             Opc = BO_Shl; break;
12397   case tok::greatergreater:       Opc = BO_Shr; break;
12398   case tok::lessequal:            Opc = BO_LE; break;
12399   case tok::less:                 Opc = BO_LT; break;
12400   case tok::greaterequal:         Opc = BO_GE; break;
12401   case tok::greater:              Opc = BO_GT; break;
12402   case tok::exclaimequal:         Opc = BO_NE; break;
12403   case tok::equalequal:           Opc = BO_EQ; break;
12404   case tok::spaceship:            Opc = BO_Cmp; break;
12405   case tok::amp:                  Opc = BO_And; break;
12406   case tok::caret:                Opc = BO_Xor; break;
12407   case tok::pipe:                 Opc = BO_Or; break;
12408   case tok::ampamp:               Opc = BO_LAnd; break;
12409   case tok::pipepipe:             Opc = BO_LOr; break;
12410   case tok::equal:                Opc = BO_Assign; break;
12411   case tok::starequal:            Opc = BO_MulAssign; break;
12412   case tok::slashequal:           Opc = BO_DivAssign; break;
12413   case tok::percentequal:         Opc = BO_RemAssign; break;
12414   case tok::plusequal:            Opc = BO_AddAssign; break;
12415   case tok::minusequal:           Opc = BO_SubAssign; break;
12416   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12417   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12418   case tok::ampequal:             Opc = BO_AndAssign; break;
12419   case tok::caretequal:           Opc = BO_XorAssign; break;
12420   case tok::pipeequal:            Opc = BO_OrAssign; break;
12421   case tok::comma:                Opc = BO_Comma; break;
12422   }
12423   return Opc;
12424 }
12425 
12426 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12427   tok::TokenKind Kind) {
12428   UnaryOperatorKind Opc;
12429   switch (Kind) {
12430   default: llvm_unreachable("Unknown unary op!");
12431   case tok::plusplus:     Opc = UO_PreInc; break;
12432   case tok::minusminus:   Opc = UO_PreDec; break;
12433   case tok::amp:          Opc = UO_AddrOf; break;
12434   case tok::star:         Opc = UO_Deref; break;
12435   case tok::plus:         Opc = UO_Plus; break;
12436   case tok::minus:        Opc = UO_Minus; break;
12437   case tok::tilde:        Opc = UO_Not; break;
12438   case tok::exclaim:      Opc = UO_LNot; break;
12439   case tok::kw___real:    Opc = UO_Real; break;
12440   case tok::kw___imag:    Opc = UO_Imag; break;
12441   case tok::kw___extension__: Opc = UO_Extension; break;
12442   }
12443   return Opc;
12444 }
12445 
12446 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12447 /// This warning suppressed in the event of macro expansions.
12448 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12449                                    SourceLocation OpLoc, bool IsBuiltin) {
12450   if (S.inTemplateInstantiation())
12451     return;
12452   if (S.isUnevaluatedContext())
12453     return;
12454   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12455     return;
12456   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12457   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12458   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12459   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12460   if (!LHSDeclRef || !RHSDeclRef ||
12461       LHSDeclRef->getLocation().isMacroID() ||
12462       RHSDeclRef->getLocation().isMacroID())
12463     return;
12464   const ValueDecl *LHSDecl =
12465     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12466   const ValueDecl *RHSDecl =
12467     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12468   if (LHSDecl != RHSDecl)
12469     return;
12470   if (LHSDecl->getType().isVolatileQualified())
12471     return;
12472   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12473     if (RefTy->getPointeeType().isVolatileQualified())
12474       return;
12475 
12476   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12477                           : diag::warn_self_assignment_overloaded)
12478       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12479       << RHSExpr->getSourceRange();
12480 }
12481 
12482 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12483 /// is usually indicative of introspection within the Objective-C pointer.
12484 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12485                                           SourceLocation OpLoc) {
12486   if (!S.getLangOpts().ObjC)
12487     return;
12488 
12489   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12490   const Expr *LHS = L.get();
12491   const Expr *RHS = R.get();
12492 
12493   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12494     ObjCPointerExpr = LHS;
12495     OtherExpr = RHS;
12496   }
12497   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12498     ObjCPointerExpr = RHS;
12499     OtherExpr = LHS;
12500   }
12501 
12502   // This warning is deliberately made very specific to reduce false
12503   // positives with logic that uses '&' for hashing.  This logic mainly
12504   // looks for code trying to introspect into tagged pointers, which
12505   // code should generally never do.
12506   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12507     unsigned Diag = diag::warn_objc_pointer_masking;
12508     // Determine if we are introspecting the result of performSelectorXXX.
12509     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12510     // Special case messages to -performSelector and friends, which
12511     // can return non-pointer values boxed in a pointer value.
12512     // Some clients may wish to silence warnings in this subcase.
12513     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12514       Selector S = ME->getSelector();
12515       StringRef SelArg0 = S.getNameForSlot(0);
12516       if (SelArg0.startswith("performSelector"))
12517         Diag = diag::warn_objc_pointer_masking_performSelector;
12518     }
12519 
12520     S.Diag(OpLoc, Diag)
12521       << ObjCPointerExpr->getSourceRange();
12522   }
12523 }
12524 
12525 static NamedDecl *getDeclFromExpr(Expr *E) {
12526   if (!E)
12527     return nullptr;
12528   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12529     return DRE->getDecl();
12530   if (auto *ME = dyn_cast<MemberExpr>(E))
12531     return ME->getMemberDecl();
12532   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12533     return IRE->getDecl();
12534   return nullptr;
12535 }
12536 
12537 // This helper function promotes a binary operator's operands (which are of a
12538 // half vector type) to a vector of floats and then truncates the result to
12539 // a vector of either half or short.
12540 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12541                                       BinaryOperatorKind Opc, QualType ResultTy,
12542                                       ExprValueKind VK, ExprObjectKind OK,
12543                                       bool IsCompAssign, SourceLocation OpLoc,
12544                                       FPOptions FPFeatures) {
12545   auto &Context = S.getASTContext();
12546   assert((isVector(ResultTy, Context.HalfTy) ||
12547           isVector(ResultTy, Context.ShortTy)) &&
12548          "Result must be a vector of half or short");
12549   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12550          isVector(RHS.get()->getType(), Context.HalfTy) &&
12551          "both operands expected to be a half vector");
12552 
12553   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12554   QualType BinOpResTy = RHS.get()->getType();
12555 
12556   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12557   // change BinOpResTy to a vector of ints.
12558   if (isVector(ResultTy, Context.ShortTy))
12559     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12560 
12561   if (IsCompAssign)
12562     return new (Context) CompoundAssignOperator(
12563         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12564         OpLoc, FPFeatures);
12565 
12566   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12567   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12568                                           VK, OK, OpLoc, FPFeatures);
12569   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12570 }
12571 
12572 static std::pair<ExprResult, ExprResult>
12573 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12574                            Expr *RHSExpr) {
12575   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12576   if (!S.getLangOpts().CPlusPlus) {
12577     // C cannot handle TypoExpr nodes on either side of a binop because it
12578     // doesn't handle dependent types properly, so make sure any TypoExprs have
12579     // been dealt with before checking the operands.
12580     LHS = S.CorrectDelayedTyposInExpr(LHS);
12581     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12582       if (Opc != BO_Assign)
12583         return ExprResult(E);
12584       // Avoid correcting the RHS to the same Expr as the LHS.
12585       Decl *D = getDeclFromExpr(E);
12586       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12587     });
12588   }
12589   return std::make_pair(LHS, RHS);
12590 }
12591 
12592 /// Returns true if conversion between vectors of halfs and vectors of floats
12593 /// is needed.
12594 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12595                                      QualType SrcType) {
12596   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12597          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12598          isVector(SrcType, Ctx.HalfTy);
12599 }
12600 
12601 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12602 /// operator @p Opc at location @c TokLoc. This routine only supports
12603 /// built-in operations; ActOnBinOp handles overloaded operators.
12604 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12605                                     BinaryOperatorKind Opc,
12606                                     Expr *LHSExpr, Expr *RHSExpr) {
12607   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12608     // The syntax only allows initializer lists on the RHS of assignment,
12609     // so we don't need to worry about accepting invalid code for
12610     // non-assignment operators.
12611     // C++11 5.17p9:
12612     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12613     //   of x = {} is x = T().
12614     InitializationKind Kind = InitializationKind::CreateDirectList(
12615         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12616     InitializedEntity Entity =
12617         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12618     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12619     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12620     if (Init.isInvalid())
12621       return Init;
12622     RHSExpr = Init.get();
12623   }
12624 
12625   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12626   QualType ResultTy;     // Result type of the binary operator.
12627   // The following two variables are used for compound assignment operators
12628   QualType CompLHSTy;    // Type of LHS after promotions for computation
12629   QualType CompResultTy; // Type of computation result
12630   ExprValueKind VK = VK_RValue;
12631   ExprObjectKind OK = OK_Ordinary;
12632   bool ConvertHalfVec = false;
12633 
12634   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12635   if (!LHS.isUsable() || !RHS.isUsable())
12636     return ExprError();
12637 
12638   if (getLangOpts().OpenCL) {
12639     QualType LHSTy = LHSExpr->getType();
12640     QualType RHSTy = RHSExpr->getType();
12641     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12642     // the ATOMIC_VAR_INIT macro.
12643     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12644       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12645       if (BO_Assign == Opc)
12646         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12647       else
12648         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12649       return ExprError();
12650     }
12651 
12652     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12653     // only with a builtin functions and therefore should be disallowed here.
12654     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12655         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12656         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12657         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12658       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12659       return ExprError();
12660     }
12661   }
12662 
12663   // Diagnose operations on the unsupported types for OpenMP device compilation.
12664   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12665     if (Opc != BO_Assign && Opc != BO_Comma) {
12666       checkOpenMPDeviceExpr(LHSExpr);
12667       checkOpenMPDeviceExpr(RHSExpr);
12668     }
12669   }
12670 
12671   switch (Opc) {
12672   case BO_Assign:
12673     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12674     if (getLangOpts().CPlusPlus &&
12675         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12676       VK = LHS.get()->getValueKind();
12677       OK = LHS.get()->getObjectKind();
12678     }
12679     if (!ResultTy.isNull()) {
12680       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12681       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12682 
12683       // Avoid copying a block to the heap if the block is assigned to a local
12684       // auto variable that is declared in the same scope as the block. This
12685       // optimization is unsafe if the local variable is declared in an outer
12686       // scope. For example:
12687       //
12688       // BlockTy b;
12689       // {
12690       //   b = ^{...};
12691       // }
12692       // // It is unsafe to invoke the block here if it wasn't copied to the
12693       // // heap.
12694       // b();
12695 
12696       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12697         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12698           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12699             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12700               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12701     }
12702     RecordModifiableNonNullParam(*this, LHS.get());
12703     break;
12704   case BO_PtrMemD:
12705   case BO_PtrMemI:
12706     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12707                                             Opc == BO_PtrMemI);
12708     break;
12709   case BO_Mul:
12710   case BO_Div:
12711     ConvertHalfVec = true;
12712     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12713                                            Opc == BO_Div);
12714     break;
12715   case BO_Rem:
12716     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12717     break;
12718   case BO_Add:
12719     ConvertHalfVec = true;
12720     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12721     break;
12722   case BO_Sub:
12723     ConvertHalfVec = true;
12724     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12725     break;
12726   case BO_Shl:
12727   case BO_Shr:
12728     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12729     break;
12730   case BO_LE:
12731   case BO_LT:
12732   case BO_GE:
12733   case BO_GT:
12734     ConvertHalfVec = true;
12735     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12736     break;
12737   case BO_EQ:
12738   case BO_NE:
12739     ConvertHalfVec = true;
12740     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12741     break;
12742   case BO_Cmp:
12743     ConvertHalfVec = true;
12744     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12745     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12746     break;
12747   case BO_And:
12748     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12749     LLVM_FALLTHROUGH;
12750   case BO_Xor:
12751   case BO_Or:
12752     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12753     break;
12754   case BO_LAnd:
12755   case BO_LOr:
12756     ConvertHalfVec = true;
12757     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12758     break;
12759   case BO_MulAssign:
12760   case BO_DivAssign:
12761     ConvertHalfVec = true;
12762     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12763                                                Opc == BO_DivAssign);
12764     CompLHSTy = CompResultTy;
12765     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12766       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12767     break;
12768   case BO_RemAssign:
12769     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12770     CompLHSTy = CompResultTy;
12771     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12772       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12773     break;
12774   case BO_AddAssign:
12775     ConvertHalfVec = true;
12776     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12777     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12778       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12779     break;
12780   case BO_SubAssign:
12781     ConvertHalfVec = true;
12782     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12783     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12784       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12785     break;
12786   case BO_ShlAssign:
12787   case BO_ShrAssign:
12788     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12789     CompLHSTy = CompResultTy;
12790     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12791       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12792     break;
12793   case BO_AndAssign:
12794   case BO_OrAssign: // fallthrough
12795     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12796     LLVM_FALLTHROUGH;
12797   case BO_XorAssign:
12798     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12799     CompLHSTy = CompResultTy;
12800     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12801       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12802     break;
12803   case BO_Comma:
12804     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12805     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12806       VK = RHS.get()->getValueKind();
12807       OK = RHS.get()->getObjectKind();
12808     }
12809     break;
12810   }
12811   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12812     return ExprError();
12813 
12814   // Some of the binary operations require promoting operands of half vector to
12815   // float vectors and truncating the result back to half vector. For now, we do
12816   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12817   // arm64).
12818   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12819          isVector(LHS.get()->getType(), Context.HalfTy) &&
12820          "both sides are half vectors or neither sides are");
12821   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12822                                             LHS.get()->getType());
12823 
12824   // Check for array bounds violations for both sides of the BinaryOperator
12825   CheckArrayAccess(LHS.get());
12826   CheckArrayAccess(RHS.get());
12827 
12828   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12829     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12830                                                  &Context.Idents.get("object_setClass"),
12831                                                  SourceLocation(), LookupOrdinaryName);
12832     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12833       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12834       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12835           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12836                                         "object_setClass(")
12837           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12838                                           ",")
12839           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12840     }
12841     else
12842       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12843   }
12844   else if (const ObjCIvarRefExpr *OIRE =
12845            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12846     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12847 
12848   // Opc is not a compound assignment if CompResultTy is null.
12849   if (CompResultTy.isNull()) {
12850     if (ConvertHalfVec)
12851       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12852                                  OpLoc, FPFeatures);
12853     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12854                                         OK, OpLoc, FPFeatures);
12855   }
12856 
12857   // Handle compound assignments.
12858   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12859       OK_ObjCProperty) {
12860     VK = VK_LValue;
12861     OK = LHS.get()->getObjectKind();
12862   }
12863 
12864   if (ConvertHalfVec)
12865     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12866                                OpLoc, FPFeatures);
12867 
12868   return new (Context) CompoundAssignOperator(
12869       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12870       OpLoc, FPFeatures);
12871 }
12872 
12873 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12874 /// operators are mixed in a way that suggests that the programmer forgot that
12875 /// comparison operators have higher precedence. The most typical example of
12876 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12877 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12878                                       SourceLocation OpLoc, Expr *LHSExpr,
12879                                       Expr *RHSExpr) {
12880   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12881   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12882 
12883   // Check that one of the sides is a comparison operator and the other isn't.
12884   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12885   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12886   if (isLeftComp == isRightComp)
12887     return;
12888 
12889   // Bitwise operations are sometimes used as eager logical ops.
12890   // Don't diagnose this.
12891   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12892   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12893   if (isLeftBitwise || isRightBitwise)
12894     return;
12895 
12896   SourceRange DiagRange = isLeftComp
12897                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12898                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12899   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12900   SourceRange ParensRange =
12901       isLeftComp
12902           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12903           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12904 
12905   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12906     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12907   SuggestParentheses(Self, OpLoc,
12908     Self.PDiag(diag::note_precedence_silence) << OpStr,
12909     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12910   SuggestParentheses(Self, OpLoc,
12911     Self.PDiag(diag::note_precedence_bitwise_first)
12912       << BinaryOperator::getOpcodeStr(Opc),
12913     ParensRange);
12914 }
12915 
12916 /// It accepts a '&&' expr that is inside a '||' one.
12917 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12918 /// in parentheses.
12919 static void
12920 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12921                                        BinaryOperator *Bop) {
12922   assert(Bop->getOpcode() == BO_LAnd);
12923   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12924       << Bop->getSourceRange() << OpLoc;
12925   SuggestParentheses(Self, Bop->getOperatorLoc(),
12926     Self.PDiag(diag::note_precedence_silence)
12927       << Bop->getOpcodeStr(),
12928     Bop->getSourceRange());
12929 }
12930 
12931 /// Returns true if the given expression can be evaluated as a constant
12932 /// 'true'.
12933 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12934   bool Res;
12935   return !E->isValueDependent() &&
12936          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12937 }
12938 
12939 /// Returns true if the given expression can be evaluated as a constant
12940 /// 'false'.
12941 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12942   bool Res;
12943   return !E->isValueDependent() &&
12944          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12945 }
12946 
12947 /// Look for '&&' in the left hand of a '||' expr.
12948 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12949                                              Expr *LHSExpr, Expr *RHSExpr) {
12950   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12951     if (Bop->getOpcode() == BO_LAnd) {
12952       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12953       if (EvaluatesAsFalse(S, RHSExpr))
12954         return;
12955       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12956       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12957         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12958     } else if (Bop->getOpcode() == BO_LOr) {
12959       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12960         // If it's "a || b && 1 || c" we didn't warn earlier for
12961         // "a || b && 1", but warn now.
12962         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12963           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12964       }
12965     }
12966   }
12967 }
12968 
12969 /// Look for '&&' in the right hand of a '||' expr.
12970 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12971                                              Expr *LHSExpr, Expr *RHSExpr) {
12972   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12973     if (Bop->getOpcode() == BO_LAnd) {
12974       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12975       if (EvaluatesAsFalse(S, LHSExpr))
12976         return;
12977       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12978       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12979         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12980     }
12981   }
12982 }
12983 
12984 /// Look for bitwise op in the left or right hand of a bitwise op with
12985 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12986 /// the '&' expression in parentheses.
12987 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12988                                          SourceLocation OpLoc, Expr *SubExpr) {
12989   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12990     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12991       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12992         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12993         << Bop->getSourceRange() << OpLoc;
12994       SuggestParentheses(S, Bop->getOperatorLoc(),
12995         S.PDiag(diag::note_precedence_silence)
12996           << Bop->getOpcodeStr(),
12997         Bop->getSourceRange());
12998     }
12999   }
13000 }
13001 
13002 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13003                                     Expr *SubExpr, StringRef Shift) {
13004   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13005     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13006       StringRef Op = Bop->getOpcodeStr();
13007       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13008           << Bop->getSourceRange() << OpLoc << Shift << Op;
13009       SuggestParentheses(S, Bop->getOperatorLoc(),
13010           S.PDiag(diag::note_precedence_silence) << Op,
13011           Bop->getSourceRange());
13012     }
13013   }
13014 }
13015 
13016 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13017                                  Expr *LHSExpr, Expr *RHSExpr) {
13018   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13019   if (!OCE)
13020     return;
13021 
13022   FunctionDecl *FD = OCE->getDirectCallee();
13023   if (!FD || !FD->isOverloadedOperator())
13024     return;
13025 
13026   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13027   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13028     return;
13029 
13030   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13031       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13032       << (Kind == OO_LessLess);
13033   SuggestParentheses(S, OCE->getOperatorLoc(),
13034                      S.PDiag(diag::note_precedence_silence)
13035                          << (Kind == OO_LessLess ? "<<" : ">>"),
13036                      OCE->getSourceRange());
13037   SuggestParentheses(
13038       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13039       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13040 }
13041 
13042 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13043 /// precedence.
13044 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13045                                     SourceLocation OpLoc, Expr *LHSExpr,
13046                                     Expr *RHSExpr){
13047   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13048   if (BinaryOperator::isBitwiseOp(Opc))
13049     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13050 
13051   // Diagnose "arg1 & arg2 | arg3"
13052   if ((Opc == BO_Or || Opc == BO_Xor) &&
13053       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13054     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13055     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13056   }
13057 
13058   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13059   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13060   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13061     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13062     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13063   }
13064 
13065   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13066       || Opc == BO_Shr) {
13067     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13068     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13069     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13070   }
13071 
13072   // Warn on overloaded shift operators and comparisons, such as:
13073   // cout << 5 == 4;
13074   if (BinaryOperator::isComparisonOp(Opc))
13075     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13076 }
13077 
13078 // Binary Operators.  'Tok' is the token for the operator.
13079 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13080                             tok::TokenKind Kind,
13081                             Expr *LHSExpr, Expr *RHSExpr) {
13082   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13083   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13084   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13085 
13086   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13087   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13088 
13089   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13090 }
13091 
13092 /// Build an overloaded binary operator expression in the given scope.
13093 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13094                                        BinaryOperatorKind Opc,
13095                                        Expr *LHS, Expr *RHS) {
13096   switch (Opc) {
13097   case BO_Assign:
13098   case BO_DivAssign:
13099   case BO_RemAssign:
13100   case BO_SubAssign:
13101   case BO_AndAssign:
13102   case BO_OrAssign:
13103   case BO_XorAssign:
13104     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13105     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13106     break;
13107   default:
13108     break;
13109   }
13110 
13111   // Find all of the overloaded operators visible from this
13112   // point. We perform both an operator-name lookup from the local
13113   // scope and an argument-dependent lookup based on the types of
13114   // the arguments.
13115   UnresolvedSet<16> Functions;
13116   OverloadedOperatorKind OverOp
13117     = BinaryOperator::getOverloadedOperator(Opc);
13118   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13119     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13120                                    RHS->getType(), Functions);
13121 
13122   // Build the (potentially-overloaded, potentially-dependent)
13123   // binary operation.
13124   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13125 }
13126 
13127 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13128                             BinaryOperatorKind Opc,
13129                             Expr *LHSExpr, Expr *RHSExpr) {
13130   ExprResult LHS, RHS;
13131   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13132   if (!LHS.isUsable() || !RHS.isUsable())
13133     return ExprError();
13134   LHSExpr = LHS.get();
13135   RHSExpr = RHS.get();
13136 
13137   // We want to end up calling one of checkPseudoObjectAssignment
13138   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13139   // both expressions are overloadable or either is type-dependent),
13140   // or CreateBuiltinBinOp (in any other case).  We also want to get
13141   // any placeholder types out of the way.
13142 
13143   // Handle pseudo-objects in the LHS.
13144   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13145     // Assignments with a pseudo-object l-value need special analysis.
13146     if (pty->getKind() == BuiltinType::PseudoObject &&
13147         BinaryOperator::isAssignmentOp(Opc))
13148       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13149 
13150     // Don't resolve overloads if the other type is overloadable.
13151     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13152       // We can't actually test that if we still have a placeholder,
13153       // though.  Fortunately, none of the exceptions we see in that
13154       // code below are valid when the LHS is an overload set.  Note
13155       // that an overload set can be dependently-typed, but it never
13156       // instantiates to having an overloadable type.
13157       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13158       if (resolvedRHS.isInvalid()) return ExprError();
13159       RHSExpr = resolvedRHS.get();
13160 
13161       if (RHSExpr->isTypeDependent() ||
13162           RHSExpr->getType()->isOverloadableType())
13163         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13164     }
13165 
13166     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13167     // template, diagnose the missing 'template' keyword instead of diagnosing
13168     // an invalid use of a bound member function.
13169     //
13170     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13171     // to C++1z [over.over]/1.4, but we already checked for that case above.
13172     if (Opc == BO_LT && inTemplateInstantiation() &&
13173         (pty->getKind() == BuiltinType::BoundMember ||
13174          pty->getKind() == BuiltinType::Overload)) {
13175       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13176       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13177           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13178             return isa<FunctionTemplateDecl>(ND);
13179           })) {
13180         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13181                                 : OE->getNameLoc(),
13182              diag::err_template_kw_missing)
13183           << OE->getName().getAsString() << "";
13184         return ExprError();
13185       }
13186     }
13187 
13188     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13189     if (LHS.isInvalid()) return ExprError();
13190     LHSExpr = LHS.get();
13191   }
13192 
13193   // Handle pseudo-objects in the RHS.
13194   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13195     // An overload in the RHS can potentially be resolved by the type
13196     // being assigned to.
13197     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13198       if (getLangOpts().CPlusPlus &&
13199           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13200            LHSExpr->getType()->isOverloadableType()))
13201         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13202 
13203       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13204     }
13205 
13206     // Don't resolve overloads if the other type is overloadable.
13207     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13208         LHSExpr->getType()->isOverloadableType())
13209       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13210 
13211     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13212     if (!resolvedRHS.isUsable()) return ExprError();
13213     RHSExpr = resolvedRHS.get();
13214   }
13215 
13216   if (getLangOpts().CPlusPlus) {
13217     // If either expression is type-dependent, always build an
13218     // overloaded op.
13219     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13220       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13221 
13222     // Otherwise, build an overloaded op if either expression has an
13223     // overloadable type.
13224     if (LHSExpr->getType()->isOverloadableType() ||
13225         RHSExpr->getType()->isOverloadableType())
13226       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13227   }
13228 
13229   // Build a built-in binary operation.
13230   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13231 }
13232 
13233 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13234   if (T.isNull() || T->isDependentType())
13235     return false;
13236 
13237   if (!T->isPromotableIntegerType())
13238     return true;
13239 
13240   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13241 }
13242 
13243 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13244                                       UnaryOperatorKind Opc,
13245                                       Expr *InputExpr) {
13246   ExprResult Input = InputExpr;
13247   ExprValueKind VK = VK_RValue;
13248   ExprObjectKind OK = OK_Ordinary;
13249   QualType resultType;
13250   bool CanOverflow = false;
13251 
13252   bool ConvertHalfVec = false;
13253   if (getLangOpts().OpenCL) {
13254     QualType Ty = InputExpr->getType();
13255     // The only legal unary operation for atomics is '&'.
13256     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13257     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13258     // only with a builtin functions and therefore should be disallowed here.
13259         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13260         || Ty->isBlockPointerType())) {
13261       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13262                        << InputExpr->getType()
13263                        << Input.get()->getSourceRange());
13264     }
13265   }
13266   // Diagnose operations on the unsupported types for OpenMP device compilation.
13267   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13268     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13269         UnaryOperator::isArithmeticOp(Opc))
13270       checkOpenMPDeviceExpr(InputExpr);
13271   }
13272 
13273   switch (Opc) {
13274   case UO_PreInc:
13275   case UO_PreDec:
13276   case UO_PostInc:
13277   case UO_PostDec:
13278     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13279                                                 OpLoc,
13280                                                 Opc == UO_PreInc ||
13281                                                 Opc == UO_PostInc,
13282                                                 Opc == UO_PreInc ||
13283                                                 Opc == UO_PreDec);
13284     CanOverflow = isOverflowingIntegerType(Context, resultType);
13285     break;
13286   case UO_AddrOf:
13287     resultType = CheckAddressOfOperand(Input, OpLoc);
13288     CheckAddressOfNoDeref(InputExpr);
13289     RecordModifiableNonNullParam(*this, InputExpr);
13290     break;
13291   case UO_Deref: {
13292     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13293     if (Input.isInvalid()) return ExprError();
13294     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13295     break;
13296   }
13297   case UO_Plus:
13298   case UO_Minus:
13299     CanOverflow = Opc == UO_Minus &&
13300                   isOverflowingIntegerType(Context, Input.get()->getType());
13301     Input = UsualUnaryConversions(Input.get());
13302     if (Input.isInvalid()) return ExprError();
13303     // Unary plus and minus require promoting an operand of half vector to a
13304     // float vector and truncating the result back to a half vector. For now, we
13305     // do this only when HalfArgsAndReturns is set (that is, when the target is
13306     // arm or arm64).
13307     ConvertHalfVec =
13308         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13309 
13310     // If the operand is a half vector, promote it to a float vector.
13311     if (ConvertHalfVec)
13312       Input = convertVector(Input.get(), Context.FloatTy, *this);
13313     resultType = Input.get()->getType();
13314     if (resultType->isDependentType())
13315       break;
13316     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13317       break;
13318     else if (resultType->isVectorType() &&
13319              // The z vector extensions don't allow + or - with bool vectors.
13320              (!Context.getLangOpts().ZVector ||
13321               resultType->getAs<VectorType>()->getVectorKind() !=
13322               VectorType::AltiVecBool))
13323       break;
13324     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13325              Opc == UO_Plus &&
13326              resultType->isPointerType())
13327       break;
13328 
13329     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13330       << resultType << Input.get()->getSourceRange());
13331 
13332   case UO_Not: // bitwise complement
13333     Input = UsualUnaryConversions(Input.get());
13334     if (Input.isInvalid())
13335       return ExprError();
13336     resultType = Input.get()->getType();
13337 
13338     if (resultType->isDependentType())
13339       break;
13340     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13341     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13342       // C99 does not support '~' for complex conjugation.
13343       Diag(OpLoc, diag::ext_integer_complement_complex)
13344           << resultType << Input.get()->getSourceRange();
13345     else if (resultType->hasIntegerRepresentation())
13346       break;
13347     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13348       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13349       // on vector float types.
13350       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13351       if (!T->isIntegerType())
13352         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13353                           << resultType << Input.get()->getSourceRange());
13354     } else {
13355       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13356                        << resultType << Input.get()->getSourceRange());
13357     }
13358     break;
13359 
13360   case UO_LNot: // logical negation
13361     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13362     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13363     if (Input.isInvalid()) return ExprError();
13364     resultType = Input.get()->getType();
13365 
13366     // Though we still have to promote half FP to float...
13367     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13368       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13369       resultType = Context.FloatTy;
13370     }
13371 
13372     if (resultType->isDependentType())
13373       break;
13374     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13375       // C99 6.5.3.3p1: ok, fallthrough;
13376       if (Context.getLangOpts().CPlusPlus) {
13377         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13378         // operand contextually converted to bool.
13379         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13380                                   ScalarTypeToBooleanCastKind(resultType));
13381       } else if (Context.getLangOpts().OpenCL &&
13382                  Context.getLangOpts().OpenCLVersion < 120) {
13383         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13384         // operate on scalar float types.
13385         if (!resultType->isIntegerType() && !resultType->isPointerType())
13386           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13387                            << resultType << Input.get()->getSourceRange());
13388       }
13389     } else if (resultType->isExtVectorType()) {
13390       if (Context.getLangOpts().OpenCL &&
13391           Context.getLangOpts().OpenCLVersion < 120 &&
13392           !Context.getLangOpts().OpenCLCPlusPlus) {
13393         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13394         // operate on vector float types.
13395         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13396         if (!T->isIntegerType())
13397           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13398                            << resultType << Input.get()->getSourceRange());
13399       }
13400       // Vector logical not returns the signed variant of the operand type.
13401       resultType = GetSignedVectorType(resultType);
13402       break;
13403     } else {
13404       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13405       //        type in C++. We should allow that here too.
13406       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13407         << resultType << Input.get()->getSourceRange());
13408     }
13409 
13410     // LNot always has type int. C99 6.5.3.3p5.
13411     // In C++, it's bool. C++ 5.3.1p8
13412     resultType = Context.getLogicalOperationType();
13413     break;
13414   case UO_Real:
13415   case UO_Imag:
13416     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13417     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13418     // complex l-values to ordinary l-values and all other values to r-values.
13419     if (Input.isInvalid()) return ExprError();
13420     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13421       if (Input.get()->getValueKind() != VK_RValue &&
13422           Input.get()->getObjectKind() == OK_Ordinary)
13423         VK = Input.get()->getValueKind();
13424     } else if (!getLangOpts().CPlusPlus) {
13425       // In C, a volatile scalar is read by __imag. In C++, it is not.
13426       Input = DefaultLvalueConversion(Input.get());
13427     }
13428     break;
13429   case UO_Extension:
13430     resultType = Input.get()->getType();
13431     VK = Input.get()->getValueKind();
13432     OK = Input.get()->getObjectKind();
13433     break;
13434   case UO_Coawait:
13435     // It's unnecessary to represent the pass-through operator co_await in the
13436     // AST; just return the input expression instead.
13437     assert(!Input.get()->getType()->isDependentType() &&
13438                    "the co_await expression must be non-dependant before "
13439                    "building operator co_await");
13440     return Input;
13441   }
13442   if (resultType.isNull() || Input.isInvalid())
13443     return ExprError();
13444 
13445   // Check for array bounds violations in the operand of the UnaryOperator,
13446   // except for the '*' and '&' operators that have to be handled specially
13447   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13448   // that are explicitly defined as valid by the standard).
13449   if (Opc != UO_AddrOf && Opc != UO_Deref)
13450     CheckArrayAccess(Input.get());
13451 
13452   auto *UO = new (Context)
13453       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13454 
13455   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13456       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13457     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13458 
13459   // Convert the result back to a half vector.
13460   if (ConvertHalfVec)
13461     return convertVector(UO, Context.HalfTy, *this);
13462   return UO;
13463 }
13464 
13465 /// Determine whether the given expression is a qualified member
13466 /// access expression, of a form that could be turned into a pointer to member
13467 /// with the address-of operator.
13468 bool Sema::isQualifiedMemberAccess(Expr *E) {
13469   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13470     if (!DRE->getQualifier())
13471       return false;
13472 
13473     ValueDecl *VD = DRE->getDecl();
13474     if (!VD->isCXXClassMember())
13475       return false;
13476 
13477     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13478       return true;
13479     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13480       return Method->isInstance();
13481 
13482     return false;
13483   }
13484 
13485   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13486     if (!ULE->getQualifier())
13487       return false;
13488 
13489     for (NamedDecl *D : ULE->decls()) {
13490       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13491         if (Method->isInstance())
13492           return true;
13493       } else {
13494         // Overload set does not contain methods.
13495         break;
13496       }
13497     }
13498 
13499     return false;
13500   }
13501 
13502   return false;
13503 }
13504 
13505 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13506                               UnaryOperatorKind Opc, Expr *Input) {
13507   // First things first: handle placeholders so that the
13508   // overloaded-operator check considers the right type.
13509   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13510     // Increment and decrement of pseudo-object references.
13511     if (pty->getKind() == BuiltinType::PseudoObject &&
13512         UnaryOperator::isIncrementDecrementOp(Opc))
13513       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13514 
13515     // extension is always a builtin operator.
13516     if (Opc == UO_Extension)
13517       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13518 
13519     // & gets special logic for several kinds of placeholder.
13520     // The builtin code knows what to do.
13521     if (Opc == UO_AddrOf &&
13522         (pty->getKind() == BuiltinType::Overload ||
13523          pty->getKind() == BuiltinType::UnknownAny ||
13524          pty->getKind() == BuiltinType::BoundMember))
13525       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13526 
13527     // Anything else needs to be handled now.
13528     ExprResult Result = CheckPlaceholderExpr(Input);
13529     if (Result.isInvalid()) return ExprError();
13530     Input = Result.get();
13531   }
13532 
13533   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13534       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13535       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13536     // Find all of the overloaded operators visible from this
13537     // point. We perform both an operator-name lookup from the local
13538     // scope and an argument-dependent lookup based on the types of
13539     // the arguments.
13540     UnresolvedSet<16> Functions;
13541     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13542     if (S && OverOp != OO_None)
13543       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13544                                    Functions);
13545 
13546     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13547   }
13548 
13549   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13550 }
13551 
13552 // Unary Operators.  'Tok' is the token for the operator.
13553 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13554                               tok::TokenKind Op, Expr *Input) {
13555   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13556 }
13557 
13558 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13559 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13560                                 LabelDecl *TheDecl) {
13561   TheDecl->markUsed(Context);
13562   // Create the AST node.  The address of a label always has type 'void*'.
13563   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13564                                      Context.getPointerType(Context.VoidTy));
13565 }
13566 
13567 void Sema::ActOnStartStmtExpr() {
13568   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13569 }
13570 
13571 void Sema::ActOnStmtExprError() {
13572   // Note that function is also called by TreeTransform when leaving a
13573   // StmtExpr scope without rebuilding anything.
13574 
13575   DiscardCleanupsInEvaluationContext();
13576   PopExpressionEvaluationContext();
13577 }
13578 
13579 ExprResult
13580 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13581                     SourceLocation RPLoc) { // "({..})"
13582   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13583   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13584 
13585   if (hasAnyUnrecoverableErrorsInThisFunction())
13586     DiscardCleanupsInEvaluationContext();
13587   assert(!Cleanup.exprNeedsCleanups() &&
13588          "cleanups within StmtExpr not correctly bound!");
13589   PopExpressionEvaluationContext();
13590 
13591   // FIXME: there are a variety of strange constraints to enforce here, for
13592   // example, it is not possible to goto into a stmt expression apparently.
13593   // More semantic analysis is needed.
13594 
13595   // If there are sub-stmts in the compound stmt, take the type of the last one
13596   // as the type of the stmtexpr.
13597   QualType Ty = Context.VoidTy;
13598   bool StmtExprMayBindToTemp = false;
13599   if (!Compound->body_empty()) {
13600     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13601     if (const auto *LastStmt =
13602             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13603       if (const Expr *Value = LastStmt->getExprStmt()) {
13604         StmtExprMayBindToTemp = true;
13605         Ty = Value->getType();
13606       }
13607     }
13608   }
13609 
13610   // FIXME: Check that expression type is complete/non-abstract; statement
13611   // expressions are not lvalues.
13612   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13613   if (StmtExprMayBindToTemp)
13614     return MaybeBindToTemporary(ResStmtExpr);
13615   return ResStmtExpr;
13616 }
13617 
13618 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13619   if (ER.isInvalid())
13620     return ExprError();
13621 
13622   // Do function/array conversion on the last expression, but not
13623   // lvalue-to-rvalue.  However, initialize an unqualified type.
13624   ER = DefaultFunctionArrayConversion(ER.get());
13625   if (ER.isInvalid())
13626     return ExprError();
13627   Expr *E = ER.get();
13628 
13629   if (E->isTypeDependent())
13630     return E;
13631 
13632   // In ARC, if the final expression ends in a consume, splice
13633   // the consume out and bind it later.  In the alternate case
13634   // (when dealing with a retainable type), the result
13635   // initialization will create a produce.  In both cases the
13636   // result will be +1, and we'll need to balance that out with
13637   // a bind.
13638   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13639   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13640     return Cast->getSubExpr();
13641 
13642   // FIXME: Provide a better location for the initialization.
13643   return PerformCopyInitialization(
13644       InitializedEntity::InitializeStmtExprResult(
13645           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13646       SourceLocation(), E);
13647 }
13648 
13649 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13650                                       TypeSourceInfo *TInfo,
13651                                       ArrayRef<OffsetOfComponent> Components,
13652                                       SourceLocation RParenLoc) {
13653   QualType ArgTy = TInfo->getType();
13654   bool Dependent = ArgTy->isDependentType();
13655   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13656 
13657   // We must have at least one component that refers to the type, and the first
13658   // one is known to be a field designator.  Verify that the ArgTy represents
13659   // a struct/union/class.
13660   if (!Dependent && !ArgTy->isRecordType())
13661     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13662                        << ArgTy << TypeRange);
13663 
13664   // Type must be complete per C99 7.17p3 because a declaring a variable
13665   // with an incomplete type would be ill-formed.
13666   if (!Dependent
13667       && RequireCompleteType(BuiltinLoc, ArgTy,
13668                              diag::err_offsetof_incomplete_type, TypeRange))
13669     return ExprError();
13670 
13671   bool DidWarnAboutNonPOD = false;
13672   QualType CurrentType = ArgTy;
13673   SmallVector<OffsetOfNode, 4> Comps;
13674   SmallVector<Expr*, 4> Exprs;
13675   for (const OffsetOfComponent &OC : Components) {
13676     if (OC.isBrackets) {
13677       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13678       if (!CurrentType->isDependentType()) {
13679         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13680         if(!AT)
13681           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13682                            << CurrentType);
13683         CurrentType = AT->getElementType();
13684       } else
13685         CurrentType = Context.DependentTy;
13686 
13687       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13688       if (IdxRval.isInvalid())
13689         return ExprError();
13690       Expr *Idx = IdxRval.get();
13691 
13692       // The expression must be an integral expression.
13693       // FIXME: An integral constant expression?
13694       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13695           !Idx->getType()->isIntegerType())
13696         return ExprError(
13697             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13698             << Idx->getSourceRange());
13699 
13700       // Record this array index.
13701       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13702       Exprs.push_back(Idx);
13703       continue;
13704     }
13705 
13706     // Offset of a field.
13707     if (CurrentType->isDependentType()) {
13708       // We have the offset of a field, but we can't look into the dependent
13709       // type. Just record the identifier of the field.
13710       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13711       CurrentType = Context.DependentTy;
13712       continue;
13713     }
13714 
13715     // We need to have a complete type to look into.
13716     if (RequireCompleteType(OC.LocStart, CurrentType,
13717                             diag::err_offsetof_incomplete_type))
13718       return ExprError();
13719 
13720     // Look for the designated field.
13721     const RecordType *RC = CurrentType->getAs<RecordType>();
13722     if (!RC)
13723       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13724                        << CurrentType);
13725     RecordDecl *RD = RC->getDecl();
13726 
13727     // C++ [lib.support.types]p5:
13728     //   The macro offsetof accepts a restricted set of type arguments in this
13729     //   International Standard. type shall be a POD structure or a POD union
13730     //   (clause 9).
13731     // C++11 [support.types]p4:
13732     //   If type is not a standard-layout class (Clause 9), the results are
13733     //   undefined.
13734     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13735       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13736       unsigned DiagID =
13737         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13738                             : diag::ext_offsetof_non_pod_type;
13739 
13740       if (!IsSafe && !DidWarnAboutNonPOD &&
13741           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13742                               PDiag(DiagID)
13743                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13744                               << CurrentType))
13745         DidWarnAboutNonPOD = true;
13746     }
13747 
13748     // Look for the field.
13749     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13750     LookupQualifiedName(R, RD);
13751     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13752     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13753     if (!MemberDecl) {
13754       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13755         MemberDecl = IndirectMemberDecl->getAnonField();
13756     }
13757 
13758     if (!MemberDecl)
13759       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13760                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13761                                                               OC.LocEnd));
13762 
13763     // C99 7.17p3:
13764     //   (If the specified member is a bit-field, the behavior is undefined.)
13765     //
13766     // We diagnose this as an error.
13767     if (MemberDecl->isBitField()) {
13768       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13769         << MemberDecl->getDeclName()
13770         << SourceRange(BuiltinLoc, RParenLoc);
13771       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13772       return ExprError();
13773     }
13774 
13775     RecordDecl *Parent = MemberDecl->getParent();
13776     if (IndirectMemberDecl)
13777       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13778 
13779     // If the member was found in a base class, introduce OffsetOfNodes for
13780     // the base class indirections.
13781     CXXBasePaths Paths;
13782     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13783                       Paths)) {
13784       if (Paths.getDetectedVirtual()) {
13785         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13786           << MemberDecl->getDeclName()
13787           << SourceRange(BuiltinLoc, RParenLoc);
13788         return ExprError();
13789       }
13790 
13791       CXXBasePath &Path = Paths.front();
13792       for (const CXXBasePathElement &B : Path)
13793         Comps.push_back(OffsetOfNode(B.Base));
13794     }
13795 
13796     if (IndirectMemberDecl) {
13797       for (auto *FI : IndirectMemberDecl->chain()) {
13798         assert(isa<FieldDecl>(FI));
13799         Comps.push_back(OffsetOfNode(OC.LocStart,
13800                                      cast<FieldDecl>(FI), OC.LocEnd));
13801       }
13802     } else
13803       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13804 
13805     CurrentType = MemberDecl->getType().getNonReferenceType();
13806   }
13807 
13808   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13809                               Comps, Exprs, RParenLoc);
13810 }
13811 
13812 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13813                                       SourceLocation BuiltinLoc,
13814                                       SourceLocation TypeLoc,
13815                                       ParsedType ParsedArgTy,
13816                                       ArrayRef<OffsetOfComponent> Components,
13817                                       SourceLocation RParenLoc) {
13818 
13819   TypeSourceInfo *ArgTInfo;
13820   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13821   if (ArgTy.isNull())
13822     return ExprError();
13823 
13824   if (!ArgTInfo)
13825     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13826 
13827   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13828 }
13829 
13830 
13831 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13832                                  Expr *CondExpr,
13833                                  Expr *LHSExpr, Expr *RHSExpr,
13834                                  SourceLocation RPLoc) {
13835   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13836 
13837   ExprValueKind VK = VK_RValue;
13838   ExprObjectKind OK = OK_Ordinary;
13839   QualType resType;
13840   bool ValueDependent = false;
13841   bool CondIsTrue = false;
13842   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13843     resType = Context.DependentTy;
13844     ValueDependent = true;
13845   } else {
13846     // The conditional expression is required to be a constant expression.
13847     llvm::APSInt condEval(32);
13848     ExprResult CondICE
13849       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13850           diag::err_typecheck_choose_expr_requires_constant, false);
13851     if (CondICE.isInvalid())
13852       return ExprError();
13853     CondExpr = CondICE.get();
13854     CondIsTrue = condEval.getZExtValue();
13855 
13856     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13857     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13858 
13859     resType = ActiveExpr->getType();
13860     ValueDependent = ActiveExpr->isValueDependent();
13861     VK = ActiveExpr->getValueKind();
13862     OK = ActiveExpr->getObjectKind();
13863   }
13864 
13865   return new (Context)
13866       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13867                  CondIsTrue, resType->isDependentType(), ValueDependent);
13868 }
13869 
13870 //===----------------------------------------------------------------------===//
13871 // Clang Extensions.
13872 //===----------------------------------------------------------------------===//
13873 
13874 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13875 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13876   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13877 
13878   if (LangOpts.CPlusPlus) {
13879     Decl *ManglingContextDecl;
13880     if (MangleNumberingContext *MCtx =
13881             getCurrentMangleNumberContext(Block->getDeclContext(),
13882                                           ManglingContextDecl)) {
13883       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13884       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13885     }
13886   }
13887 
13888   PushBlockScope(CurScope, Block);
13889   CurContext->addDecl(Block);
13890   if (CurScope)
13891     PushDeclContext(CurScope, Block);
13892   else
13893     CurContext = Block;
13894 
13895   getCurBlock()->HasImplicitReturnType = true;
13896 
13897   // Enter a new evaluation context to insulate the block from any
13898   // cleanups from the enclosing full-expression.
13899   PushExpressionEvaluationContext(
13900       ExpressionEvaluationContext::PotentiallyEvaluated);
13901 }
13902 
13903 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13904                                Scope *CurScope) {
13905   assert(ParamInfo.getIdentifier() == nullptr &&
13906          "block-id should have no identifier!");
13907   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13908   BlockScopeInfo *CurBlock = getCurBlock();
13909 
13910   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13911   QualType T = Sig->getType();
13912 
13913   // FIXME: We should allow unexpanded parameter packs here, but that would,
13914   // in turn, make the block expression contain unexpanded parameter packs.
13915   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13916     // Drop the parameters.
13917     FunctionProtoType::ExtProtoInfo EPI;
13918     EPI.HasTrailingReturn = false;
13919     EPI.TypeQuals.addConst();
13920     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13921     Sig = Context.getTrivialTypeSourceInfo(T);
13922   }
13923 
13924   // GetTypeForDeclarator always produces a function type for a block
13925   // literal signature.  Furthermore, it is always a FunctionProtoType
13926   // unless the function was written with a typedef.
13927   assert(T->isFunctionType() &&
13928          "GetTypeForDeclarator made a non-function block signature");
13929 
13930   // Look for an explicit signature in that function type.
13931   FunctionProtoTypeLoc ExplicitSignature;
13932 
13933   if ((ExplicitSignature = Sig->getTypeLoc()
13934                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
13935 
13936     // Check whether that explicit signature was synthesized by
13937     // GetTypeForDeclarator.  If so, don't save that as part of the
13938     // written signature.
13939     if (ExplicitSignature.getLocalRangeBegin() ==
13940         ExplicitSignature.getLocalRangeEnd()) {
13941       // This would be much cheaper if we stored TypeLocs instead of
13942       // TypeSourceInfos.
13943       TypeLoc Result = ExplicitSignature.getReturnLoc();
13944       unsigned Size = Result.getFullDataSize();
13945       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13946       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13947 
13948       ExplicitSignature = FunctionProtoTypeLoc();
13949     }
13950   }
13951 
13952   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13953   CurBlock->FunctionType = T;
13954 
13955   const FunctionType *Fn = T->getAs<FunctionType>();
13956   QualType RetTy = Fn->getReturnType();
13957   bool isVariadic =
13958     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13959 
13960   CurBlock->TheDecl->setIsVariadic(isVariadic);
13961 
13962   // Context.DependentTy is used as a placeholder for a missing block
13963   // return type.  TODO:  what should we do with declarators like:
13964   //   ^ * { ... }
13965   // If the answer is "apply template argument deduction"....
13966   if (RetTy != Context.DependentTy) {
13967     CurBlock->ReturnType = RetTy;
13968     CurBlock->TheDecl->setBlockMissingReturnType(false);
13969     CurBlock->HasImplicitReturnType = false;
13970   }
13971 
13972   // Push block parameters from the declarator if we had them.
13973   SmallVector<ParmVarDecl*, 8> Params;
13974   if (ExplicitSignature) {
13975     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13976       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13977       if (Param->getIdentifier() == nullptr &&
13978           !Param->isImplicit() &&
13979           !Param->isInvalidDecl() &&
13980           !getLangOpts().CPlusPlus)
13981         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13982       Params.push_back(Param);
13983     }
13984 
13985   // Fake up parameter variables if we have a typedef, like
13986   //   ^ fntype { ... }
13987   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13988     for (const auto &I : Fn->param_types()) {
13989       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13990           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13991       Params.push_back(Param);
13992     }
13993   }
13994 
13995   // Set the parameters on the block decl.
13996   if (!Params.empty()) {
13997     CurBlock->TheDecl->setParams(Params);
13998     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13999                              /*CheckParameterNames=*/false);
14000   }
14001 
14002   // Finally we can process decl attributes.
14003   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14004 
14005   // Put the parameter variables in scope.
14006   for (auto AI : CurBlock->TheDecl->parameters()) {
14007     AI->setOwningFunction(CurBlock->TheDecl);
14008 
14009     // If this has an identifier, add it to the scope stack.
14010     if (AI->getIdentifier()) {
14011       CheckShadow(CurBlock->TheScope, AI);
14012 
14013       PushOnScopeChains(AI, CurBlock->TheScope);
14014     }
14015   }
14016 }
14017 
14018 /// ActOnBlockError - If there is an error parsing a block, this callback
14019 /// is invoked to pop the information about the block from the action impl.
14020 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14021   // Leave the expression-evaluation context.
14022   DiscardCleanupsInEvaluationContext();
14023   PopExpressionEvaluationContext();
14024 
14025   // Pop off CurBlock, handle nested blocks.
14026   PopDeclContext();
14027   PopFunctionScopeInfo();
14028 }
14029 
14030 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14031 /// literal was successfully completed.  ^(int x){...}
14032 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14033                                     Stmt *Body, Scope *CurScope) {
14034   // If blocks are disabled, emit an error.
14035   if (!LangOpts.Blocks)
14036     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14037 
14038   // Leave the expression-evaluation context.
14039   if (hasAnyUnrecoverableErrorsInThisFunction())
14040     DiscardCleanupsInEvaluationContext();
14041   assert(!Cleanup.exprNeedsCleanups() &&
14042          "cleanups within block not correctly bound!");
14043   PopExpressionEvaluationContext();
14044 
14045   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14046   BlockDecl *BD = BSI->TheDecl;
14047 
14048   if (BSI->HasImplicitReturnType)
14049     deduceClosureReturnType(*BSI);
14050 
14051   QualType RetTy = Context.VoidTy;
14052   if (!BSI->ReturnType.isNull())
14053     RetTy = BSI->ReturnType;
14054 
14055   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14056   QualType BlockTy;
14057 
14058   // If the user wrote a function type in some form, try to use that.
14059   if (!BSI->FunctionType.isNull()) {
14060     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
14061 
14062     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14063     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14064 
14065     // Turn protoless block types into nullary block types.
14066     if (isa<FunctionNoProtoType>(FTy)) {
14067       FunctionProtoType::ExtProtoInfo EPI;
14068       EPI.ExtInfo = Ext;
14069       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14070 
14071     // Otherwise, if we don't need to change anything about the function type,
14072     // preserve its sugar structure.
14073     } else if (FTy->getReturnType() == RetTy &&
14074                (!NoReturn || FTy->getNoReturnAttr())) {
14075       BlockTy = BSI->FunctionType;
14076 
14077     // Otherwise, make the minimal modifications to the function type.
14078     } else {
14079       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14080       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14081       EPI.TypeQuals = Qualifiers();
14082       EPI.ExtInfo = Ext;
14083       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14084     }
14085 
14086   // If we don't have a function type, just build one from nothing.
14087   } else {
14088     FunctionProtoType::ExtProtoInfo EPI;
14089     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14090     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14091   }
14092 
14093   DiagnoseUnusedParameters(BD->parameters());
14094   BlockTy = Context.getBlockPointerType(BlockTy);
14095 
14096   // If needed, diagnose invalid gotos and switches in the block.
14097   if (getCurFunction()->NeedsScopeChecking() &&
14098       !PP.isCodeCompletionEnabled())
14099     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14100 
14101   BD->setBody(cast<CompoundStmt>(Body));
14102 
14103   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14104     DiagnoseUnguardedAvailabilityViolations(BD);
14105 
14106   // Try to apply the named return value optimization. We have to check again
14107   // if we can do this, though, because blocks keep return statements around
14108   // to deduce an implicit return type.
14109   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14110       !BD->isDependentContext())
14111     computeNRVO(Body, BSI);
14112 
14113   PopDeclContext();
14114 
14115   // Pop the block scope now but keep it alive to the end of this function.
14116   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14117   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14118 
14119   // Set the captured variables on the block.
14120   SmallVector<BlockDecl::Capture, 4> Captures;
14121   for (Capture &Cap : BSI->Captures) {
14122     if (Cap.isInvalid() || Cap.isThisCapture())
14123       continue;
14124 
14125     VarDecl *Var = Cap.getVariable();
14126     Expr *CopyExpr = nullptr;
14127     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14128       if (const RecordType *Record =
14129               Cap.getCaptureType()->getAs<RecordType>()) {
14130         // The capture logic needs the destructor, so make sure we mark it.
14131         // Usually this is unnecessary because most local variables have
14132         // their destructors marked at declaration time, but parameters are
14133         // an exception because it's technically only the call site that
14134         // actually requires the destructor.
14135         if (isa<ParmVarDecl>(Var))
14136           FinalizeVarWithDestructor(Var, Record);
14137 
14138         // Enter a separate potentially-evaluated context while building block
14139         // initializers to isolate their cleanups from those of the block
14140         // itself.
14141         // FIXME: Is this appropriate even when the block itself occurs in an
14142         // unevaluated operand?
14143         EnterExpressionEvaluationContext EvalContext(
14144             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14145 
14146         SourceLocation Loc = Cap.getLocation();
14147 
14148         ExprResult Result = BuildDeclarationNameExpr(
14149             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14150 
14151         // According to the blocks spec, the capture of a variable from
14152         // the stack requires a const copy constructor.  This is not true
14153         // of the copy/move done to move a __block variable to the heap.
14154         if (!Result.isInvalid() &&
14155             !Result.get()->getType().isConstQualified()) {
14156           Result = ImpCastExprToType(Result.get(),
14157                                      Result.get()->getType().withConst(),
14158                                      CK_NoOp, VK_LValue);
14159         }
14160 
14161         if (!Result.isInvalid()) {
14162           Result = PerformCopyInitialization(
14163               InitializedEntity::InitializeBlock(Var->getLocation(),
14164                                                  Cap.getCaptureType(), false),
14165               Loc, Result.get());
14166         }
14167 
14168         // Build a full-expression copy expression if initialization
14169         // succeeded and used a non-trivial constructor.  Recover from
14170         // errors by pretending that the copy isn't necessary.
14171         if (!Result.isInvalid() &&
14172             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14173                 ->isTrivial()) {
14174           Result = MaybeCreateExprWithCleanups(Result);
14175           CopyExpr = Result.get();
14176         }
14177       }
14178     }
14179 
14180     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14181                               CopyExpr);
14182     Captures.push_back(NewCap);
14183   }
14184   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14185 
14186   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14187 
14188   // If the block isn't obviously global, i.e. it captures anything at
14189   // all, then we need to do a few things in the surrounding context:
14190   if (Result->getBlockDecl()->hasCaptures()) {
14191     // First, this expression has a new cleanup object.
14192     ExprCleanupObjects.push_back(Result->getBlockDecl());
14193     Cleanup.setExprNeedsCleanups(true);
14194 
14195     // It also gets a branch-protected scope if any of the captured
14196     // variables needs destruction.
14197     for (const auto &CI : Result->getBlockDecl()->captures()) {
14198       const VarDecl *var = CI.getVariable();
14199       if (var->getType().isDestructedType() != QualType::DK_none) {
14200         setFunctionHasBranchProtectedScope();
14201         break;
14202       }
14203     }
14204   }
14205 
14206   if (getCurFunction())
14207     getCurFunction()->addBlock(BD);
14208 
14209   return Result;
14210 }
14211 
14212 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14213                             SourceLocation RPLoc) {
14214   TypeSourceInfo *TInfo;
14215   GetTypeFromParser(Ty, &TInfo);
14216   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14217 }
14218 
14219 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14220                                 Expr *E, TypeSourceInfo *TInfo,
14221                                 SourceLocation RPLoc) {
14222   Expr *OrigExpr = E;
14223   bool IsMS = false;
14224 
14225   // CUDA device code does not support varargs.
14226   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14227     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14228       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14229       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14230         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14231     }
14232   }
14233 
14234   // NVPTX does not support va_arg expression.
14235   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14236       Context.getTargetInfo().getTriple().isNVPTX())
14237     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14238 
14239   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14240   // as Microsoft ABI on an actual Microsoft platform, where
14241   // __builtin_ms_va_list and __builtin_va_list are the same.)
14242   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14243       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14244     QualType MSVaListType = Context.getBuiltinMSVaListType();
14245     if (Context.hasSameType(MSVaListType, E->getType())) {
14246       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14247         return ExprError();
14248       IsMS = true;
14249     }
14250   }
14251 
14252   // Get the va_list type
14253   QualType VaListType = Context.getBuiltinVaListType();
14254   if (!IsMS) {
14255     if (VaListType->isArrayType()) {
14256       // Deal with implicit array decay; for example, on x86-64,
14257       // va_list is an array, but it's supposed to decay to
14258       // a pointer for va_arg.
14259       VaListType = Context.getArrayDecayedType(VaListType);
14260       // Make sure the input expression also decays appropriately.
14261       ExprResult Result = UsualUnaryConversions(E);
14262       if (Result.isInvalid())
14263         return ExprError();
14264       E = Result.get();
14265     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14266       // If va_list is a record type and we are compiling in C++ mode,
14267       // check the argument using reference binding.
14268       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14269           Context, Context.getLValueReferenceType(VaListType), false);
14270       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14271       if (Init.isInvalid())
14272         return ExprError();
14273       E = Init.getAs<Expr>();
14274     } else {
14275       // Otherwise, the va_list argument must be an l-value because
14276       // it is modified by va_arg.
14277       if (!E->isTypeDependent() &&
14278           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14279         return ExprError();
14280     }
14281   }
14282 
14283   if (!IsMS && !E->isTypeDependent() &&
14284       !Context.hasSameType(VaListType, E->getType()))
14285     return ExprError(
14286         Diag(E->getBeginLoc(),
14287              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14288         << OrigExpr->getType() << E->getSourceRange());
14289 
14290   if (!TInfo->getType()->isDependentType()) {
14291     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14292                             diag::err_second_parameter_to_va_arg_incomplete,
14293                             TInfo->getTypeLoc()))
14294       return ExprError();
14295 
14296     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14297                                TInfo->getType(),
14298                                diag::err_second_parameter_to_va_arg_abstract,
14299                                TInfo->getTypeLoc()))
14300       return ExprError();
14301 
14302     if (!TInfo->getType().isPODType(Context)) {
14303       Diag(TInfo->getTypeLoc().getBeginLoc(),
14304            TInfo->getType()->isObjCLifetimeType()
14305              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14306              : diag::warn_second_parameter_to_va_arg_not_pod)
14307         << TInfo->getType()
14308         << TInfo->getTypeLoc().getSourceRange();
14309     }
14310 
14311     // Check for va_arg where arguments of the given type will be promoted
14312     // (i.e. this va_arg is guaranteed to have undefined behavior).
14313     QualType PromoteType;
14314     if (TInfo->getType()->isPromotableIntegerType()) {
14315       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14316       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14317         PromoteType = QualType();
14318     }
14319     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14320       PromoteType = Context.DoubleTy;
14321     if (!PromoteType.isNull())
14322       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14323                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14324                           << TInfo->getType()
14325                           << PromoteType
14326                           << TInfo->getTypeLoc().getSourceRange());
14327   }
14328 
14329   QualType T = TInfo->getType().getNonLValueExprType(Context);
14330   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14331 }
14332 
14333 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14334   // The type of __null will be int or long, depending on the size of
14335   // pointers on the target.
14336   QualType Ty;
14337   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14338   if (pw == Context.getTargetInfo().getIntWidth())
14339     Ty = Context.IntTy;
14340   else if (pw == Context.getTargetInfo().getLongWidth())
14341     Ty = Context.LongTy;
14342   else if (pw == Context.getTargetInfo().getLongLongWidth())
14343     Ty = Context.LongLongTy;
14344   else {
14345     llvm_unreachable("I don't know size of pointer!");
14346   }
14347 
14348   return new (Context) GNUNullExpr(Ty, TokenLoc);
14349 }
14350 
14351 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14352                                     SourceLocation BuiltinLoc,
14353                                     SourceLocation RPLoc) {
14354   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14355 }
14356 
14357 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14358                                     SourceLocation BuiltinLoc,
14359                                     SourceLocation RPLoc,
14360                                     DeclContext *ParentContext) {
14361   return new (Context)
14362       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14363 }
14364 
14365 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14366                                               bool Diagnose) {
14367   if (!getLangOpts().ObjC)
14368     return false;
14369 
14370   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14371   if (!PT)
14372     return false;
14373 
14374   if (!PT->isObjCIdType()) {
14375     // Check if the destination is the 'NSString' interface.
14376     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14377     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14378       return false;
14379   }
14380 
14381   // Ignore any parens, implicit casts (should only be
14382   // array-to-pointer decays), and not-so-opaque values.  The last is
14383   // important for making this trigger for property assignments.
14384   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14385   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14386     if (OV->getSourceExpr())
14387       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14388 
14389   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14390   if (!SL || !SL->isAscii())
14391     return false;
14392   if (Diagnose) {
14393     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14394         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14395     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14396   }
14397   return true;
14398 }
14399 
14400 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14401                                               const Expr *SrcExpr) {
14402   if (!DstType->isFunctionPointerType() ||
14403       !SrcExpr->getType()->isFunctionType())
14404     return false;
14405 
14406   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14407   if (!DRE)
14408     return false;
14409 
14410   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14411   if (!FD)
14412     return false;
14413 
14414   return !S.checkAddressOfFunctionIsAvailable(FD,
14415                                               /*Complain=*/true,
14416                                               SrcExpr->getBeginLoc());
14417 }
14418 
14419 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14420                                     SourceLocation Loc,
14421                                     QualType DstType, QualType SrcType,
14422                                     Expr *SrcExpr, AssignmentAction Action,
14423                                     bool *Complained) {
14424   if (Complained)
14425     *Complained = false;
14426 
14427   // Decode the result (notice that AST's are still created for extensions).
14428   bool CheckInferredResultType = false;
14429   bool isInvalid = false;
14430   unsigned DiagKind = 0;
14431   FixItHint Hint;
14432   ConversionFixItGenerator ConvHints;
14433   bool MayHaveConvFixit = false;
14434   bool MayHaveFunctionDiff = false;
14435   const ObjCInterfaceDecl *IFace = nullptr;
14436   const ObjCProtocolDecl *PDecl = nullptr;
14437 
14438   switch (ConvTy) {
14439   case Compatible:
14440       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14441       return false;
14442 
14443   case PointerToInt:
14444     DiagKind = diag::ext_typecheck_convert_pointer_int;
14445     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14446     MayHaveConvFixit = true;
14447     break;
14448   case IntToPointer:
14449     DiagKind = diag::ext_typecheck_convert_int_pointer;
14450     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14451     MayHaveConvFixit = true;
14452     break;
14453   case IncompatiblePointer:
14454     if (Action == AA_Passing_CFAudited)
14455       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14456     else if (SrcType->isFunctionPointerType() &&
14457              DstType->isFunctionPointerType())
14458       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14459     else
14460       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14461 
14462     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14463       SrcType->isObjCObjectPointerType();
14464     if (Hint.isNull() && !CheckInferredResultType) {
14465       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14466     }
14467     else if (CheckInferredResultType) {
14468       SrcType = SrcType.getUnqualifiedType();
14469       DstType = DstType.getUnqualifiedType();
14470     }
14471     MayHaveConvFixit = true;
14472     break;
14473   case IncompatiblePointerSign:
14474     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14475     break;
14476   case FunctionVoidPointer:
14477     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14478     break;
14479   case IncompatiblePointerDiscardsQualifiers: {
14480     // Perform array-to-pointer decay if necessary.
14481     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14482 
14483     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14484     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14485     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14486       DiagKind = diag::err_typecheck_incompatible_address_space;
14487       break;
14488 
14489     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14490       DiagKind = diag::err_typecheck_incompatible_ownership;
14491       break;
14492     }
14493 
14494     llvm_unreachable("unknown error case for discarding qualifiers!");
14495     // fallthrough
14496   }
14497   case CompatiblePointerDiscardsQualifiers:
14498     // If the qualifiers lost were because we were applying the
14499     // (deprecated) C++ conversion from a string literal to a char*
14500     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14501     // Ideally, this check would be performed in
14502     // checkPointerTypesForAssignment. However, that would require a
14503     // bit of refactoring (so that the second argument is an
14504     // expression, rather than a type), which should be done as part
14505     // of a larger effort to fix checkPointerTypesForAssignment for
14506     // C++ semantics.
14507     if (getLangOpts().CPlusPlus &&
14508         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14509       return false;
14510     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14511     break;
14512   case IncompatibleNestedPointerQualifiers:
14513     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14514     break;
14515   case IncompatibleNestedPointerAddressSpaceMismatch:
14516     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14517     break;
14518   case IntToBlockPointer:
14519     DiagKind = diag::err_int_to_block_pointer;
14520     break;
14521   case IncompatibleBlockPointer:
14522     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14523     break;
14524   case IncompatibleObjCQualifiedId: {
14525     if (SrcType->isObjCQualifiedIdType()) {
14526       const ObjCObjectPointerType *srcOPT =
14527                 SrcType->getAs<ObjCObjectPointerType>();
14528       for (auto *srcProto : srcOPT->quals()) {
14529         PDecl = srcProto;
14530         break;
14531       }
14532       if (const ObjCInterfaceType *IFaceT =
14533             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14534         IFace = IFaceT->getDecl();
14535     }
14536     else if (DstType->isObjCQualifiedIdType()) {
14537       const ObjCObjectPointerType *dstOPT =
14538         DstType->getAs<ObjCObjectPointerType>();
14539       for (auto *dstProto : dstOPT->quals()) {
14540         PDecl = dstProto;
14541         break;
14542       }
14543       if (const ObjCInterfaceType *IFaceT =
14544             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14545         IFace = IFaceT->getDecl();
14546     }
14547     DiagKind = diag::warn_incompatible_qualified_id;
14548     break;
14549   }
14550   case IncompatibleVectors:
14551     DiagKind = diag::warn_incompatible_vectors;
14552     break;
14553   case IncompatibleObjCWeakRef:
14554     DiagKind = diag::err_arc_weak_unavailable_assign;
14555     break;
14556   case Incompatible:
14557     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14558       if (Complained)
14559         *Complained = true;
14560       return true;
14561     }
14562 
14563     DiagKind = diag::err_typecheck_convert_incompatible;
14564     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14565     MayHaveConvFixit = true;
14566     isInvalid = true;
14567     MayHaveFunctionDiff = true;
14568     break;
14569   }
14570 
14571   QualType FirstType, SecondType;
14572   switch (Action) {
14573   case AA_Assigning:
14574   case AA_Initializing:
14575     // The destination type comes first.
14576     FirstType = DstType;
14577     SecondType = SrcType;
14578     break;
14579 
14580   case AA_Returning:
14581   case AA_Passing:
14582   case AA_Passing_CFAudited:
14583   case AA_Converting:
14584   case AA_Sending:
14585   case AA_Casting:
14586     // The source type comes first.
14587     FirstType = SrcType;
14588     SecondType = DstType;
14589     break;
14590   }
14591 
14592   PartialDiagnostic FDiag = PDiag(DiagKind);
14593   if (Action == AA_Passing_CFAudited)
14594     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14595   else
14596     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14597 
14598   // If we can fix the conversion, suggest the FixIts.
14599   assert(ConvHints.isNull() || Hint.isNull());
14600   if (!ConvHints.isNull()) {
14601     for (FixItHint &H : ConvHints.Hints)
14602       FDiag << H;
14603   } else {
14604     FDiag << Hint;
14605   }
14606   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14607 
14608   if (MayHaveFunctionDiff)
14609     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14610 
14611   Diag(Loc, FDiag);
14612   if (DiagKind == diag::warn_incompatible_qualified_id &&
14613       PDecl && IFace && !IFace->hasDefinition())
14614       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14615         << IFace << PDecl;
14616 
14617   if (SecondType == Context.OverloadTy)
14618     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14619                               FirstType, /*TakingAddress=*/true);
14620 
14621   if (CheckInferredResultType)
14622     EmitRelatedResultTypeNote(SrcExpr);
14623 
14624   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14625     EmitRelatedResultTypeNoteForReturn(DstType);
14626 
14627   if (Complained)
14628     *Complained = true;
14629   return isInvalid;
14630 }
14631 
14632 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14633                                                  llvm::APSInt *Result) {
14634   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14635   public:
14636     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14637       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14638     }
14639   } Diagnoser;
14640 
14641   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14642 }
14643 
14644 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14645                                                  llvm::APSInt *Result,
14646                                                  unsigned DiagID,
14647                                                  bool AllowFold) {
14648   class IDDiagnoser : public VerifyICEDiagnoser {
14649     unsigned DiagID;
14650 
14651   public:
14652     IDDiagnoser(unsigned DiagID)
14653       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14654 
14655     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14656       S.Diag(Loc, DiagID) << SR;
14657     }
14658   } Diagnoser(DiagID);
14659 
14660   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14661 }
14662 
14663 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14664                                             SourceRange SR) {
14665   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14666 }
14667 
14668 ExprResult
14669 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14670                                       VerifyICEDiagnoser &Diagnoser,
14671                                       bool AllowFold) {
14672   SourceLocation DiagLoc = E->getBeginLoc();
14673 
14674   if (getLangOpts().CPlusPlus11) {
14675     // C++11 [expr.const]p5:
14676     //   If an expression of literal class type is used in a context where an
14677     //   integral constant expression is required, then that class type shall
14678     //   have a single non-explicit conversion function to an integral or
14679     //   unscoped enumeration type
14680     ExprResult Converted;
14681     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14682     public:
14683       CXX11ConvertDiagnoser(bool Silent)
14684           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14685                                 Silent, true) {}
14686 
14687       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14688                                            QualType T) override {
14689         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14690       }
14691 
14692       SemaDiagnosticBuilder diagnoseIncomplete(
14693           Sema &S, SourceLocation Loc, QualType T) override {
14694         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14695       }
14696 
14697       SemaDiagnosticBuilder diagnoseExplicitConv(
14698           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14699         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14700       }
14701 
14702       SemaDiagnosticBuilder noteExplicitConv(
14703           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14704         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14705                  << ConvTy->isEnumeralType() << ConvTy;
14706       }
14707 
14708       SemaDiagnosticBuilder diagnoseAmbiguous(
14709           Sema &S, SourceLocation Loc, QualType T) override {
14710         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14711       }
14712 
14713       SemaDiagnosticBuilder noteAmbiguous(
14714           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14715         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14716                  << ConvTy->isEnumeralType() << ConvTy;
14717       }
14718 
14719       SemaDiagnosticBuilder diagnoseConversion(
14720           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14721         llvm_unreachable("conversion functions are permitted");
14722       }
14723     } ConvertDiagnoser(Diagnoser.Suppress);
14724 
14725     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14726                                                     ConvertDiagnoser);
14727     if (Converted.isInvalid())
14728       return Converted;
14729     E = Converted.get();
14730     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14731       return ExprError();
14732   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14733     // An ICE must be of integral or unscoped enumeration type.
14734     if (!Diagnoser.Suppress)
14735       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14736     return ExprError();
14737   }
14738 
14739   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14740   // in the non-ICE case.
14741   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14742     if (Result)
14743       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14744     if (!isa<ConstantExpr>(E))
14745       E = ConstantExpr::Create(Context, E);
14746     return E;
14747   }
14748 
14749   Expr::EvalResult EvalResult;
14750   SmallVector<PartialDiagnosticAt, 8> Notes;
14751   EvalResult.Diag = &Notes;
14752 
14753   // Try to evaluate the expression, and produce diagnostics explaining why it's
14754   // not a constant expression as a side-effect.
14755   bool Folded =
14756       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14757       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14758 
14759   if (!isa<ConstantExpr>(E))
14760     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14761 
14762   // In C++11, we can rely on diagnostics being produced for any expression
14763   // which is not a constant expression. If no diagnostics were produced, then
14764   // this is a constant expression.
14765   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14766     if (Result)
14767       *Result = EvalResult.Val.getInt();
14768     return E;
14769   }
14770 
14771   // If our only note is the usual "invalid subexpression" note, just point
14772   // the caret at its location rather than producing an essentially
14773   // redundant note.
14774   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14775         diag::note_invalid_subexpr_in_const_expr) {
14776     DiagLoc = Notes[0].first;
14777     Notes.clear();
14778   }
14779 
14780   if (!Folded || !AllowFold) {
14781     if (!Diagnoser.Suppress) {
14782       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14783       for (const PartialDiagnosticAt &Note : Notes)
14784         Diag(Note.first, Note.second);
14785     }
14786 
14787     return ExprError();
14788   }
14789 
14790   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14791   for (const PartialDiagnosticAt &Note : Notes)
14792     Diag(Note.first, Note.second);
14793 
14794   if (Result)
14795     *Result = EvalResult.Val.getInt();
14796   return E;
14797 }
14798 
14799 namespace {
14800   // Handle the case where we conclude a expression which we speculatively
14801   // considered to be unevaluated is actually evaluated.
14802   class TransformToPE : public TreeTransform<TransformToPE> {
14803     typedef TreeTransform<TransformToPE> BaseTransform;
14804 
14805   public:
14806     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14807 
14808     // Make sure we redo semantic analysis
14809     bool AlwaysRebuild() { return true; }
14810     bool ReplacingOriginal() { return true; }
14811 
14812     // We need to special-case DeclRefExprs referring to FieldDecls which
14813     // are not part of a member pointer formation; normal TreeTransforming
14814     // doesn't catch this case because of the way we represent them in the AST.
14815     // FIXME: This is a bit ugly; is it really the best way to handle this
14816     // case?
14817     //
14818     // Error on DeclRefExprs referring to FieldDecls.
14819     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14820       if (isa<FieldDecl>(E->getDecl()) &&
14821           !SemaRef.isUnevaluatedContext())
14822         return SemaRef.Diag(E->getLocation(),
14823                             diag::err_invalid_non_static_member_use)
14824             << E->getDecl() << E->getSourceRange();
14825 
14826       return BaseTransform::TransformDeclRefExpr(E);
14827     }
14828 
14829     // Exception: filter out member pointer formation
14830     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14831       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14832         return E;
14833 
14834       return BaseTransform::TransformUnaryOperator(E);
14835     }
14836 
14837     // The body of a lambda-expression is in a separate expression evaluation
14838     // context so never needs to be transformed.
14839     // FIXME: Ideally we wouldn't transform the closure type either, and would
14840     // just recreate the capture expressions and lambda expression.
14841     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14842       return SkipLambdaBody(E, Body);
14843     }
14844   };
14845 }
14846 
14847 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14848   assert(isUnevaluatedContext() &&
14849          "Should only transform unevaluated expressions");
14850   ExprEvalContexts.back().Context =
14851       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14852   if (isUnevaluatedContext())
14853     return E;
14854   return TransformToPE(*this).TransformExpr(E);
14855 }
14856 
14857 void
14858 Sema::PushExpressionEvaluationContext(
14859     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14860     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14861   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14862                                 LambdaContextDecl, ExprContext);
14863   Cleanup.reset();
14864   if (!MaybeODRUseExprs.empty())
14865     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14866 }
14867 
14868 void
14869 Sema::PushExpressionEvaluationContext(
14870     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14871     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14872   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14873   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14874 }
14875 
14876 namespace {
14877 
14878 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14879   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14880   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14881     if (E->getOpcode() == UO_Deref)
14882       return CheckPossibleDeref(S, E->getSubExpr());
14883   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14884     return CheckPossibleDeref(S, E->getBase());
14885   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14886     return CheckPossibleDeref(S, E->getBase());
14887   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14888     QualType Inner;
14889     QualType Ty = E->getType();
14890     if (const auto *Ptr = Ty->getAs<PointerType>())
14891       Inner = Ptr->getPointeeType();
14892     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14893       Inner = Arr->getElementType();
14894     else
14895       return nullptr;
14896 
14897     if (Inner->hasAttr(attr::NoDeref))
14898       return E;
14899   }
14900   return nullptr;
14901 }
14902 
14903 } // namespace
14904 
14905 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14906   for (const Expr *E : Rec.PossibleDerefs) {
14907     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14908     if (DeclRef) {
14909       const ValueDecl *Decl = DeclRef->getDecl();
14910       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14911           << Decl->getName() << E->getSourceRange();
14912       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14913     } else {
14914       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14915           << E->getSourceRange();
14916     }
14917   }
14918   Rec.PossibleDerefs.clear();
14919 }
14920 
14921 void Sema::PopExpressionEvaluationContext() {
14922   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14923   unsigned NumTypos = Rec.NumTypos;
14924 
14925   if (!Rec.Lambdas.empty()) {
14926     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14927     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14928         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14929       unsigned D;
14930       if (Rec.isUnevaluated()) {
14931         // C++11 [expr.prim.lambda]p2:
14932         //   A lambda-expression shall not appear in an unevaluated operand
14933         //   (Clause 5).
14934         D = diag::err_lambda_unevaluated_operand;
14935       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14936         // C++1y [expr.const]p2:
14937         //   A conditional-expression e is a core constant expression unless the
14938         //   evaluation of e, following the rules of the abstract machine, would
14939         //   evaluate [...] a lambda-expression.
14940         D = diag::err_lambda_in_constant_expression;
14941       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14942         // C++17 [expr.prim.lamda]p2:
14943         // A lambda-expression shall not appear [...] in a template-argument.
14944         D = diag::err_lambda_in_invalid_context;
14945       } else
14946         llvm_unreachable("Couldn't infer lambda error message.");
14947 
14948       for (const auto *L : Rec.Lambdas)
14949         Diag(L->getBeginLoc(), D);
14950     }
14951   }
14952 
14953   WarnOnPendingNoDerefs(Rec);
14954 
14955   // When are coming out of an unevaluated context, clear out any
14956   // temporaries that we may have created as part of the evaluation of
14957   // the expression in that context: they aren't relevant because they
14958   // will never be constructed.
14959   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14960     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14961                              ExprCleanupObjects.end());
14962     Cleanup = Rec.ParentCleanup;
14963     CleanupVarDeclMarking();
14964     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14965   // Otherwise, merge the contexts together.
14966   } else {
14967     Cleanup.mergeFrom(Rec.ParentCleanup);
14968     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14969                             Rec.SavedMaybeODRUseExprs.end());
14970   }
14971 
14972   // Pop the current expression evaluation context off the stack.
14973   ExprEvalContexts.pop_back();
14974 
14975   // The global expression evaluation context record is never popped.
14976   ExprEvalContexts.back().NumTypos += NumTypos;
14977 }
14978 
14979 void Sema::DiscardCleanupsInEvaluationContext() {
14980   ExprCleanupObjects.erase(
14981          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14982          ExprCleanupObjects.end());
14983   Cleanup.reset();
14984   MaybeODRUseExprs.clear();
14985 }
14986 
14987 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14988   ExprResult Result = CheckPlaceholderExpr(E);
14989   if (Result.isInvalid())
14990     return ExprError();
14991   E = Result.get();
14992   if (!E->getType()->isVariablyModifiedType())
14993     return E;
14994   return TransformToPotentiallyEvaluated(E);
14995 }
14996 
14997 /// Are we in a context that is potentially constant evaluated per C++20
14998 /// [expr.const]p12?
14999 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15000   /// C++2a [expr.const]p12:
15001   //   An expression or conversion is potentially constant evaluated if it is
15002   switch (SemaRef.ExprEvalContexts.back().Context) {
15003     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15004       // -- a manifestly constant-evaluated expression,
15005     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15006     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15007     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15008       // -- a potentially-evaluated expression,
15009     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15010       // -- an immediate subexpression of a braced-init-list,
15011 
15012       // -- [FIXME] an expression of the form & cast-expression that occurs
15013       //    within a templated entity
15014       // -- a subexpression of one of the above that is not a subexpression of
15015       // a nested unevaluated operand.
15016       return true;
15017 
15018     case Sema::ExpressionEvaluationContext::Unevaluated:
15019     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15020       // Expressions in this context are never evaluated.
15021       return false;
15022   }
15023   llvm_unreachable("Invalid context");
15024 }
15025 
15026 /// Return true if this function has a calling convention that requires mangling
15027 /// in the size of the parameter pack.
15028 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15029   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15030   // we don't need parameter type sizes.
15031   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15032   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15033                             TT.getArch() != llvm::Triple::x86_64))
15034     return false;
15035 
15036   // If this is C++ and this isn't an extern "C" function, parameters do not
15037   // need to be complete. In this case, C++ mangling will apply, which doesn't
15038   // use the size of the parameters.
15039   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15040     return false;
15041 
15042   // Stdcall, fastcall, and vectorcall need this special treatment.
15043   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15044   switch (CC) {
15045   case CC_X86StdCall:
15046   case CC_X86FastCall:
15047   case CC_X86VectorCall:
15048     return true;
15049   default:
15050     break;
15051   }
15052   return false;
15053 }
15054 
15055 /// Require that all of the parameter types of function be complete. Normally,
15056 /// parameter types are only required to be complete when a function is called
15057 /// or defined, but to mangle functions with certain calling conventions, the
15058 /// mangler needs to know the size of the parameter list. In this situation,
15059 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15060 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15061 /// result in a linker error. Clang doesn't implement this behavior, and instead
15062 /// attempts to error at compile time.
15063 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15064                                                   SourceLocation Loc) {
15065   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15066     FunctionDecl *FD;
15067     ParmVarDecl *Param;
15068 
15069   public:
15070     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15071         : FD(FD), Param(Param) {}
15072 
15073     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15074       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15075       StringRef CCName;
15076       switch (CC) {
15077       case CC_X86StdCall:
15078         CCName = "stdcall";
15079         break;
15080       case CC_X86FastCall:
15081         CCName = "fastcall";
15082         break;
15083       case CC_X86VectorCall:
15084         CCName = "vectorcall";
15085         break;
15086       default:
15087         llvm_unreachable("CC does not need mangling");
15088       }
15089 
15090       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15091           << Param->getDeclName() << FD->getDeclName() << CCName;
15092     }
15093   };
15094 
15095   for (ParmVarDecl *Param : FD->parameters()) {
15096     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15097     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15098   }
15099 }
15100 
15101 namespace {
15102 enum class OdrUseContext {
15103   /// Declarations in this context are not odr-used.
15104   None,
15105   /// Declarations in this context are formally odr-used, but this is a
15106   /// dependent context.
15107   Dependent,
15108   /// Declarations in this context are odr-used but not actually used (yet).
15109   FormallyOdrUsed,
15110   /// Declarations in this context are used.
15111   Used
15112 };
15113 }
15114 
15115 /// Are we within a context in which references to resolved functions or to
15116 /// variables result in odr-use?
15117 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15118   OdrUseContext Result;
15119 
15120   switch (SemaRef.ExprEvalContexts.back().Context) {
15121     case Sema::ExpressionEvaluationContext::Unevaluated:
15122     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15123     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15124       return OdrUseContext::None;
15125 
15126     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15127     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15128       Result = OdrUseContext::Used;
15129       break;
15130 
15131     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15132       Result = OdrUseContext::FormallyOdrUsed;
15133       break;
15134 
15135     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15136       // A default argument formally results in odr-use, but doesn't actually
15137       // result in a use in any real sense until it itself is used.
15138       Result = OdrUseContext::FormallyOdrUsed;
15139       break;
15140   }
15141 
15142   if (SemaRef.CurContext->isDependentContext())
15143     return OdrUseContext::Dependent;
15144 
15145   return Result;
15146 }
15147 
15148 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15149   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15150   return Func->isConstexpr() &&
15151          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15152 }
15153 
15154 /// Mark a function referenced, and check whether it is odr-used
15155 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15156 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15157                                   bool MightBeOdrUse) {
15158   assert(Func && "No function?");
15159 
15160   Func->setReferenced();
15161 
15162   // Recursive functions aren't really used until they're used from some other
15163   // context.
15164   bool IsRecursiveCall = CurContext == Func;
15165 
15166   // C++11 [basic.def.odr]p3:
15167   //   A function whose name appears as a potentially-evaluated expression is
15168   //   odr-used if it is the unique lookup result or the selected member of a
15169   //   set of overloaded functions [...].
15170   //
15171   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15172   // can just check that here.
15173   OdrUseContext OdrUse =
15174       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15175   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15176     OdrUse = OdrUseContext::FormallyOdrUsed;
15177 
15178   // C++20 [expr.const]p12:
15179   //   A function [...] is needed for constant evaluation if it is [...] a
15180   //   constexpr function that is named by an expression that is potentially
15181   //   constant evaluated
15182   bool NeededForConstantEvaluation =
15183       isPotentiallyConstantEvaluatedContext(*this) &&
15184       isImplicitlyDefinableConstexprFunction(Func);
15185 
15186   // Determine whether we require a function definition to exist, per
15187   // C++11 [temp.inst]p3:
15188   //   Unless a function template specialization has been explicitly
15189   //   instantiated or explicitly specialized, the function template
15190   //   specialization is implicitly instantiated when the specialization is
15191   //   referenced in a context that requires a function definition to exist.
15192   // C++20 [temp.inst]p7:
15193   //   The existence of a definition of a [...] function is considered to
15194   //   affect the semantics of the program if the [...] function is needed for
15195   //   constant evaluation by an expression
15196   // C++20 [basic.def.odr]p10:
15197   //   Every program shall contain exactly one definition of every non-inline
15198   //   function or variable that is odr-used in that program outside of a
15199   //   discarded statement
15200   // C++20 [special]p1:
15201   //   The implementation will implicitly define [defaulted special members]
15202   //   if they are odr-used or needed for constant evaluation.
15203   //
15204   // Note that we skip the implicit instantiation of templates that are only
15205   // used in unused default arguments or by recursive calls to themselves.
15206   // This is formally non-conforming, but seems reasonable in practice.
15207   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15208                                              NeededForConstantEvaluation);
15209 
15210   // C++14 [temp.expl.spec]p6:
15211   //   If a template [...] is explicitly specialized then that specialization
15212   //   shall be declared before the first use of that specialization that would
15213   //   cause an implicit instantiation to take place, in every translation unit
15214   //   in which such a use occurs
15215   if (NeedDefinition &&
15216       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15217        Func->getMemberSpecializationInfo()))
15218     checkSpecializationVisibility(Loc, Func);
15219 
15220   // C++14 [except.spec]p17:
15221   //   An exception-specification is considered to be needed when:
15222   //   - the function is odr-used or, if it appears in an unevaluated operand,
15223   //     would be odr-used if the expression were potentially-evaluated;
15224   //
15225   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15226   // function is a pure virtual function we're calling, and in that case the
15227   // function was selected by overload resolution and we need to resolve its
15228   // exception specification for a different reason.
15229   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15230   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15231     ResolveExceptionSpec(Loc, FPT);
15232 
15233   if (getLangOpts().CUDA)
15234     CheckCUDACall(Loc, Func);
15235 
15236   // If we need a definition, try to create one.
15237   if (NeedDefinition && !Func->getBody()) {
15238     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
15239       Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15240       if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15241         if (Constructor->isDefaultConstructor()) {
15242           if (Constructor->isTrivial() &&
15243               !Constructor->hasAttr<DLLExportAttr>())
15244             return;
15245           DefineImplicitDefaultConstructor(Loc, Constructor);
15246         } else if (Constructor->isCopyConstructor()) {
15247           DefineImplicitCopyConstructor(Loc, Constructor);
15248         } else if (Constructor->isMoveConstructor()) {
15249           DefineImplicitMoveConstructor(Loc, Constructor);
15250         }
15251       } else if (Constructor->getInheritedConstructor()) {
15252         DefineInheritingConstructor(Loc, Constructor);
15253       }
15254     } else if (CXXDestructorDecl *Destructor =
15255                    dyn_cast<CXXDestructorDecl>(Func)) {
15256       Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15257       if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15258         if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15259           return;
15260         DefineImplicitDestructor(Loc, Destructor);
15261       }
15262       if (Destructor->isVirtual() && getLangOpts().AppleKext)
15263         MarkVTableUsed(Loc, Destructor->getParent());
15264     } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15265       if (MethodDecl->isOverloadedOperator() &&
15266           MethodDecl->getOverloadedOperator() == OO_Equal) {
15267         MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15268         if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15269           if (MethodDecl->isCopyAssignmentOperator())
15270             DefineImplicitCopyAssignment(Loc, MethodDecl);
15271           else if (MethodDecl->isMoveAssignmentOperator())
15272             DefineImplicitMoveAssignment(Loc, MethodDecl);
15273         }
15274       } else if (isa<CXXConversionDecl>(MethodDecl) &&
15275                  MethodDecl->getParent()->isLambda()) {
15276         CXXConversionDecl *Conversion =
15277             cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15278         if (Conversion->isLambdaToBlockPointerConversion())
15279           DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15280         else
15281           DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15282       } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15283         MarkVTableUsed(Loc, MethodDecl->getParent());
15284     }
15285 
15286     // Implicit instantiation of function templates and member functions of
15287     // class templates.
15288     if (Func->isImplicitlyInstantiable()) {
15289       TemplateSpecializationKind TSK =
15290           Func->getTemplateSpecializationKindForInstantiation();
15291       SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15292       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15293       if (FirstInstantiation) {
15294         PointOfInstantiation = Loc;
15295         Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15296       } else if (TSK != TSK_ImplicitInstantiation) {
15297         // Use the point of use as the point of instantiation, instead of the
15298         // point of explicit instantiation (which we track as the actual point
15299         // of instantiation). This gives better backtraces in diagnostics.
15300         PointOfInstantiation = Loc;
15301       }
15302 
15303       if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15304           Func->isConstexpr()) {
15305         if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15306             cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15307             CodeSynthesisContexts.size())
15308           PendingLocalImplicitInstantiations.push_back(
15309               std::make_pair(Func, PointOfInstantiation));
15310         else if (Func->isConstexpr())
15311           // Do not defer instantiations of constexpr functions, to avoid the
15312           // expression evaluator needing to call back into Sema if it sees a
15313           // call to such a function.
15314           InstantiateFunctionDefinition(PointOfInstantiation, Func);
15315         else {
15316           Func->setInstantiationIsPending(true);
15317           PendingInstantiations.push_back(
15318               std::make_pair(Func, PointOfInstantiation));
15319           // Notify the consumer that a function was implicitly instantiated.
15320           Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15321         }
15322       }
15323     } else {
15324       // Walk redefinitions, as some of them may be instantiable.
15325       for (auto i : Func->redecls()) {
15326         if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15327           MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15328       }
15329     }
15330   }
15331 
15332   // If this is the first "real" use, act on that.
15333   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15334     // Keep track of used but undefined functions.
15335     if (!Func->isDefined()) {
15336       if (mightHaveNonExternalLinkage(Func))
15337         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15338       else if (Func->getMostRecentDecl()->isInlined() &&
15339                !LangOpts.GNUInline &&
15340                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15341         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15342       else if (isExternalWithNoLinkageType(Func))
15343         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15344     }
15345 
15346     // Some x86 Windows calling conventions mangle the size of the parameter
15347     // pack into the name. Computing the size of the parameters requires the
15348     // parameter types to be complete. Check that now.
15349     if (funcHasParameterSizeMangling(*this, Func))
15350       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15351 
15352     Func->markUsed(Context);
15353 
15354     if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
15355       checkOpenMPDeviceFunction(Loc, Func);
15356   }
15357 }
15358 
15359 /// Directly mark a variable odr-used. Given a choice, prefer to use
15360 /// MarkVariableReferenced since it does additional checks and then
15361 /// calls MarkVarDeclODRUsed.
15362 /// If the variable must be captured:
15363 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15364 ///  - else capture it in the DeclContext that maps to the
15365 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15366 static void
15367 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15368                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15369   // Keep track of used but undefined variables.
15370   // FIXME: We shouldn't suppress this warning for static data members.
15371   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15372       (!Var->isExternallyVisible() || Var->isInline() ||
15373        SemaRef.isExternalWithNoLinkageType(Var)) &&
15374       !(Var->isStaticDataMember() && Var->hasInit())) {
15375     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15376     if (old.isInvalid())
15377       old = Loc;
15378   }
15379   QualType CaptureType, DeclRefType;
15380   if (SemaRef.LangOpts.OpenMP)
15381     SemaRef.tryCaptureOpenMPLambdas(Var);
15382   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15383     /*EllipsisLoc*/ SourceLocation(),
15384     /*BuildAndDiagnose*/ true,
15385     CaptureType, DeclRefType,
15386     FunctionScopeIndexToStopAt);
15387 
15388   Var->markUsed(SemaRef.Context);
15389 }
15390 
15391 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15392                                              SourceLocation Loc,
15393                                              unsigned CapturingScopeIndex) {
15394   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15395 }
15396 
15397 static void
15398 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15399                                    ValueDecl *var, DeclContext *DC) {
15400   DeclContext *VarDC = var->getDeclContext();
15401 
15402   //  If the parameter still belongs to the translation unit, then
15403   //  we're actually just using one parameter in the declaration of
15404   //  the next.
15405   if (isa<ParmVarDecl>(var) &&
15406       isa<TranslationUnitDecl>(VarDC))
15407     return;
15408 
15409   // For C code, don't diagnose about capture if we're not actually in code
15410   // right now; it's impossible to write a non-constant expression outside of
15411   // function context, so we'll get other (more useful) diagnostics later.
15412   //
15413   // For C++, things get a bit more nasty... it would be nice to suppress this
15414   // diagnostic for certain cases like using a local variable in an array bound
15415   // for a member of a local class, but the correct predicate is not obvious.
15416   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15417     return;
15418 
15419   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15420   unsigned ContextKind = 3; // unknown
15421   if (isa<CXXMethodDecl>(VarDC) &&
15422       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15423     ContextKind = 2;
15424   } else if (isa<FunctionDecl>(VarDC)) {
15425     ContextKind = 0;
15426   } else if (isa<BlockDecl>(VarDC)) {
15427     ContextKind = 1;
15428   }
15429 
15430   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15431     << var << ValueKind << ContextKind << VarDC;
15432   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15433       << var;
15434 
15435   // FIXME: Add additional diagnostic info about class etc. which prevents
15436   // capture.
15437 }
15438 
15439 
15440 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15441                                       bool &SubCapturesAreNested,
15442                                       QualType &CaptureType,
15443                                       QualType &DeclRefType) {
15444    // Check whether we've already captured it.
15445   if (CSI->CaptureMap.count(Var)) {
15446     // If we found a capture, any subcaptures are nested.
15447     SubCapturesAreNested = true;
15448 
15449     // Retrieve the capture type for this variable.
15450     CaptureType = CSI->getCapture(Var).getCaptureType();
15451 
15452     // Compute the type of an expression that refers to this variable.
15453     DeclRefType = CaptureType.getNonReferenceType();
15454 
15455     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15456     // are mutable in the sense that user can change their value - they are
15457     // private instances of the captured declarations.
15458     const Capture &Cap = CSI->getCapture(Var);
15459     if (Cap.isCopyCapture() &&
15460         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15461         !(isa<CapturedRegionScopeInfo>(CSI) &&
15462           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15463       DeclRefType.addConst();
15464     return true;
15465   }
15466   return false;
15467 }
15468 
15469 // Only block literals, captured statements, and lambda expressions can
15470 // capture; other scopes don't work.
15471 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15472                                  SourceLocation Loc,
15473                                  const bool Diagnose, Sema &S) {
15474   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15475     return getLambdaAwareParentOfDeclContext(DC);
15476   else if (Var->hasLocalStorage()) {
15477     if (Diagnose)
15478        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15479   }
15480   return nullptr;
15481 }
15482 
15483 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15484 // certain types of variables (unnamed, variably modified types etc.)
15485 // so check for eligibility.
15486 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15487                                  SourceLocation Loc,
15488                                  const bool Diagnose, Sema &S) {
15489 
15490   bool IsBlock = isa<BlockScopeInfo>(CSI);
15491   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15492 
15493   // Lambdas are not allowed to capture unnamed variables
15494   // (e.g. anonymous unions).
15495   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15496   // assuming that's the intent.
15497   if (IsLambda && !Var->getDeclName()) {
15498     if (Diagnose) {
15499       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15500       S.Diag(Var->getLocation(), diag::note_declared_at);
15501     }
15502     return false;
15503   }
15504 
15505   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15506   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15507     if (Diagnose) {
15508       S.Diag(Loc, diag::err_ref_vm_type);
15509       S.Diag(Var->getLocation(), diag::note_previous_decl)
15510         << Var->getDeclName();
15511     }
15512     return false;
15513   }
15514   // Prohibit structs with flexible array members too.
15515   // We cannot capture what is in the tail end of the struct.
15516   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15517     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15518       if (Diagnose) {
15519         if (IsBlock)
15520           S.Diag(Loc, diag::err_ref_flexarray_type);
15521         else
15522           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15523             << Var->getDeclName();
15524         S.Diag(Var->getLocation(), diag::note_previous_decl)
15525           << Var->getDeclName();
15526       }
15527       return false;
15528     }
15529   }
15530   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15531   // Lambdas and captured statements are not allowed to capture __block
15532   // variables; they don't support the expected semantics.
15533   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15534     if (Diagnose) {
15535       S.Diag(Loc, diag::err_capture_block_variable)
15536         << Var->getDeclName() << !IsLambda;
15537       S.Diag(Var->getLocation(), diag::note_previous_decl)
15538         << Var->getDeclName();
15539     }
15540     return false;
15541   }
15542   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15543   if (S.getLangOpts().OpenCL && IsBlock &&
15544       Var->getType()->isBlockPointerType()) {
15545     if (Diagnose)
15546       S.Diag(Loc, diag::err_opencl_block_ref_block);
15547     return false;
15548   }
15549 
15550   return true;
15551 }
15552 
15553 // Returns true if the capture by block was successful.
15554 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15555                                  SourceLocation Loc,
15556                                  const bool BuildAndDiagnose,
15557                                  QualType &CaptureType,
15558                                  QualType &DeclRefType,
15559                                  const bool Nested,
15560                                  Sema &S, bool Invalid) {
15561   bool ByRef = false;
15562 
15563   // Blocks are not allowed to capture arrays, excepting OpenCL.
15564   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15565   // (decayed to pointers).
15566   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15567     if (BuildAndDiagnose) {
15568       S.Diag(Loc, diag::err_ref_array_type);
15569       S.Diag(Var->getLocation(), diag::note_previous_decl)
15570       << Var->getDeclName();
15571       Invalid = true;
15572     } else {
15573       return false;
15574     }
15575   }
15576 
15577   // Forbid the block-capture of autoreleasing variables.
15578   if (!Invalid &&
15579       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15580     if (BuildAndDiagnose) {
15581       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15582         << /*block*/ 0;
15583       S.Diag(Var->getLocation(), diag::note_previous_decl)
15584         << Var->getDeclName();
15585       Invalid = true;
15586     } else {
15587       return false;
15588     }
15589   }
15590 
15591   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15592   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15593     // This function finds out whether there is an AttributedType of kind
15594     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15595     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15596     // rather than being added implicitly by the compiler.
15597     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15598       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15599         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15600           return true;
15601 
15602         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15603         Ty = AttrTy->getModifiedType();
15604       }
15605 
15606       return false;
15607     };
15608 
15609     QualType PointeeTy = PT->getPointeeType();
15610 
15611     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15612         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15613         !IsObjCOwnershipAttributedType(PointeeTy)) {
15614       if (BuildAndDiagnose) {
15615         SourceLocation VarLoc = Var->getLocation();
15616         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15617         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15618       }
15619     }
15620   }
15621 
15622   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15623   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15624       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15625     // Block capture by reference does not change the capture or
15626     // declaration reference types.
15627     ByRef = true;
15628   } else {
15629     // Block capture by copy introduces 'const'.
15630     CaptureType = CaptureType.getNonReferenceType().withConst();
15631     DeclRefType = CaptureType;
15632   }
15633 
15634   // Actually capture the variable.
15635   if (BuildAndDiagnose)
15636     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15637                     CaptureType, Invalid);
15638 
15639   return !Invalid;
15640 }
15641 
15642 
15643 /// Capture the given variable in the captured region.
15644 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15645                                     VarDecl *Var,
15646                                     SourceLocation Loc,
15647                                     const bool BuildAndDiagnose,
15648                                     QualType &CaptureType,
15649                                     QualType &DeclRefType,
15650                                     const bool RefersToCapturedVariable,
15651                                     Sema &S, bool Invalid) {
15652   // By default, capture variables by reference.
15653   bool ByRef = true;
15654   // Using an LValue reference type is consistent with Lambdas (see below).
15655   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15656     if (S.isOpenMPCapturedDecl(Var)) {
15657       bool HasConst = DeclRefType.isConstQualified();
15658       DeclRefType = DeclRefType.getUnqualifiedType();
15659       // Don't lose diagnostics about assignments to const.
15660       if (HasConst)
15661         DeclRefType.addConst();
15662     }
15663     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15664   }
15665 
15666   if (ByRef)
15667     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15668   else
15669     CaptureType = DeclRefType;
15670 
15671   // Actually capture the variable.
15672   if (BuildAndDiagnose)
15673     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15674                     Loc, SourceLocation(), CaptureType, Invalid);
15675 
15676   return !Invalid;
15677 }
15678 
15679 /// Capture the given variable in the lambda.
15680 static bool captureInLambda(LambdaScopeInfo *LSI,
15681                             VarDecl *Var,
15682                             SourceLocation Loc,
15683                             const bool BuildAndDiagnose,
15684                             QualType &CaptureType,
15685                             QualType &DeclRefType,
15686                             const bool RefersToCapturedVariable,
15687                             const Sema::TryCaptureKind Kind,
15688                             SourceLocation EllipsisLoc,
15689                             const bool IsTopScope,
15690                             Sema &S, bool Invalid) {
15691   // Determine whether we are capturing by reference or by value.
15692   bool ByRef = false;
15693   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15694     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15695   } else {
15696     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15697   }
15698 
15699   // Compute the type of the field that will capture this variable.
15700   if (ByRef) {
15701     // C++11 [expr.prim.lambda]p15:
15702     //   An entity is captured by reference if it is implicitly or
15703     //   explicitly captured but not captured by copy. It is
15704     //   unspecified whether additional unnamed non-static data
15705     //   members are declared in the closure type for entities
15706     //   captured by reference.
15707     //
15708     // FIXME: It is not clear whether we want to build an lvalue reference
15709     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15710     // to do the former, while EDG does the latter. Core issue 1249 will
15711     // clarify, but for now we follow GCC because it's a more permissive and
15712     // easily defensible position.
15713     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15714   } else {
15715     // C++11 [expr.prim.lambda]p14:
15716     //   For each entity captured by copy, an unnamed non-static
15717     //   data member is declared in the closure type. The
15718     //   declaration order of these members is unspecified. The type
15719     //   of such a data member is the type of the corresponding
15720     //   captured entity if the entity is not a reference to an
15721     //   object, or the referenced type otherwise. [Note: If the
15722     //   captured entity is a reference to a function, the
15723     //   corresponding data member is also a reference to a
15724     //   function. - end note ]
15725     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15726       if (!RefType->getPointeeType()->isFunctionType())
15727         CaptureType = RefType->getPointeeType();
15728     }
15729 
15730     // Forbid the lambda copy-capture of autoreleasing variables.
15731     if (!Invalid &&
15732         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15733       if (BuildAndDiagnose) {
15734         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15735         S.Diag(Var->getLocation(), diag::note_previous_decl)
15736           << Var->getDeclName();
15737         Invalid = true;
15738       } else {
15739         return false;
15740       }
15741     }
15742 
15743     // Make sure that by-copy captures are of a complete and non-abstract type.
15744     if (!Invalid && BuildAndDiagnose) {
15745       if (!CaptureType->isDependentType() &&
15746           S.RequireCompleteType(Loc, CaptureType,
15747                                 diag::err_capture_of_incomplete_type,
15748                                 Var->getDeclName()))
15749         Invalid = true;
15750       else if (S.RequireNonAbstractType(Loc, CaptureType,
15751                                         diag::err_capture_of_abstract_type))
15752         Invalid = true;
15753     }
15754   }
15755 
15756   // Compute the type of a reference to this captured variable.
15757   if (ByRef)
15758     DeclRefType = CaptureType.getNonReferenceType();
15759   else {
15760     // C++ [expr.prim.lambda]p5:
15761     //   The closure type for a lambda-expression has a public inline
15762     //   function call operator [...]. This function call operator is
15763     //   declared const (9.3.1) if and only if the lambda-expression's
15764     //   parameter-declaration-clause is not followed by mutable.
15765     DeclRefType = CaptureType.getNonReferenceType();
15766     if (!LSI->Mutable && !CaptureType->isReferenceType())
15767       DeclRefType.addConst();
15768   }
15769 
15770   // Add the capture.
15771   if (BuildAndDiagnose)
15772     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15773                     Loc, EllipsisLoc, CaptureType, Invalid);
15774 
15775   return !Invalid;
15776 }
15777 
15778 bool Sema::tryCaptureVariable(
15779     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15780     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15781     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15782   // An init-capture is notionally from the context surrounding its
15783   // declaration, but its parent DC is the lambda class.
15784   DeclContext *VarDC = Var->getDeclContext();
15785   if (Var->isInitCapture())
15786     VarDC = VarDC->getParent();
15787 
15788   DeclContext *DC = CurContext;
15789   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15790       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15791   // We need to sync up the Declaration Context with the
15792   // FunctionScopeIndexToStopAt
15793   if (FunctionScopeIndexToStopAt) {
15794     unsigned FSIndex = FunctionScopes.size() - 1;
15795     while (FSIndex != MaxFunctionScopesIndex) {
15796       DC = getLambdaAwareParentOfDeclContext(DC);
15797       --FSIndex;
15798     }
15799   }
15800 
15801 
15802   // If the variable is declared in the current context, there is no need to
15803   // capture it.
15804   if (VarDC == DC) return true;
15805 
15806   // Capture global variables if it is required to use private copy of this
15807   // variable.
15808   bool IsGlobal = !Var->hasLocalStorage();
15809   if (IsGlobal &&
15810       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15811                                                 MaxFunctionScopesIndex)))
15812     return true;
15813   Var = Var->getCanonicalDecl();
15814 
15815   // Walk up the stack to determine whether we can capture the variable,
15816   // performing the "simple" checks that don't depend on type. We stop when
15817   // we've either hit the declared scope of the variable or find an existing
15818   // capture of that variable.  We start from the innermost capturing-entity
15819   // (the DC) and ensure that all intervening capturing-entities
15820   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15821   // declcontext can either capture the variable or have already captured
15822   // the variable.
15823   CaptureType = Var->getType();
15824   DeclRefType = CaptureType.getNonReferenceType();
15825   bool Nested = false;
15826   bool Explicit = (Kind != TryCapture_Implicit);
15827   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15828   do {
15829     // Only block literals, captured statements, and lambda expressions can
15830     // capture; other scopes don't work.
15831     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15832                                                               ExprLoc,
15833                                                               BuildAndDiagnose,
15834                                                               *this);
15835     // We need to check for the parent *first* because, if we *have*
15836     // private-captured a global variable, we need to recursively capture it in
15837     // intermediate blocks, lambdas, etc.
15838     if (!ParentDC) {
15839       if (IsGlobal) {
15840         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15841         break;
15842       }
15843       return true;
15844     }
15845 
15846     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15847     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15848 
15849 
15850     // Check whether we've already captured it.
15851     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15852                                              DeclRefType)) {
15853       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15854       break;
15855     }
15856     // If we are instantiating a generic lambda call operator body,
15857     // we do not want to capture new variables.  What was captured
15858     // during either a lambdas transformation or initial parsing
15859     // should be used.
15860     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15861       if (BuildAndDiagnose) {
15862         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15863         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15864           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15865           Diag(Var->getLocation(), diag::note_previous_decl)
15866              << Var->getDeclName();
15867           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15868         } else
15869           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15870       }
15871       return true;
15872     }
15873 
15874     // Try to capture variable-length arrays types.
15875     if (Var->getType()->isVariablyModifiedType()) {
15876       // We're going to walk down into the type and look for VLA
15877       // expressions.
15878       QualType QTy = Var->getType();
15879       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15880         QTy = PVD->getOriginalType();
15881       captureVariablyModifiedType(Context, QTy, CSI);
15882     }
15883 
15884     if (getLangOpts().OpenMP) {
15885       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15886         // OpenMP private variables should not be captured in outer scope, so
15887         // just break here. Similarly, global variables that are captured in a
15888         // target region should not be captured outside the scope of the region.
15889         if (RSI->CapRegionKind == CR_OpenMP) {
15890           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15891           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15892                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15893           // When we detect target captures we are looking from inside the
15894           // target region, therefore we need to propagate the capture from the
15895           // enclosing region. Therefore, the capture is not initially nested.
15896           if (IsTargetCap)
15897             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15898 
15899           if (IsTargetCap || IsOpenMPPrivateDecl) {
15900             Nested = !IsTargetCap;
15901             DeclRefType = DeclRefType.getUnqualifiedType();
15902             CaptureType = Context.getLValueReferenceType(DeclRefType);
15903             break;
15904           }
15905         }
15906       }
15907     }
15908     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15909       // No capture-default, and this is not an explicit capture
15910       // so cannot capture this variable.
15911       if (BuildAndDiagnose) {
15912         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15913         Diag(Var->getLocation(), diag::note_previous_decl)
15914           << Var->getDeclName();
15915         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15916           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15917                diag::note_lambda_decl);
15918         // FIXME: If we error out because an outer lambda can not implicitly
15919         // capture a variable that an inner lambda explicitly captures, we
15920         // should have the inner lambda do the explicit capture - because
15921         // it makes for cleaner diagnostics later.  This would purely be done
15922         // so that the diagnostic does not misleadingly claim that a variable
15923         // can not be captured by a lambda implicitly even though it is captured
15924         // explicitly.  Suggestion:
15925         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15926         //    at the function head
15927         //  - cache the StartingDeclContext - this must be a lambda
15928         //  - captureInLambda in the innermost lambda the variable.
15929       }
15930       return true;
15931     }
15932 
15933     FunctionScopesIndex--;
15934     DC = ParentDC;
15935     Explicit = false;
15936   } while (!VarDC->Equals(DC));
15937 
15938   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15939   // computing the type of the capture at each step, checking type-specific
15940   // requirements, and adding captures if requested.
15941   // If the variable had already been captured previously, we start capturing
15942   // at the lambda nested within that one.
15943   bool Invalid = false;
15944   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15945        ++I) {
15946     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15947 
15948     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15949     // certain types of variables (unnamed, variably modified types etc.)
15950     // so check for eligibility.
15951     if (!Invalid)
15952       Invalid =
15953           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
15954 
15955     // After encountering an error, if we're actually supposed to capture, keep
15956     // capturing in nested contexts to suppress any follow-on diagnostics.
15957     if (Invalid && !BuildAndDiagnose)
15958       return true;
15959 
15960     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15961       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15962                                DeclRefType, Nested, *this, Invalid);
15963       Nested = true;
15964     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15965       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
15966                                          CaptureType, DeclRefType, Nested,
15967                                          *this, Invalid);
15968       Nested = true;
15969     } else {
15970       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15971       Invalid =
15972           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15973                            DeclRefType, Nested, Kind, EllipsisLoc,
15974                            /*IsTopScope*/ I == N - 1, *this, Invalid);
15975       Nested = true;
15976     }
15977 
15978     if (Invalid && !BuildAndDiagnose)
15979       return true;
15980   }
15981   return Invalid;
15982 }
15983 
15984 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15985                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15986   QualType CaptureType;
15987   QualType DeclRefType;
15988   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15989                             /*BuildAndDiagnose=*/true, CaptureType,
15990                             DeclRefType, nullptr);
15991 }
15992 
15993 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15994   QualType CaptureType;
15995   QualType DeclRefType;
15996   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15997                              /*BuildAndDiagnose=*/false, CaptureType,
15998                              DeclRefType, nullptr);
15999 }
16000 
16001 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16002   QualType CaptureType;
16003   QualType DeclRefType;
16004 
16005   // Determine whether we can capture this variable.
16006   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16007                          /*BuildAndDiagnose=*/false, CaptureType,
16008                          DeclRefType, nullptr))
16009     return QualType();
16010 
16011   return DeclRefType;
16012 }
16013 
16014 namespace {
16015 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16016 // The produced TemplateArgumentListInfo* points to data stored within this
16017 // object, so should only be used in contexts where the pointer will not be
16018 // used after the CopiedTemplateArgs object is destroyed.
16019 class CopiedTemplateArgs {
16020   bool HasArgs;
16021   TemplateArgumentListInfo TemplateArgStorage;
16022 public:
16023   template<typename RefExpr>
16024   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16025     if (HasArgs)
16026       E->copyTemplateArgumentsInto(TemplateArgStorage);
16027   }
16028   operator TemplateArgumentListInfo*()
16029 #ifdef __has_cpp_attribute
16030 #if __has_cpp_attribute(clang::lifetimebound)
16031   [[clang::lifetimebound]]
16032 #endif
16033 #endif
16034   {
16035     return HasArgs ? &TemplateArgStorage : nullptr;
16036   }
16037 };
16038 }
16039 
16040 /// Walk the set of potential results of an expression and mark them all as
16041 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16042 ///
16043 /// \return A new expression if we found any potential results, ExprEmpty() if
16044 ///         not, and ExprError() if we diagnosed an error.
16045 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16046                                                       NonOdrUseReason NOUR) {
16047   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16048   // an object that satisfies the requirements for appearing in a
16049   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16050   // is immediately applied."  This function handles the lvalue-to-rvalue
16051   // conversion part.
16052   //
16053   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16054   // transform it into the relevant kind of non-odr-use node and rebuild the
16055   // tree of nodes leading to it.
16056   //
16057   // This is a mini-TreeTransform that only transforms a restricted subset of
16058   // nodes (and only certain operands of them).
16059 
16060   // Rebuild a subexpression.
16061   auto Rebuild = [&](Expr *Sub) {
16062     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16063   };
16064 
16065   // Check whether a potential result satisfies the requirements of NOUR.
16066   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16067     // Any entity other than a VarDecl is always odr-used whenever it's named
16068     // in a potentially-evaluated expression.
16069     auto *VD = dyn_cast<VarDecl>(D);
16070     if (!VD)
16071       return true;
16072 
16073     // C++2a [basic.def.odr]p4:
16074     //   A variable x whose name appears as a potentially-evalauted expression
16075     //   e is odr-used by e unless
16076     //   -- x is a reference that is usable in constant expressions, or
16077     //   -- x is a variable of non-reference type that is usable in constant
16078     //      expressions and has no mutable subobjects, and e is an element of
16079     //      the set of potential results of an expression of
16080     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16081     //      conversion is applied, or
16082     //   -- x is a variable of non-reference type, and e is an element of the
16083     //      set of potential results of a discarded-value expression to which
16084     //      the lvalue-to-rvalue conversion is not applied
16085     //
16086     // We check the first bullet and the "potentially-evaluated" condition in
16087     // BuildDeclRefExpr. We check the type requirements in the second bullet
16088     // in CheckLValueToRValueConversionOperand below.
16089     switch (NOUR) {
16090     case NOUR_None:
16091     case NOUR_Unevaluated:
16092       llvm_unreachable("unexpected non-odr-use-reason");
16093 
16094     case NOUR_Constant:
16095       // Constant references were handled when they were built.
16096       if (VD->getType()->isReferenceType())
16097         return true;
16098       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16099         if (RD->hasMutableFields())
16100           return true;
16101       if (!VD->isUsableInConstantExpressions(S.Context))
16102         return true;
16103       break;
16104 
16105     case NOUR_Discarded:
16106       if (VD->getType()->isReferenceType())
16107         return true;
16108       break;
16109     }
16110     return false;
16111   };
16112 
16113   // Mark that this expression does not constitute an odr-use.
16114   auto MarkNotOdrUsed = [&] {
16115     S.MaybeODRUseExprs.erase(E);
16116     if (LambdaScopeInfo *LSI = S.getCurLambda())
16117       LSI->markVariableExprAsNonODRUsed(E);
16118   };
16119 
16120   // C++2a [basic.def.odr]p2:
16121   //   The set of potential results of an expression e is defined as follows:
16122   switch (E->getStmtClass()) {
16123   //   -- If e is an id-expression, ...
16124   case Expr::DeclRefExprClass: {
16125     auto *DRE = cast<DeclRefExpr>(E);
16126     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16127       break;
16128 
16129     // Rebuild as a non-odr-use DeclRefExpr.
16130     MarkNotOdrUsed();
16131     return DeclRefExpr::Create(
16132         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16133         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16134         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16135         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16136   }
16137 
16138   case Expr::FunctionParmPackExprClass: {
16139     auto *FPPE = cast<FunctionParmPackExpr>(E);
16140     // If any of the declarations in the pack is odr-used, then the expression
16141     // as a whole constitutes an odr-use.
16142     for (VarDecl *D : *FPPE)
16143       if (IsPotentialResultOdrUsed(D))
16144         return ExprEmpty();
16145 
16146     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16147     // nothing cares about whether we marked this as an odr-use, but it might
16148     // be useful for non-compiler tools.
16149     MarkNotOdrUsed();
16150     break;
16151   }
16152 
16153   //   -- If e is a subscripting operation with an array operand...
16154   case Expr::ArraySubscriptExprClass: {
16155     auto *ASE = cast<ArraySubscriptExpr>(E);
16156     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16157     if (!OldBase->getType()->isArrayType())
16158       break;
16159     ExprResult Base = Rebuild(OldBase);
16160     if (!Base.isUsable())
16161       return Base;
16162     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16163     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16164     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16165     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16166                                      ASE->getRBracketLoc());
16167   }
16168 
16169   case Expr::MemberExprClass: {
16170     auto *ME = cast<MemberExpr>(E);
16171     // -- If e is a class member access expression [...] naming a non-static
16172     //    data member...
16173     if (isa<FieldDecl>(ME->getMemberDecl())) {
16174       ExprResult Base = Rebuild(ME->getBase());
16175       if (!Base.isUsable())
16176         return Base;
16177       return MemberExpr::Create(
16178           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16179           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16180           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16181           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16182           ME->getObjectKind(), ME->isNonOdrUse());
16183     }
16184 
16185     if (ME->getMemberDecl()->isCXXInstanceMember())
16186       break;
16187 
16188     // -- If e is a class member access expression naming a static data member,
16189     //    ...
16190     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16191       break;
16192 
16193     // Rebuild as a non-odr-use MemberExpr.
16194     MarkNotOdrUsed();
16195     return MemberExpr::Create(
16196         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16197         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16198         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16199         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16200     return ExprEmpty();
16201   }
16202 
16203   case Expr::BinaryOperatorClass: {
16204     auto *BO = cast<BinaryOperator>(E);
16205     Expr *LHS = BO->getLHS();
16206     Expr *RHS = BO->getRHS();
16207     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16208     if (BO->getOpcode() == BO_PtrMemD) {
16209       ExprResult Sub = Rebuild(LHS);
16210       if (!Sub.isUsable())
16211         return Sub;
16212       LHS = Sub.get();
16213     //   -- If e is a comma expression, ...
16214     } else if (BO->getOpcode() == BO_Comma) {
16215       ExprResult Sub = Rebuild(RHS);
16216       if (!Sub.isUsable())
16217         return Sub;
16218       RHS = Sub.get();
16219     } else {
16220       break;
16221     }
16222     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16223                         LHS, RHS);
16224   }
16225 
16226   //   -- If e has the form (e1)...
16227   case Expr::ParenExprClass: {
16228     auto *PE = cast<ParenExpr>(E);
16229     ExprResult Sub = Rebuild(PE->getSubExpr());
16230     if (!Sub.isUsable())
16231       return Sub;
16232     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16233   }
16234 
16235   //   -- If e is a glvalue conditional expression, ...
16236   // We don't apply this to a binary conditional operator. FIXME: Should we?
16237   case Expr::ConditionalOperatorClass: {
16238     auto *CO = cast<ConditionalOperator>(E);
16239     ExprResult LHS = Rebuild(CO->getLHS());
16240     if (LHS.isInvalid())
16241       return ExprError();
16242     ExprResult RHS = Rebuild(CO->getRHS());
16243     if (RHS.isInvalid())
16244       return ExprError();
16245     if (!LHS.isUsable() && !RHS.isUsable())
16246       return ExprEmpty();
16247     if (!LHS.isUsable())
16248       LHS = CO->getLHS();
16249     if (!RHS.isUsable())
16250       RHS = CO->getRHS();
16251     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16252                                 CO->getCond(), LHS.get(), RHS.get());
16253   }
16254 
16255   // [Clang extension]
16256   //   -- If e has the form __extension__ e1...
16257   case Expr::UnaryOperatorClass: {
16258     auto *UO = cast<UnaryOperator>(E);
16259     if (UO->getOpcode() != UO_Extension)
16260       break;
16261     ExprResult Sub = Rebuild(UO->getSubExpr());
16262     if (!Sub.isUsable())
16263       return Sub;
16264     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16265                           Sub.get());
16266   }
16267 
16268   // [Clang extension]
16269   //   -- If e has the form _Generic(...), the set of potential results is the
16270   //      union of the sets of potential results of the associated expressions.
16271   case Expr::GenericSelectionExprClass: {
16272     auto *GSE = cast<GenericSelectionExpr>(E);
16273 
16274     SmallVector<Expr *, 4> AssocExprs;
16275     bool AnyChanged = false;
16276     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16277       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16278       if (AssocExpr.isInvalid())
16279         return ExprError();
16280       if (AssocExpr.isUsable()) {
16281         AssocExprs.push_back(AssocExpr.get());
16282         AnyChanged = true;
16283       } else {
16284         AssocExprs.push_back(OrigAssocExpr);
16285       }
16286     }
16287 
16288     return AnyChanged ? S.CreateGenericSelectionExpr(
16289                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16290                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16291                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16292                       : ExprEmpty();
16293   }
16294 
16295   // [Clang extension]
16296   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16297   //      results is the union of the sets of potential results of the
16298   //      second and third subexpressions.
16299   case Expr::ChooseExprClass: {
16300     auto *CE = cast<ChooseExpr>(E);
16301 
16302     ExprResult LHS = Rebuild(CE->getLHS());
16303     if (LHS.isInvalid())
16304       return ExprError();
16305 
16306     ExprResult RHS = Rebuild(CE->getLHS());
16307     if (RHS.isInvalid())
16308       return ExprError();
16309 
16310     if (!LHS.get() && !RHS.get())
16311       return ExprEmpty();
16312     if (!LHS.isUsable())
16313       LHS = CE->getLHS();
16314     if (!RHS.isUsable())
16315       RHS = CE->getRHS();
16316 
16317     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16318                              RHS.get(), CE->getRParenLoc());
16319   }
16320 
16321   // Step through non-syntactic nodes.
16322   case Expr::ConstantExprClass: {
16323     auto *CE = cast<ConstantExpr>(E);
16324     ExprResult Sub = Rebuild(CE->getSubExpr());
16325     if (!Sub.isUsable())
16326       return Sub;
16327     return ConstantExpr::Create(S.Context, Sub.get());
16328   }
16329 
16330   // We could mostly rely on the recursive rebuilding to rebuild implicit
16331   // casts, but not at the top level, so rebuild them here.
16332   case Expr::ImplicitCastExprClass: {
16333     auto *ICE = cast<ImplicitCastExpr>(E);
16334     // Only step through the narrow set of cast kinds we expect to encounter.
16335     // Anything else suggests we've left the region in which potential results
16336     // can be found.
16337     switch (ICE->getCastKind()) {
16338     case CK_NoOp:
16339     case CK_DerivedToBase:
16340     case CK_UncheckedDerivedToBase: {
16341       ExprResult Sub = Rebuild(ICE->getSubExpr());
16342       if (!Sub.isUsable())
16343         return Sub;
16344       CXXCastPath Path(ICE->path());
16345       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16346                                  ICE->getValueKind(), &Path);
16347     }
16348 
16349     default:
16350       break;
16351     }
16352     break;
16353   }
16354 
16355   default:
16356     break;
16357   }
16358 
16359   // Can't traverse through this node. Nothing to do.
16360   return ExprEmpty();
16361 }
16362 
16363 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16364   // C++2a [basic.def.odr]p4:
16365   //   [...] an expression of non-volatile-qualified non-class type to which
16366   //   the lvalue-to-rvalue conversion is applied [...]
16367   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16368     return E;
16369 
16370   ExprResult Result =
16371       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16372   if (Result.isInvalid())
16373     return ExprError();
16374   return Result.get() ? Result : E;
16375 }
16376 
16377 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16378   Res = CorrectDelayedTyposInExpr(Res);
16379 
16380   if (!Res.isUsable())
16381     return Res;
16382 
16383   // If a constant-expression is a reference to a variable where we delay
16384   // deciding whether it is an odr-use, just assume we will apply the
16385   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16386   // (a non-type template argument), we have special handling anyway.
16387   return CheckLValueToRValueConversionOperand(Res.get());
16388 }
16389 
16390 void Sema::CleanupVarDeclMarking() {
16391   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16392   // call.
16393   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16394   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16395 
16396   for (Expr *E : LocalMaybeODRUseExprs) {
16397     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16398       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16399                          DRE->getLocation(), *this);
16400     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16401       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16402                          *this);
16403     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16404       for (VarDecl *VD : *FP)
16405         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16406     } else {
16407       llvm_unreachable("Unexpected expression");
16408     }
16409   }
16410 
16411   assert(MaybeODRUseExprs.empty() &&
16412          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16413 }
16414 
16415 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16416                                     VarDecl *Var, Expr *E) {
16417   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16418           isa<FunctionParmPackExpr>(E)) &&
16419          "Invalid Expr argument to DoMarkVarDeclReferenced");
16420   Var->setReferenced();
16421 
16422   if (Var->isInvalidDecl())
16423     return;
16424 
16425   auto *MSI = Var->getMemberSpecializationInfo();
16426   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16427                                        : Var->getTemplateSpecializationKind();
16428 
16429   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16430   bool UsableInConstantExpr =
16431       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16432 
16433   // C++20 [expr.const]p12:
16434   //   A variable [...] is needed for constant evaluation if it is [...] a
16435   //   variable whose name appears as a potentially constant evaluated
16436   //   expression that is either a contexpr variable or is of non-volatile
16437   //   const-qualified integral type or of reference type
16438   bool NeededForConstantEvaluation =
16439       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16440 
16441   bool NeedDefinition =
16442       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16443 
16444   VarTemplateSpecializationDecl *VarSpec =
16445       dyn_cast<VarTemplateSpecializationDecl>(Var);
16446   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16447          "Can't instantiate a partial template specialization.");
16448 
16449   // If this might be a member specialization of a static data member, check
16450   // the specialization is visible. We already did the checks for variable
16451   // template specializations when we created them.
16452   if (NeedDefinition && TSK != TSK_Undeclared &&
16453       !isa<VarTemplateSpecializationDecl>(Var))
16454     SemaRef.checkSpecializationVisibility(Loc, Var);
16455 
16456   // Perform implicit instantiation of static data members, static data member
16457   // templates of class templates, and variable template specializations. Delay
16458   // instantiations of variable templates, except for those that could be used
16459   // in a constant expression.
16460   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16461     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16462     // instantiation declaration if a variable is usable in a constant
16463     // expression (among other cases).
16464     bool TryInstantiating =
16465         TSK == TSK_ImplicitInstantiation ||
16466         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16467 
16468     if (TryInstantiating) {
16469       SourceLocation PointOfInstantiation =
16470           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16471       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16472       if (FirstInstantiation) {
16473         PointOfInstantiation = Loc;
16474         if (MSI)
16475           MSI->setPointOfInstantiation(PointOfInstantiation);
16476         else
16477           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16478       }
16479 
16480       bool InstantiationDependent = false;
16481       bool IsNonDependent =
16482           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16483                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16484                   : true;
16485 
16486       // Do not instantiate specializations that are still type-dependent.
16487       if (IsNonDependent) {
16488         if (UsableInConstantExpr) {
16489           // Do not defer instantiations of variables that could be used in a
16490           // constant expression.
16491           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16492         } else if (FirstInstantiation ||
16493                    isa<VarTemplateSpecializationDecl>(Var)) {
16494           // FIXME: For a specialization of a variable template, we don't
16495           // distinguish between "declaration and type implicitly instantiated"
16496           // and "implicit instantiation of definition requested", so we have
16497           // no direct way to avoid enqueueing the pending instantiation
16498           // multiple times.
16499           SemaRef.PendingInstantiations
16500               .push_back(std::make_pair(Var, PointOfInstantiation));
16501         }
16502       }
16503     }
16504   }
16505 
16506   // C++2a [basic.def.odr]p4:
16507   //   A variable x whose name appears as a potentially-evaluated expression e
16508   //   is odr-used by e unless
16509   //   -- x is a reference that is usable in constant expressions
16510   //   -- x is a variable of non-reference type that is usable in constant
16511   //      expressions and has no mutable subobjects [FIXME], and e is an
16512   //      element of the set of potential results of an expression of
16513   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16514   //      conversion is applied
16515   //   -- x is a variable of non-reference type, and e is an element of the set
16516   //      of potential results of a discarded-value expression to which the
16517   //      lvalue-to-rvalue conversion is not applied [FIXME]
16518   //
16519   // We check the first part of the second bullet here, and
16520   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16521   // FIXME: To get the third bullet right, we need to delay this even for
16522   // variables that are not usable in constant expressions.
16523 
16524   // If we already know this isn't an odr-use, there's nothing more to do.
16525   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16526     if (DRE->isNonOdrUse())
16527       return;
16528   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16529     if (ME->isNonOdrUse())
16530       return;
16531 
16532   switch (OdrUse) {
16533   case OdrUseContext::None:
16534     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16535            "missing non-odr-use marking for unevaluated decl ref");
16536     break;
16537 
16538   case OdrUseContext::FormallyOdrUsed:
16539     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16540     // behavior.
16541     break;
16542 
16543   case OdrUseContext::Used:
16544     // If we might later find that this expression isn't actually an odr-use,
16545     // delay the marking.
16546     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16547       SemaRef.MaybeODRUseExprs.insert(E);
16548     else
16549       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16550     break;
16551 
16552   case OdrUseContext::Dependent:
16553     // If this is a dependent context, we don't need to mark variables as
16554     // odr-used, but we may still need to track them for lambda capture.
16555     // FIXME: Do we also need to do this inside dependent typeid expressions
16556     // (which are modeled as unevaluated at this point)?
16557     const bool RefersToEnclosingScope =
16558         (SemaRef.CurContext != Var->getDeclContext() &&
16559          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16560     if (RefersToEnclosingScope) {
16561       LambdaScopeInfo *const LSI =
16562           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16563       if (LSI && (!LSI->CallOperator ||
16564                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16565         // If a variable could potentially be odr-used, defer marking it so
16566         // until we finish analyzing the full expression for any
16567         // lvalue-to-rvalue
16568         // or discarded value conversions that would obviate odr-use.
16569         // Add it to the list of potential captures that will be analyzed
16570         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16571         // unless the variable is a reference that was initialized by a constant
16572         // expression (this will never need to be captured or odr-used).
16573         //
16574         // FIXME: We can simplify this a lot after implementing P0588R1.
16575         assert(E && "Capture variable should be used in an expression.");
16576         if (!Var->getType()->isReferenceType() ||
16577             !Var->isUsableInConstantExpressions(SemaRef.Context))
16578           LSI->addPotentialCapture(E->IgnoreParens());
16579       }
16580     }
16581     break;
16582   }
16583 }
16584 
16585 /// Mark a variable referenced, and check whether it is odr-used
16586 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16587 /// used directly for normal expressions referring to VarDecl.
16588 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16589   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16590 }
16591 
16592 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16593                                Decl *D, Expr *E, bool MightBeOdrUse) {
16594   if (SemaRef.isInOpenMPDeclareTargetContext())
16595     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16596 
16597   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16598     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16599     return;
16600   }
16601 
16602   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16603 
16604   // If this is a call to a method via a cast, also mark the method in the
16605   // derived class used in case codegen can devirtualize the call.
16606   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16607   if (!ME)
16608     return;
16609   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16610   if (!MD)
16611     return;
16612   // Only attempt to devirtualize if this is truly a virtual call.
16613   bool IsVirtualCall = MD->isVirtual() &&
16614                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16615   if (!IsVirtualCall)
16616     return;
16617 
16618   // If it's possible to devirtualize the call, mark the called function
16619   // referenced.
16620   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16621       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16622   if (DM)
16623     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16624 }
16625 
16626 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16627 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16628   // TODO: update this with DR# once a defect report is filed.
16629   // C++11 defect. The address of a pure member should not be an ODR use, even
16630   // if it's a qualified reference.
16631   bool OdrUse = true;
16632   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16633     if (Method->isVirtual() &&
16634         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16635       OdrUse = false;
16636   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16637 }
16638 
16639 /// Perform reference-marking and odr-use handling for a MemberExpr.
16640 void Sema::MarkMemberReferenced(MemberExpr *E) {
16641   // C++11 [basic.def.odr]p2:
16642   //   A non-overloaded function whose name appears as a potentially-evaluated
16643   //   expression or a member of a set of candidate functions, if selected by
16644   //   overload resolution when referred to from a potentially-evaluated
16645   //   expression, is odr-used, unless it is a pure virtual function and its
16646   //   name is not explicitly qualified.
16647   bool MightBeOdrUse = true;
16648   if (E->performsVirtualDispatch(getLangOpts())) {
16649     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16650       if (Method->isPure())
16651         MightBeOdrUse = false;
16652   }
16653   SourceLocation Loc =
16654       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16655   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16656 }
16657 
16658 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16659 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16660   for (VarDecl *VD : *E)
16661     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16662 }
16663 
16664 /// Perform marking for a reference to an arbitrary declaration.  It
16665 /// marks the declaration referenced, and performs odr-use checking for
16666 /// functions and variables. This method should not be used when building a
16667 /// normal expression which refers to a variable.
16668 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16669                                  bool MightBeOdrUse) {
16670   if (MightBeOdrUse) {
16671     if (auto *VD = dyn_cast<VarDecl>(D)) {
16672       MarkVariableReferenced(Loc, VD);
16673       return;
16674     }
16675   }
16676   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16677     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16678     return;
16679   }
16680   D->setReferenced();
16681 }
16682 
16683 namespace {
16684   // Mark all of the declarations used by a type as referenced.
16685   // FIXME: Not fully implemented yet! We need to have a better understanding
16686   // of when we're entering a context we should not recurse into.
16687   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16688   // TreeTransforms rebuilding the type in a new context. Rather than
16689   // duplicating the TreeTransform logic, we should consider reusing it here.
16690   // Currently that causes problems when rebuilding LambdaExprs.
16691   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16692     Sema &S;
16693     SourceLocation Loc;
16694 
16695   public:
16696     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16697 
16698     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16699 
16700     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16701   };
16702 }
16703 
16704 bool MarkReferencedDecls::TraverseTemplateArgument(
16705     const TemplateArgument &Arg) {
16706   {
16707     // A non-type template argument is a constant-evaluated context.
16708     EnterExpressionEvaluationContext Evaluated(
16709         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16710     if (Arg.getKind() == TemplateArgument::Declaration) {
16711       if (Decl *D = Arg.getAsDecl())
16712         S.MarkAnyDeclReferenced(Loc, D, true);
16713     } else if (Arg.getKind() == TemplateArgument::Expression) {
16714       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16715     }
16716   }
16717 
16718   return Inherited::TraverseTemplateArgument(Arg);
16719 }
16720 
16721 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16722   MarkReferencedDecls Marker(*this, Loc);
16723   Marker.TraverseType(T);
16724 }
16725 
16726 namespace {
16727   /// Helper class that marks all of the declarations referenced by
16728   /// potentially-evaluated subexpressions as "referenced".
16729   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16730     Sema &S;
16731     bool SkipLocalVariables;
16732 
16733   public:
16734     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16735 
16736     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16737       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16738 
16739     void VisitDeclRefExpr(DeclRefExpr *E) {
16740       // If we were asked not to visit local variables, don't.
16741       if (SkipLocalVariables) {
16742         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16743           if (VD->hasLocalStorage())
16744             return;
16745       }
16746 
16747       S.MarkDeclRefReferenced(E);
16748     }
16749 
16750     void VisitMemberExpr(MemberExpr *E) {
16751       S.MarkMemberReferenced(E);
16752       Inherited::VisitMemberExpr(E);
16753     }
16754 
16755     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16756       S.MarkFunctionReferenced(
16757           E->getBeginLoc(),
16758           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16759       Visit(E->getSubExpr());
16760     }
16761 
16762     void VisitCXXNewExpr(CXXNewExpr *E) {
16763       if (E->getOperatorNew())
16764         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16765       if (E->getOperatorDelete())
16766         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16767       Inherited::VisitCXXNewExpr(E);
16768     }
16769 
16770     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16771       if (E->getOperatorDelete())
16772         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16773       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16774       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16775         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16776         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16777       }
16778 
16779       Inherited::VisitCXXDeleteExpr(E);
16780     }
16781 
16782     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16783       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16784       Inherited::VisitCXXConstructExpr(E);
16785     }
16786 
16787     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16788       Visit(E->getExpr());
16789     }
16790   };
16791 }
16792 
16793 /// Mark any declarations that appear within this expression or any
16794 /// potentially-evaluated subexpressions as "referenced".
16795 ///
16796 /// \param SkipLocalVariables If true, don't mark local variables as
16797 /// 'referenced'.
16798 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16799                                             bool SkipLocalVariables) {
16800   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16801 }
16802 
16803 /// Emit a diagnostic that describes an effect on the run-time behavior
16804 /// of the program being compiled.
16805 ///
16806 /// This routine emits the given diagnostic when the code currently being
16807 /// type-checked is "potentially evaluated", meaning that there is a
16808 /// possibility that the code will actually be executable. Code in sizeof()
16809 /// expressions, code used only during overload resolution, etc., are not
16810 /// potentially evaluated. This routine will suppress such diagnostics or,
16811 /// in the absolutely nutty case of potentially potentially evaluated
16812 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16813 /// later.
16814 ///
16815 /// This routine should be used for all diagnostics that describe the run-time
16816 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16817 /// Failure to do so will likely result in spurious diagnostics or failures
16818 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16819 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16820                                const PartialDiagnostic &PD) {
16821   switch (ExprEvalContexts.back().Context) {
16822   case ExpressionEvaluationContext::Unevaluated:
16823   case ExpressionEvaluationContext::UnevaluatedList:
16824   case ExpressionEvaluationContext::UnevaluatedAbstract:
16825   case ExpressionEvaluationContext::DiscardedStatement:
16826     // The argument will never be evaluated, so don't complain.
16827     break;
16828 
16829   case ExpressionEvaluationContext::ConstantEvaluated:
16830     // Relevant diagnostics should be produced by constant evaluation.
16831     break;
16832 
16833   case ExpressionEvaluationContext::PotentiallyEvaluated:
16834   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16835     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16836       FunctionScopes.back()->PossiblyUnreachableDiags.
16837         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16838       return true;
16839     }
16840 
16841     // The initializer of a constexpr variable or of the first declaration of a
16842     // static data member is not syntactically a constant evaluated constant,
16843     // but nonetheless is always required to be a constant expression, so we
16844     // can skip diagnosing.
16845     // FIXME: Using the mangling context here is a hack.
16846     if (auto *VD = dyn_cast_or_null<VarDecl>(
16847             ExprEvalContexts.back().ManglingContextDecl)) {
16848       if (VD->isConstexpr() ||
16849           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16850         break;
16851       // FIXME: For any other kind of variable, we should build a CFG for its
16852       // initializer and check whether the context in question is reachable.
16853     }
16854 
16855     Diag(Loc, PD);
16856     return true;
16857   }
16858 
16859   return false;
16860 }
16861 
16862 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16863                                const PartialDiagnostic &PD) {
16864   return DiagRuntimeBehavior(
16865       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
16866 }
16867 
16868 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16869                                CallExpr *CE, FunctionDecl *FD) {
16870   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16871     return false;
16872 
16873   // If we're inside a decltype's expression, don't check for a valid return
16874   // type or construct temporaries until we know whether this is the last call.
16875   if (ExprEvalContexts.back().ExprContext ==
16876       ExpressionEvaluationContextRecord::EK_Decltype) {
16877     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16878     return false;
16879   }
16880 
16881   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16882     FunctionDecl *FD;
16883     CallExpr *CE;
16884 
16885   public:
16886     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16887       : FD(FD), CE(CE) { }
16888 
16889     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16890       if (!FD) {
16891         S.Diag(Loc, diag::err_call_incomplete_return)
16892           << T << CE->getSourceRange();
16893         return;
16894       }
16895 
16896       S.Diag(Loc, diag::err_call_function_incomplete_return)
16897         << CE->getSourceRange() << FD->getDeclName() << T;
16898       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16899           << FD->getDeclName();
16900     }
16901   } Diagnoser(FD, CE);
16902 
16903   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16904     return true;
16905 
16906   return false;
16907 }
16908 
16909 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16910 // will prevent this condition from triggering, which is what we want.
16911 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16912   SourceLocation Loc;
16913 
16914   unsigned diagnostic = diag::warn_condition_is_assignment;
16915   bool IsOrAssign = false;
16916 
16917   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16918     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16919       return;
16920 
16921     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16922 
16923     // Greylist some idioms by putting them into a warning subcategory.
16924     if (ObjCMessageExpr *ME
16925           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16926       Selector Sel = ME->getSelector();
16927 
16928       // self = [<foo> init...]
16929       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16930         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16931 
16932       // <foo> = [<bar> nextObject]
16933       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16934         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16935     }
16936 
16937     Loc = Op->getOperatorLoc();
16938   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16939     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16940       return;
16941 
16942     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16943     Loc = Op->getOperatorLoc();
16944   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16945     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16946   else {
16947     // Not an assignment.
16948     return;
16949   }
16950 
16951   Diag(Loc, diagnostic) << E->getSourceRange();
16952 
16953   SourceLocation Open = E->getBeginLoc();
16954   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16955   Diag(Loc, diag::note_condition_assign_silence)
16956         << FixItHint::CreateInsertion(Open, "(")
16957         << FixItHint::CreateInsertion(Close, ")");
16958 
16959   if (IsOrAssign)
16960     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16961       << FixItHint::CreateReplacement(Loc, "!=");
16962   else
16963     Diag(Loc, diag::note_condition_assign_to_comparison)
16964       << FixItHint::CreateReplacement(Loc, "==");
16965 }
16966 
16967 /// Redundant parentheses over an equality comparison can indicate
16968 /// that the user intended an assignment used as condition.
16969 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16970   // Don't warn if the parens came from a macro.
16971   SourceLocation parenLoc = ParenE->getBeginLoc();
16972   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16973     return;
16974   // Don't warn for dependent expressions.
16975   if (ParenE->isTypeDependent())
16976     return;
16977 
16978   Expr *E = ParenE->IgnoreParens();
16979 
16980   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16981     if (opE->getOpcode() == BO_EQ &&
16982         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16983                                                            == Expr::MLV_Valid) {
16984       SourceLocation Loc = opE->getOperatorLoc();
16985 
16986       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16987       SourceRange ParenERange = ParenE->getSourceRange();
16988       Diag(Loc, diag::note_equality_comparison_silence)
16989         << FixItHint::CreateRemoval(ParenERange.getBegin())
16990         << FixItHint::CreateRemoval(ParenERange.getEnd());
16991       Diag(Loc, diag::note_equality_comparison_to_assign)
16992         << FixItHint::CreateReplacement(Loc, "=");
16993     }
16994 }
16995 
16996 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16997                                        bool IsConstexpr) {
16998   DiagnoseAssignmentAsCondition(E);
16999   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17000     DiagnoseEqualityWithExtraParens(parenE);
17001 
17002   ExprResult result = CheckPlaceholderExpr(E);
17003   if (result.isInvalid()) return ExprError();
17004   E = result.get();
17005 
17006   if (!E->isTypeDependent()) {
17007     if (getLangOpts().CPlusPlus)
17008       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17009 
17010     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17011     if (ERes.isInvalid())
17012       return ExprError();
17013     E = ERes.get();
17014 
17015     QualType T = E->getType();
17016     if (!T->isScalarType()) { // C99 6.8.4.1p1
17017       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17018         << T << E->getSourceRange();
17019       return ExprError();
17020     }
17021     CheckBoolLikeConversion(E, Loc);
17022   }
17023 
17024   return E;
17025 }
17026 
17027 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17028                                            Expr *SubExpr, ConditionKind CK) {
17029   // Empty conditions are valid in for-statements.
17030   if (!SubExpr)
17031     return ConditionResult();
17032 
17033   ExprResult Cond;
17034   switch (CK) {
17035   case ConditionKind::Boolean:
17036     Cond = CheckBooleanCondition(Loc, SubExpr);
17037     break;
17038 
17039   case ConditionKind::ConstexprIf:
17040     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17041     break;
17042 
17043   case ConditionKind::Switch:
17044     Cond = CheckSwitchCondition(Loc, SubExpr);
17045     break;
17046   }
17047   if (Cond.isInvalid())
17048     return ConditionError();
17049 
17050   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17051   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17052   if (!FullExpr.get())
17053     return ConditionError();
17054 
17055   return ConditionResult(*this, nullptr, FullExpr,
17056                          CK == ConditionKind::ConstexprIf);
17057 }
17058 
17059 namespace {
17060   /// A visitor for rebuilding a call to an __unknown_any expression
17061   /// to have an appropriate type.
17062   struct RebuildUnknownAnyFunction
17063     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17064 
17065     Sema &S;
17066 
17067     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17068 
17069     ExprResult VisitStmt(Stmt *S) {
17070       llvm_unreachable("unexpected statement!");
17071     }
17072 
17073     ExprResult VisitExpr(Expr *E) {
17074       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17075         << E->getSourceRange();
17076       return ExprError();
17077     }
17078 
17079     /// Rebuild an expression which simply semantically wraps another
17080     /// expression which it shares the type and value kind of.
17081     template <class T> ExprResult rebuildSugarExpr(T *E) {
17082       ExprResult SubResult = Visit(E->getSubExpr());
17083       if (SubResult.isInvalid()) return ExprError();
17084 
17085       Expr *SubExpr = SubResult.get();
17086       E->setSubExpr(SubExpr);
17087       E->setType(SubExpr->getType());
17088       E->setValueKind(SubExpr->getValueKind());
17089       assert(E->getObjectKind() == OK_Ordinary);
17090       return E;
17091     }
17092 
17093     ExprResult VisitParenExpr(ParenExpr *E) {
17094       return rebuildSugarExpr(E);
17095     }
17096 
17097     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17098       return rebuildSugarExpr(E);
17099     }
17100 
17101     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17102       ExprResult SubResult = Visit(E->getSubExpr());
17103       if (SubResult.isInvalid()) return ExprError();
17104 
17105       Expr *SubExpr = SubResult.get();
17106       E->setSubExpr(SubExpr);
17107       E->setType(S.Context.getPointerType(SubExpr->getType()));
17108       assert(E->getValueKind() == VK_RValue);
17109       assert(E->getObjectKind() == OK_Ordinary);
17110       return E;
17111     }
17112 
17113     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17114       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17115 
17116       E->setType(VD->getType());
17117 
17118       assert(E->getValueKind() == VK_RValue);
17119       if (S.getLangOpts().CPlusPlus &&
17120           !(isa<CXXMethodDecl>(VD) &&
17121             cast<CXXMethodDecl>(VD)->isInstance()))
17122         E->setValueKind(VK_LValue);
17123 
17124       return E;
17125     }
17126 
17127     ExprResult VisitMemberExpr(MemberExpr *E) {
17128       return resolveDecl(E, E->getMemberDecl());
17129     }
17130 
17131     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17132       return resolveDecl(E, E->getDecl());
17133     }
17134   };
17135 }
17136 
17137 /// Given a function expression of unknown-any type, try to rebuild it
17138 /// to have a function type.
17139 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17140   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17141   if (Result.isInvalid()) return ExprError();
17142   return S.DefaultFunctionArrayConversion(Result.get());
17143 }
17144 
17145 namespace {
17146   /// A visitor for rebuilding an expression of type __unknown_anytype
17147   /// into one which resolves the type directly on the referring
17148   /// expression.  Strict preservation of the original source
17149   /// structure is not a goal.
17150   struct RebuildUnknownAnyExpr
17151     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17152 
17153     Sema &S;
17154 
17155     /// The current destination type.
17156     QualType DestType;
17157 
17158     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17159       : S(S), DestType(CastType) {}
17160 
17161     ExprResult VisitStmt(Stmt *S) {
17162       llvm_unreachable("unexpected statement!");
17163     }
17164 
17165     ExprResult VisitExpr(Expr *E) {
17166       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17167         << E->getSourceRange();
17168       return ExprError();
17169     }
17170 
17171     ExprResult VisitCallExpr(CallExpr *E);
17172     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17173 
17174     /// Rebuild an expression which simply semantically wraps another
17175     /// expression which it shares the type and value kind of.
17176     template <class T> ExprResult rebuildSugarExpr(T *E) {
17177       ExprResult SubResult = Visit(E->getSubExpr());
17178       if (SubResult.isInvalid()) return ExprError();
17179       Expr *SubExpr = SubResult.get();
17180       E->setSubExpr(SubExpr);
17181       E->setType(SubExpr->getType());
17182       E->setValueKind(SubExpr->getValueKind());
17183       assert(E->getObjectKind() == OK_Ordinary);
17184       return E;
17185     }
17186 
17187     ExprResult VisitParenExpr(ParenExpr *E) {
17188       return rebuildSugarExpr(E);
17189     }
17190 
17191     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17192       return rebuildSugarExpr(E);
17193     }
17194 
17195     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17196       const PointerType *Ptr = DestType->getAs<PointerType>();
17197       if (!Ptr) {
17198         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17199           << E->getSourceRange();
17200         return ExprError();
17201       }
17202 
17203       if (isa<CallExpr>(E->getSubExpr())) {
17204         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17205           << E->getSourceRange();
17206         return ExprError();
17207       }
17208 
17209       assert(E->getValueKind() == VK_RValue);
17210       assert(E->getObjectKind() == OK_Ordinary);
17211       E->setType(DestType);
17212 
17213       // Build the sub-expression as if it were an object of the pointee type.
17214       DestType = Ptr->getPointeeType();
17215       ExprResult SubResult = Visit(E->getSubExpr());
17216       if (SubResult.isInvalid()) return ExprError();
17217       E->setSubExpr(SubResult.get());
17218       return E;
17219     }
17220 
17221     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17222 
17223     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17224 
17225     ExprResult VisitMemberExpr(MemberExpr *E) {
17226       return resolveDecl(E, E->getMemberDecl());
17227     }
17228 
17229     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17230       return resolveDecl(E, E->getDecl());
17231     }
17232   };
17233 }
17234 
17235 /// Rebuilds a call expression which yielded __unknown_anytype.
17236 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17237   Expr *CalleeExpr = E->getCallee();
17238 
17239   enum FnKind {
17240     FK_MemberFunction,
17241     FK_FunctionPointer,
17242     FK_BlockPointer
17243   };
17244 
17245   FnKind Kind;
17246   QualType CalleeType = CalleeExpr->getType();
17247   if (CalleeType == S.Context.BoundMemberTy) {
17248     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17249     Kind = FK_MemberFunction;
17250     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17251   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17252     CalleeType = Ptr->getPointeeType();
17253     Kind = FK_FunctionPointer;
17254   } else {
17255     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17256     Kind = FK_BlockPointer;
17257   }
17258   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17259 
17260   // Verify that this is a legal result type of a function.
17261   if (DestType->isArrayType() || DestType->isFunctionType()) {
17262     unsigned diagID = diag::err_func_returning_array_function;
17263     if (Kind == FK_BlockPointer)
17264       diagID = diag::err_block_returning_array_function;
17265 
17266     S.Diag(E->getExprLoc(), diagID)
17267       << DestType->isFunctionType() << DestType;
17268     return ExprError();
17269   }
17270 
17271   // Otherwise, go ahead and set DestType as the call's result.
17272   E->setType(DestType.getNonLValueExprType(S.Context));
17273   E->setValueKind(Expr::getValueKindForType(DestType));
17274   assert(E->getObjectKind() == OK_Ordinary);
17275 
17276   // Rebuild the function type, replacing the result type with DestType.
17277   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17278   if (Proto) {
17279     // __unknown_anytype(...) is a special case used by the debugger when
17280     // it has no idea what a function's signature is.
17281     //
17282     // We want to build this call essentially under the K&R
17283     // unprototyped rules, but making a FunctionNoProtoType in C++
17284     // would foul up all sorts of assumptions.  However, we cannot
17285     // simply pass all arguments as variadic arguments, nor can we
17286     // portably just call the function under a non-variadic type; see
17287     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17288     // However, it turns out that in practice it is generally safe to
17289     // call a function declared as "A foo(B,C,D);" under the prototype
17290     // "A foo(B,C,D,...);".  The only known exception is with the
17291     // Windows ABI, where any variadic function is implicitly cdecl
17292     // regardless of its normal CC.  Therefore we change the parameter
17293     // types to match the types of the arguments.
17294     //
17295     // This is a hack, but it is far superior to moving the
17296     // corresponding target-specific code from IR-gen to Sema/AST.
17297 
17298     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17299     SmallVector<QualType, 8> ArgTypes;
17300     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17301       ArgTypes.reserve(E->getNumArgs());
17302       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17303         Expr *Arg = E->getArg(i);
17304         QualType ArgType = Arg->getType();
17305         if (E->isLValue()) {
17306           ArgType = S.Context.getLValueReferenceType(ArgType);
17307         } else if (E->isXValue()) {
17308           ArgType = S.Context.getRValueReferenceType(ArgType);
17309         }
17310         ArgTypes.push_back(ArgType);
17311       }
17312       ParamTypes = ArgTypes;
17313     }
17314     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17315                                          Proto->getExtProtoInfo());
17316   } else {
17317     DestType = S.Context.getFunctionNoProtoType(DestType,
17318                                                 FnType->getExtInfo());
17319   }
17320 
17321   // Rebuild the appropriate pointer-to-function type.
17322   switch (Kind) {
17323   case FK_MemberFunction:
17324     // Nothing to do.
17325     break;
17326 
17327   case FK_FunctionPointer:
17328     DestType = S.Context.getPointerType(DestType);
17329     break;
17330 
17331   case FK_BlockPointer:
17332     DestType = S.Context.getBlockPointerType(DestType);
17333     break;
17334   }
17335 
17336   // Finally, we can recurse.
17337   ExprResult CalleeResult = Visit(CalleeExpr);
17338   if (!CalleeResult.isUsable()) return ExprError();
17339   E->setCallee(CalleeResult.get());
17340 
17341   // Bind a temporary if necessary.
17342   return S.MaybeBindToTemporary(E);
17343 }
17344 
17345 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17346   // Verify that this is a legal result type of a call.
17347   if (DestType->isArrayType() || DestType->isFunctionType()) {
17348     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17349       << DestType->isFunctionType() << DestType;
17350     return ExprError();
17351   }
17352 
17353   // Rewrite the method result type if available.
17354   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17355     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17356     Method->setReturnType(DestType);
17357   }
17358 
17359   // Change the type of the message.
17360   E->setType(DestType.getNonReferenceType());
17361   E->setValueKind(Expr::getValueKindForType(DestType));
17362 
17363   return S.MaybeBindToTemporary(E);
17364 }
17365 
17366 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17367   // The only case we should ever see here is a function-to-pointer decay.
17368   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17369     assert(E->getValueKind() == VK_RValue);
17370     assert(E->getObjectKind() == OK_Ordinary);
17371 
17372     E->setType(DestType);
17373 
17374     // Rebuild the sub-expression as the pointee (function) type.
17375     DestType = DestType->castAs<PointerType>()->getPointeeType();
17376 
17377     ExprResult Result = Visit(E->getSubExpr());
17378     if (!Result.isUsable()) return ExprError();
17379 
17380     E->setSubExpr(Result.get());
17381     return E;
17382   } else if (E->getCastKind() == CK_LValueToRValue) {
17383     assert(E->getValueKind() == VK_RValue);
17384     assert(E->getObjectKind() == OK_Ordinary);
17385 
17386     assert(isa<BlockPointerType>(E->getType()));
17387 
17388     E->setType(DestType);
17389 
17390     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17391     DestType = S.Context.getLValueReferenceType(DestType);
17392 
17393     ExprResult Result = Visit(E->getSubExpr());
17394     if (!Result.isUsable()) return ExprError();
17395 
17396     E->setSubExpr(Result.get());
17397     return E;
17398   } else {
17399     llvm_unreachable("Unhandled cast type!");
17400   }
17401 }
17402 
17403 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17404   ExprValueKind ValueKind = VK_LValue;
17405   QualType Type = DestType;
17406 
17407   // We know how to make this work for certain kinds of decls:
17408 
17409   //  - functions
17410   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17411     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17412       DestType = Ptr->getPointeeType();
17413       ExprResult Result = resolveDecl(E, VD);
17414       if (Result.isInvalid()) return ExprError();
17415       return S.ImpCastExprToType(Result.get(), Type,
17416                                  CK_FunctionToPointerDecay, VK_RValue);
17417     }
17418 
17419     if (!Type->isFunctionType()) {
17420       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17421         << VD << E->getSourceRange();
17422       return ExprError();
17423     }
17424     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17425       // We must match the FunctionDecl's type to the hack introduced in
17426       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17427       // type. See the lengthy commentary in that routine.
17428       QualType FDT = FD->getType();
17429       const FunctionType *FnType = FDT->castAs<FunctionType>();
17430       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17431       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17432       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17433         SourceLocation Loc = FD->getLocation();
17434         FunctionDecl *NewFD = FunctionDecl::Create(
17435             S.Context, FD->getDeclContext(), Loc, Loc,
17436             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17437             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17438             /*ConstexprKind*/ CSK_unspecified);
17439 
17440         if (FD->getQualifier())
17441           NewFD->setQualifierInfo(FD->getQualifierLoc());
17442 
17443         SmallVector<ParmVarDecl*, 16> Params;
17444         for (const auto &AI : FT->param_types()) {
17445           ParmVarDecl *Param =
17446             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17447           Param->setScopeInfo(0, Params.size());
17448           Params.push_back(Param);
17449         }
17450         NewFD->setParams(Params);
17451         DRE->setDecl(NewFD);
17452         VD = DRE->getDecl();
17453       }
17454     }
17455 
17456     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17457       if (MD->isInstance()) {
17458         ValueKind = VK_RValue;
17459         Type = S.Context.BoundMemberTy;
17460       }
17461 
17462     // Function references aren't l-values in C.
17463     if (!S.getLangOpts().CPlusPlus)
17464       ValueKind = VK_RValue;
17465 
17466   //  - variables
17467   } else if (isa<VarDecl>(VD)) {
17468     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17469       Type = RefTy->getPointeeType();
17470     } else if (Type->isFunctionType()) {
17471       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17472         << VD << E->getSourceRange();
17473       return ExprError();
17474     }
17475 
17476   //  - nothing else
17477   } else {
17478     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17479       << VD << E->getSourceRange();
17480     return ExprError();
17481   }
17482 
17483   // Modifying the declaration like this is friendly to IR-gen but
17484   // also really dangerous.
17485   VD->setType(DestType);
17486   E->setType(Type);
17487   E->setValueKind(ValueKind);
17488   return E;
17489 }
17490 
17491 /// Check a cast of an unknown-any type.  We intentionally only
17492 /// trigger this for C-style casts.
17493 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17494                                      Expr *CastExpr, CastKind &CastKind,
17495                                      ExprValueKind &VK, CXXCastPath &Path) {
17496   // The type we're casting to must be either void or complete.
17497   if (!CastType->isVoidType() &&
17498       RequireCompleteType(TypeRange.getBegin(), CastType,
17499                           diag::err_typecheck_cast_to_incomplete))
17500     return ExprError();
17501 
17502   // Rewrite the casted expression from scratch.
17503   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17504   if (!result.isUsable()) return ExprError();
17505 
17506   CastExpr = result.get();
17507   VK = CastExpr->getValueKind();
17508   CastKind = CK_NoOp;
17509 
17510   return CastExpr;
17511 }
17512 
17513 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17514   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17515 }
17516 
17517 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17518                                     Expr *arg, QualType &paramType) {
17519   // If the syntactic form of the argument is not an explicit cast of
17520   // any sort, just do default argument promotion.
17521   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17522   if (!castArg) {
17523     ExprResult result = DefaultArgumentPromotion(arg);
17524     if (result.isInvalid()) return ExprError();
17525     paramType = result.get()->getType();
17526     return result;
17527   }
17528 
17529   // Otherwise, use the type that was written in the explicit cast.
17530   assert(!arg->hasPlaceholderType());
17531   paramType = castArg->getTypeAsWritten();
17532 
17533   // Copy-initialize a parameter of that type.
17534   InitializedEntity entity =
17535     InitializedEntity::InitializeParameter(Context, paramType,
17536                                            /*consumed*/ false);
17537   return PerformCopyInitialization(entity, callLoc, arg);
17538 }
17539 
17540 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17541   Expr *orig = E;
17542   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17543   while (true) {
17544     E = E->IgnoreParenImpCasts();
17545     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17546       E = call->getCallee();
17547       diagID = diag::err_uncasted_call_of_unknown_any;
17548     } else {
17549       break;
17550     }
17551   }
17552 
17553   SourceLocation loc;
17554   NamedDecl *d;
17555   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17556     loc = ref->getLocation();
17557     d = ref->getDecl();
17558   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17559     loc = mem->getMemberLoc();
17560     d = mem->getMemberDecl();
17561   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17562     diagID = diag::err_uncasted_call_of_unknown_any;
17563     loc = msg->getSelectorStartLoc();
17564     d = msg->getMethodDecl();
17565     if (!d) {
17566       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17567         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17568         << orig->getSourceRange();
17569       return ExprError();
17570     }
17571   } else {
17572     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17573       << E->getSourceRange();
17574     return ExprError();
17575   }
17576 
17577   S.Diag(loc, diagID) << d << orig->getSourceRange();
17578 
17579   // Never recoverable.
17580   return ExprError();
17581 }
17582 
17583 /// Check for operands with placeholder types and complain if found.
17584 /// Returns ExprError() if there was an error and no recovery was possible.
17585 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17586   if (!getLangOpts().CPlusPlus) {
17587     // C cannot handle TypoExpr nodes on either side of a binop because it
17588     // doesn't handle dependent types properly, so make sure any TypoExprs have
17589     // been dealt with before checking the operands.
17590     ExprResult Result = CorrectDelayedTyposInExpr(E);
17591     if (!Result.isUsable()) return ExprError();
17592     E = Result.get();
17593   }
17594 
17595   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17596   if (!placeholderType) return E;
17597 
17598   switch (placeholderType->getKind()) {
17599 
17600   // Overloaded expressions.
17601   case BuiltinType::Overload: {
17602     // Try to resolve a single function template specialization.
17603     // This is obligatory.
17604     ExprResult Result = E;
17605     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17606       return Result;
17607 
17608     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17609     // leaves Result unchanged on failure.
17610     Result = E;
17611     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17612       return Result;
17613 
17614     // If that failed, try to recover with a call.
17615     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17616                          /*complain*/ true);
17617     return Result;
17618   }
17619 
17620   // Bound member functions.
17621   case BuiltinType::BoundMember: {
17622     ExprResult result = E;
17623     const Expr *BME = E->IgnoreParens();
17624     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17625     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17626     if (isa<CXXPseudoDestructorExpr>(BME)) {
17627       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17628     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17629       if (ME->getMemberNameInfo().getName().getNameKind() ==
17630           DeclarationName::CXXDestructorName)
17631         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17632     }
17633     tryToRecoverWithCall(result, PD,
17634                          /*complain*/ true);
17635     return result;
17636   }
17637 
17638   // ARC unbridged casts.
17639   case BuiltinType::ARCUnbridgedCast: {
17640     Expr *realCast = stripARCUnbridgedCast(E);
17641     diagnoseARCUnbridgedCast(realCast);
17642     return realCast;
17643   }
17644 
17645   // Expressions of unknown type.
17646   case BuiltinType::UnknownAny:
17647     return diagnoseUnknownAnyExpr(*this, E);
17648 
17649   // Pseudo-objects.
17650   case BuiltinType::PseudoObject:
17651     return checkPseudoObjectRValue(E);
17652 
17653   case BuiltinType::BuiltinFn: {
17654     // Accept __noop without parens by implicitly converting it to a call expr.
17655     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17656     if (DRE) {
17657       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17658       if (FD->getBuiltinID() == Builtin::BI__noop) {
17659         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17660                               CK_BuiltinFnToFnPtr)
17661                 .get();
17662         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17663                                 VK_RValue, SourceLocation());
17664       }
17665     }
17666 
17667     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17668     return ExprError();
17669   }
17670 
17671   // Expressions of unknown type.
17672   case BuiltinType::OMPArraySection:
17673     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17674     return ExprError();
17675 
17676   // Everything else should be impossible.
17677 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17678   case BuiltinType::Id:
17679 #include "clang/Basic/OpenCLImageTypes.def"
17680 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17681   case BuiltinType::Id:
17682 #include "clang/Basic/OpenCLExtensionTypes.def"
17683 #define SVE_TYPE(Name, Id, SingletonId) \
17684   case BuiltinType::Id:
17685 #include "clang/Basic/AArch64SVEACLETypes.def"
17686 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17687 #define PLACEHOLDER_TYPE(Id, SingletonId)
17688 #include "clang/AST/BuiltinTypes.def"
17689     break;
17690   }
17691 
17692   llvm_unreachable("invalid placeholder type!");
17693 }
17694 
17695 bool Sema::CheckCaseExpression(Expr *E) {
17696   if (E->isTypeDependent())
17697     return true;
17698   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17699     return E->getType()->isIntegralOrEnumerationType();
17700   return false;
17701 }
17702 
17703 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17704 ExprResult
17705 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17706   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17707          "Unknown Objective-C Boolean value!");
17708   QualType BoolT = Context.ObjCBuiltinBoolTy;
17709   if (!Context.getBOOLDecl()) {
17710     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17711                         Sema::LookupOrdinaryName);
17712     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17713       NamedDecl *ND = Result.getFoundDecl();
17714       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17715         Context.setBOOLDecl(TD);
17716     }
17717   }
17718   if (Context.getBOOLDecl())
17719     BoolT = Context.getBOOLType();
17720   return new (Context)
17721       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17722 }
17723 
17724 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17725     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17726     SourceLocation RParen) {
17727 
17728   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17729 
17730   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17731     return Spec.getPlatform() == Platform;
17732   });
17733 
17734   VersionTuple Version;
17735   if (Spec != AvailSpecs.end())
17736     Version = Spec->getVersion();
17737 
17738   // The use of `@available` in the enclosing function should be analyzed to
17739   // warn when it's used inappropriately (i.e. not if(@available)).
17740   if (getCurFunctionOrMethodDecl())
17741     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17742   else if (getCurBlock() || getCurLambda())
17743     getCurFunction()->HasPotentialAvailabilityViolations = true;
17744 
17745   return new (Context)
17746       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17747 }