1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/FixedPoint.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51 
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55   // See if this is an auto-typed variable whose initializer we are parsing.
56   if (ParsingInitForAutoVars.count(D))
57     return false;
58 
59   // See if this is a deleted function.
60   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61     if (FD->isDeleted())
62       return false;
63 
64     // If the function has a deduced return type, and we can't deduce it,
65     // then we can't use it either.
66     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68       return false;
69   }
70 
71   // See if this function is unavailable.
72   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
73       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
74     return false;
75 
76   return true;
77 }
78 
79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
80   // Warn if this is used but marked unused.
81   if (const auto *A = D->getAttr<UnusedAttr>()) {
82     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
83     // should diagnose them.
84     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
85         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
86       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
87       if (DC && !DC->hasAttr<UnusedAttr>())
88         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
89     }
90   }
91 }
92 
93 /// Emit a note explaining that this function is deleted.
94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
95   assert(Decl->isDeleted());
96 
97   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
98 
99   if (Method && Method->isDeleted() && Method->isDefaulted()) {
100     // If the method was explicitly defaulted, point at that declaration.
101     if (!Method->isImplicit())
102       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
103 
104     // Try to diagnose why this special member function was implicitly
105     // deleted. This might fail, if that reason no longer applies.
106     CXXSpecialMember CSM = getSpecialMember(Method);
107     if (CSM != CXXInvalid)
108       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
109 
110     return;
111   }
112 
113   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
114   if (Ctor && Ctor->isInheritingConstructor())
115     return NoteDeletedInheritingConstructor(Ctor);
116 
117   Diag(Decl->getLocation(), diag::note_availability_specified_here)
118     << Decl << true;
119 }
120 
121 /// Determine whether a FunctionDecl was ever declared with an
122 /// explicit storage class.
123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
124   for (auto I : D->redecls()) {
125     if (I->getStorageClass() != SC_None)
126       return true;
127   }
128   return false;
129 }
130 
131 /// Check whether we're in an extern inline function and referring to a
132 /// variable or function with internal linkage (C11 6.7.4p3).
133 ///
134 /// This is only a warning because we used to silently accept this code, but
135 /// in many cases it will not behave correctly. This is not enabled in C++ mode
136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
137 /// and so while there may still be user mistakes, most of the time we can't
138 /// prove that there are errors.
139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
140                                                       const NamedDecl *D,
141                                                       SourceLocation Loc) {
142   // This is disabled under C++; there are too many ways for this to fire in
143   // contexts where the warning is a false positive, or where it is technically
144   // correct but benign.
145   if (S.getLangOpts().CPlusPlus)
146     return;
147 
148   // Check if this is an inlined function or method.
149   FunctionDecl *Current = S.getCurFunctionDecl();
150   if (!Current)
151     return;
152   if (!Current->isInlined())
153     return;
154   if (!Current->isExternallyVisible())
155     return;
156 
157   // Check if the decl has internal linkage.
158   if (D->getFormalLinkage() != InternalLinkage)
159     return;
160 
161   // Downgrade from ExtWarn to Extension if
162   //  (1) the supposedly external inline function is in the main file,
163   //      and probably won't be included anywhere else.
164   //  (2) the thing we're referencing is a pure function.
165   //  (3) the thing we're referencing is another inline function.
166   // This last can give us false negatives, but it's better than warning on
167   // wrappers for simple C library functions.
168   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
169   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
170   if (!DowngradeWarning && UsedFn)
171     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
172 
173   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
174                                : diag::ext_internal_in_extern_inline)
175     << /*IsVar=*/!UsedFn << D;
176 
177   S.MaybeSuggestAddingStaticToDecl(Current);
178 
179   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
180       << D;
181 }
182 
183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
184   const FunctionDecl *First = Cur->getFirstDecl();
185 
186   // Suggest "static" on the function, if possible.
187   if (!hasAnyExplicitStorageClass(First)) {
188     SourceLocation DeclBegin = First->getSourceRange().getBegin();
189     Diag(DeclBegin, diag::note_convert_inline_to_static)
190       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
191   }
192 }
193 
194 /// Determine whether the use of this declaration is valid, and
195 /// emit any corresponding diagnostics.
196 ///
197 /// This routine diagnoses various problems with referencing
198 /// declarations that can occur when using a declaration. For example,
199 /// it might warn if a deprecated or unavailable declaration is being
200 /// used, or produce an error (and return true) if a C++0x deleted
201 /// function is being used.
202 ///
203 /// \returns true if there was an error (this declaration cannot be
204 /// referenced), false otherwise.
205 ///
206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
207                              const ObjCInterfaceDecl *UnknownObjCClass,
208                              bool ObjCPropertyAccess,
209                              bool AvoidPartialAvailabilityChecks,
210                              ObjCInterfaceDecl *ClassReceiver) {
211   SourceLocation Loc = Locs.front();
212   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
213     // If there were any diagnostics suppressed by template argument deduction,
214     // emit them now.
215     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
216     if (Pos != SuppressedDiagnostics.end()) {
217       for (const PartialDiagnosticAt &Suppressed : Pos->second)
218         Diag(Suppressed.first, Suppressed.second);
219 
220       // Clear out the list of suppressed diagnostics, so that we don't emit
221       // them again for this specialization. However, we don't obsolete this
222       // entry from the table, because we want to avoid ever emitting these
223       // diagnostics again.
224       Pos->second.clear();
225     }
226 
227     // C++ [basic.start.main]p3:
228     //   The function 'main' shall not be used within a program.
229     if (cast<FunctionDecl>(D)->isMain())
230       Diag(Loc, diag::ext_main_used);
231   }
232 
233   // See if this is an auto-typed variable whose initializer we are parsing.
234   if (ParsingInitForAutoVars.count(D)) {
235     if (isa<BindingDecl>(D)) {
236       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
237         << D->getDeclName();
238     } else {
239       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
240         << D->getDeclName() << cast<VarDecl>(D)->getType();
241     }
242     return true;
243   }
244 
245   // See if this is a deleted function.
246   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
247     if (FD->isDeleted()) {
248       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
249       if (Ctor && Ctor->isInheritingConstructor())
250         Diag(Loc, diag::err_deleted_inherited_ctor_use)
251             << Ctor->getParent()
252             << Ctor->getInheritedConstructor().getConstructor()->getParent();
253       else
254         Diag(Loc, diag::err_deleted_function_use);
255       NoteDeletedFunction(FD);
256       return true;
257     }
258 
259     // If the function has a deduced return type, and we can't deduce it,
260     // then we can't use it either.
261     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
262         DeduceReturnType(FD, Loc))
263       return true;
264 
265     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
266       return true;
267   }
268 
269   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
270     // Lambdas are only default-constructible or assignable in C++2a onwards.
271     if (MD->getParent()->isLambda() &&
272         ((isa<CXXConstructorDecl>(MD) &&
273           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
274          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
275       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
276         << !isa<CXXConstructorDecl>(MD);
277     }
278   }
279 
280   auto getReferencedObjCProp = [](const NamedDecl *D) ->
281                                       const ObjCPropertyDecl * {
282     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
283       return MD->findPropertyDecl();
284     return nullptr;
285   };
286   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
287     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
288       return true;
289   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
290       return true;
291   }
292 
293   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
294   // Only the variables omp_in and omp_out are allowed in the combiner.
295   // Only the variables omp_priv and omp_orig are allowed in the
296   // initializer-clause.
297   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
298   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
299       isa<VarDecl>(D)) {
300     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
301         << getCurFunction()->HasOMPDeclareReductionCombiner;
302     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
303     return true;
304   }
305 
306   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
307                              AvoidPartialAvailabilityChecks, ClassReceiver);
308 
309   DiagnoseUnusedOfDecl(*this, D, Loc);
310 
311   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
312 
313   return false;
314 }
315 
316 /// Retrieve the message suffix that should be added to a
317 /// diagnostic complaining about the given function being deleted or
318 /// unavailable.
319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
320   std::string Message;
321   if (FD->getAvailability(&Message))
322     return ": " + Message;
323 
324   return std::string();
325 }
326 
327 /// DiagnoseSentinelCalls - This routine checks whether a call or
328 /// message-send is to a declaration with the sentinel attribute, and
329 /// if so, it checks that the requirements of the sentinel are
330 /// satisfied.
331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
332                                  ArrayRef<Expr *> Args) {
333   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
334   if (!attr)
335     return;
336 
337   // The number of formal parameters of the declaration.
338   unsigned numFormalParams;
339 
340   // The kind of declaration.  This is also an index into a %select in
341   // the diagnostic.
342   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
343 
344   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
345     numFormalParams = MD->param_size();
346     calleeType = CT_Method;
347   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
348     numFormalParams = FD->param_size();
349     calleeType = CT_Function;
350   } else if (isa<VarDecl>(D)) {
351     QualType type = cast<ValueDecl>(D)->getType();
352     const FunctionType *fn = nullptr;
353     if (const PointerType *ptr = type->getAs<PointerType>()) {
354       fn = ptr->getPointeeType()->getAs<FunctionType>();
355       if (!fn) return;
356       calleeType = CT_Function;
357     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
358       fn = ptr->getPointeeType()->castAs<FunctionType>();
359       calleeType = CT_Block;
360     } else {
361       return;
362     }
363 
364     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
365       numFormalParams = proto->getNumParams();
366     } else {
367       numFormalParams = 0;
368     }
369   } else {
370     return;
371   }
372 
373   // "nullPos" is the number of formal parameters at the end which
374   // effectively count as part of the variadic arguments.  This is
375   // useful if you would prefer to not have *any* formal parameters,
376   // but the language forces you to have at least one.
377   unsigned nullPos = attr->getNullPos();
378   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
379   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
380 
381   // The number of arguments which should follow the sentinel.
382   unsigned numArgsAfterSentinel = attr->getSentinel();
383 
384   // If there aren't enough arguments for all the formal parameters,
385   // the sentinel, and the args after the sentinel, complain.
386   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
387     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
388     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
389     return;
390   }
391 
392   // Otherwise, find the sentinel expression.
393   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
394   if (!sentinelExpr) return;
395   if (sentinelExpr->isValueDependent()) return;
396   if (Context.isSentinelNullExpr(sentinelExpr)) return;
397 
398   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
399   // or 'NULL' if those are actually defined in the context.  Only use
400   // 'nil' for ObjC methods, where it's much more likely that the
401   // variadic arguments form a list of object pointers.
402   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
403   std::string NullValue;
404   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
405     NullValue = "nil";
406   else if (getLangOpts().CPlusPlus11)
407     NullValue = "nullptr";
408   else if (PP.isMacroDefined("NULL"))
409     NullValue = "NULL";
410   else
411     NullValue = "(void*) 0";
412 
413   if (MissingNilLoc.isInvalid())
414     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
415   else
416     Diag(MissingNilLoc, diag::warn_missing_sentinel)
417       << int(calleeType)
418       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
419   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
420 }
421 
422 SourceRange Sema::getExprRange(Expr *E) const {
423   return E ? E->getSourceRange() : SourceRange();
424 }
425 
426 //===----------------------------------------------------------------------===//
427 //  Standard Promotions and Conversions
428 //===----------------------------------------------------------------------===//
429 
430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
432   // Handle any placeholder expressions which made it here.
433   if (E->getType()->isPlaceholderType()) {
434     ExprResult result = CheckPlaceholderExpr(E);
435     if (result.isInvalid()) return ExprError();
436     E = result.get();
437   }
438 
439   QualType Ty = E->getType();
440   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
441 
442   if (Ty->isFunctionType()) {
443     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
444       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
445         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
446           return ExprError();
447 
448     E = ImpCastExprToType(E, Context.getPointerType(Ty),
449                           CK_FunctionToPointerDecay).get();
450   } else if (Ty->isArrayType()) {
451     // In C90 mode, arrays only promote to pointers if the array expression is
452     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
453     // type 'array of type' is converted to an expression that has type 'pointer
454     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
455     // that has type 'array of type' ...".  The relevant change is "an lvalue"
456     // (C90) to "an expression" (C99).
457     //
458     // C++ 4.2p1:
459     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
460     // T" can be converted to an rvalue of type "pointer to T".
461     //
462     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
463       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
464                             CK_ArrayToPointerDecay).get();
465   }
466   return E;
467 }
468 
469 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
470   // Check to see if we are dereferencing a null pointer.  If so,
471   // and if not volatile-qualified, this is undefined behavior that the
472   // optimizer will delete, so warn about it.  People sometimes try to use this
473   // to get a deterministic trap and are surprised by clang's behavior.  This
474   // only handles the pattern "*null", which is a very syntactic check.
475   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
476     if (UO->getOpcode() == UO_Deref &&
477         UO->getSubExpr()->IgnoreParenCasts()->
478           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
479         !UO->getType().isVolatileQualified()) {
480     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
481                           S.PDiag(diag::warn_indirection_through_null)
482                             << UO->getSubExpr()->getSourceRange());
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                         S.PDiag(diag::note_indirection_through_null));
485   }
486 }
487 
488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
489                                     SourceLocation AssignLoc,
490                                     const Expr* RHS) {
491   const ObjCIvarDecl *IV = OIRE->getDecl();
492   if (!IV)
493     return;
494 
495   DeclarationName MemberName = IV->getDeclName();
496   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
497   if (!Member || !Member->isStr("isa"))
498     return;
499 
500   const Expr *Base = OIRE->getBase();
501   QualType BaseType = Base->getType();
502   if (OIRE->isArrow())
503     BaseType = BaseType->getPointeeType();
504   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
505     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
506       ObjCInterfaceDecl *ClassDeclared = nullptr;
507       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
508       if (!ClassDeclared->getSuperClass()
509           && (*ClassDeclared->ivar_begin()) == IV) {
510         if (RHS) {
511           NamedDecl *ObjectSetClass =
512             S.LookupSingleName(S.TUScope,
513                                &S.Context.Idents.get("object_setClass"),
514                                SourceLocation(), S.LookupOrdinaryName);
515           if (ObjectSetClass) {
516             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
517             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
518                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
519                                               "object_setClass(")
520                 << FixItHint::CreateReplacement(
521                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
522                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
523           }
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
526         } else {
527           NamedDecl *ObjectGetClass =
528             S.LookupSingleName(S.TUScope,
529                                &S.Context.Idents.get("object_getClass"),
530                                SourceLocation(), S.LookupOrdinaryName);
531           if (ObjectGetClass)
532             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
533                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
534                                               "object_getClass(")
535                 << FixItHint::CreateReplacement(
536                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
537           else
538             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
539         }
540         S.Diag(IV->getLocation(), diag::note_ivar_decl);
541       }
542     }
543 }
544 
545 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
546   // Handle any placeholder expressions which made it here.
547   if (E->getType()->isPlaceholderType()) {
548     ExprResult result = CheckPlaceholderExpr(E);
549     if (result.isInvalid()) return ExprError();
550     E = result.get();
551   }
552 
553   // C++ [conv.lval]p1:
554   //   A glvalue of a non-function, non-array type T can be
555   //   converted to a prvalue.
556   if (!E->isGLValue()) return E;
557 
558   QualType T = E->getType();
559   assert(!T.isNull() && "r-value conversion on typeless expression?");
560 
561   // We don't want to throw lvalue-to-rvalue casts on top of
562   // expressions of certain types in C++.
563   if (getLangOpts().CPlusPlus &&
564       (E->getType() == Context.OverloadTy ||
565        T->isDependentType() ||
566        T->isRecordType()))
567     return E;
568 
569   // The C standard is actually really unclear on this point, and
570   // DR106 tells us what the result should be but not why.  It's
571   // generally best to say that void types just doesn't undergo
572   // lvalue-to-rvalue at all.  Note that expressions of unqualified
573   // 'void' type are never l-values, but qualified void can be.
574   if (T->isVoidType())
575     return E;
576 
577   // OpenCL usually rejects direct accesses to values of 'half' type.
578   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
579       T->isHalfType()) {
580     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
581       << 0 << T;
582     return ExprError();
583   }
584 
585   CheckForNullPointerDereference(*this, E);
586   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
587     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
588                                      &Context.Idents.get("object_getClass"),
589                                      SourceLocation(), LookupOrdinaryName);
590     if (ObjectGetClass)
591       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
592           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
593           << FixItHint::CreateReplacement(
594                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
595     else
596       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
597   }
598   else if (const ObjCIvarRefExpr *OIRE =
599             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
600     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
601 
602   // C++ [conv.lval]p1:
603   //   [...] If T is a non-class type, the type of the prvalue is the
604   //   cv-unqualified version of T. Otherwise, the type of the
605   //   rvalue is T.
606   //
607   // C99 6.3.2.1p2:
608   //   If the lvalue has qualified type, the value has the unqualified
609   //   version of the type of the lvalue; otherwise, the value has the
610   //   type of the lvalue.
611   if (T.hasQualifiers())
612     T = T.getUnqualifiedType();
613 
614   // Under the MS ABI, lock down the inheritance model now.
615   if (T->isMemberPointerType() &&
616       Context.getTargetInfo().getCXXABI().isMicrosoft())
617     (void)isCompleteType(E->getExprLoc(), T);
618 
619   UpdateMarkingForLValueToRValue(E);
620 
621   // Loading a __weak object implicitly retains the value, so we need a cleanup to
622   // balance that.
623   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
624     Cleanup.setExprNeedsCleanups(true);
625 
626   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
627                                             nullptr, VK_RValue);
628 
629   // C11 6.3.2.1p2:
630   //   ... if the lvalue has atomic type, the value has the non-atomic version
631   //   of the type of the lvalue ...
632   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
633     T = Atomic->getValueType().getUnqualifiedType();
634     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
635                                    nullptr, VK_RValue);
636   }
637 
638   return Res;
639 }
640 
641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
642   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
643   if (Res.isInvalid())
644     return ExprError();
645   Res = DefaultLvalueConversion(Res.get());
646   if (Res.isInvalid())
647     return ExprError();
648   return Res;
649 }
650 
651 /// CallExprUnaryConversions - a special case of an unary conversion
652 /// performed on a function designator of a call expression.
653 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
654   QualType Ty = E->getType();
655   ExprResult Res = E;
656   // Only do implicit cast for a function type, but not for a pointer
657   // to function type.
658   if (Ty->isFunctionType()) {
659     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
660                             CK_FunctionToPointerDecay).get();
661     if (Res.isInvalid())
662       return ExprError();
663   }
664   Res = DefaultLvalueConversion(Res.get());
665   if (Res.isInvalid())
666     return ExprError();
667   return Res.get();
668 }
669 
670 /// UsualUnaryConversions - Performs various conversions that are common to most
671 /// operators (C99 6.3). The conversions of array and function types are
672 /// sometimes suppressed. For example, the array->pointer conversion doesn't
673 /// apply if the array is an argument to the sizeof or address (&) operators.
674 /// In these instances, this routine should *not* be called.
675 ExprResult Sema::UsualUnaryConversions(Expr *E) {
676   // First, convert to an r-value.
677   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
678   if (Res.isInvalid())
679     return ExprError();
680   E = Res.get();
681 
682   QualType Ty = E->getType();
683   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
684 
685   // Half FP have to be promoted to float unless it is natively supported
686   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
687     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
688 
689   // Try to perform integral promotions if the object has a theoretically
690   // promotable type.
691   if (Ty->isIntegralOrUnscopedEnumerationType()) {
692     // C99 6.3.1.1p2:
693     //
694     //   The following may be used in an expression wherever an int or
695     //   unsigned int may be used:
696     //     - an object or expression with an integer type whose integer
697     //       conversion rank is less than or equal to the rank of int
698     //       and unsigned int.
699     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
700     //
701     //   If an int can represent all values of the original type, the
702     //   value is converted to an int; otherwise, it is converted to an
703     //   unsigned int. These are called the integer promotions. All
704     //   other types are unchanged by the integer promotions.
705 
706     QualType PTy = Context.isPromotableBitField(E);
707     if (!PTy.isNull()) {
708       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
709       return E;
710     }
711     if (Ty->isPromotableIntegerType()) {
712       QualType PT = Context.getPromotedIntegerType(Ty);
713       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
714       return E;
715     }
716   }
717   return E;
718 }
719 
720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
721 /// do not have a prototype. Arguments that have type float or __fp16
722 /// are promoted to double. All other argument types are converted by
723 /// UsualUnaryConversions().
724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
725   QualType Ty = E->getType();
726   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
727 
728   ExprResult Res = UsualUnaryConversions(E);
729   if (Res.isInvalid())
730     return ExprError();
731   E = Res.get();
732 
733   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
734   // promote to double.
735   // Note that default argument promotion applies only to float (and
736   // half/fp16); it does not apply to _Float16.
737   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
738   if (BTy && (BTy->getKind() == BuiltinType::Half ||
739               BTy->getKind() == BuiltinType::Float)) {
740     if (getLangOpts().OpenCL &&
741         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
742         if (BTy->getKind() == BuiltinType::Half) {
743             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
744         }
745     } else {
746       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
747     }
748   }
749 
750   // C++ performs lvalue-to-rvalue conversion as a default argument
751   // promotion, even on class types, but note:
752   //   C++11 [conv.lval]p2:
753   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
754   //     operand or a subexpression thereof the value contained in the
755   //     referenced object is not accessed. Otherwise, if the glvalue
756   //     has a class type, the conversion copy-initializes a temporary
757   //     of type T from the glvalue and the result of the conversion
758   //     is a prvalue for the temporary.
759   // FIXME: add some way to gate this entire thing for correctness in
760   // potentially potentially evaluated contexts.
761   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
762     ExprResult Temp = PerformCopyInitialization(
763                        InitializedEntity::InitializeTemporary(E->getType()),
764                                                 E->getExprLoc(), E);
765     if (Temp.isInvalid())
766       return ExprError();
767     E = Temp.get();
768   }
769 
770   return E;
771 }
772 
773 /// Determine the degree of POD-ness for an expression.
774 /// Incomplete types are considered POD, since this check can be performed
775 /// when we're in an unevaluated context.
776 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
777   if (Ty->isIncompleteType()) {
778     // C++11 [expr.call]p7:
779     //   After these conversions, if the argument does not have arithmetic,
780     //   enumeration, pointer, pointer to member, or class type, the program
781     //   is ill-formed.
782     //
783     // Since we've already performed array-to-pointer and function-to-pointer
784     // decay, the only such type in C++ is cv void. This also handles
785     // initializer lists as variadic arguments.
786     if (Ty->isVoidType())
787       return VAK_Invalid;
788 
789     if (Ty->isObjCObjectType())
790       return VAK_Invalid;
791     return VAK_Valid;
792   }
793 
794   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
795     return VAK_Invalid;
796 
797   if (Ty.isCXX98PODType(Context))
798     return VAK_Valid;
799 
800   // C++11 [expr.call]p7:
801   //   Passing a potentially-evaluated argument of class type (Clause 9)
802   //   having a non-trivial copy constructor, a non-trivial move constructor,
803   //   or a non-trivial destructor, with no corresponding parameter,
804   //   is conditionally-supported with implementation-defined semantics.
805   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
806     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
807       if (!Record->hasNonTrivialCopyConstructor() &&
808           !Record->hasNonTrivialMoveConstructor() &&
809           !Record->hasNonTrivialDestructor())
810         return VAK_ValidInCXX11;
811 
812   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
813     return VAK_Valid;
814 
815   if (Ty->isObjCObjectType())
816     return VAK_Invalid;
817 
818   if (getLangOpts().MSVCCompat)
819     return VAK_MSVCUndefined;
820 
821   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
822   // permitted to reject them. We should consider doing so.
823   return VAK_Undefined;
824 }
825 
826 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
827   // Don't allow one to pass an Objective-C interface to a vararg.
828   const QualType &Ty = E->getType();
829   VarArgKind VAK = isValidVarArgType(Ty);
830 
831   // Complain about passing non-POD types through varargs.
832   switch (VAK) {
833   case VAK_ValidInCXX11:
834     DiagRuntimeBehavior(
835         E->getBeginLoc(), nullptr,
836         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
837     LLVM_FALLTHROUGH;
838   case VAK_Valid:
839     if (Ty->isRecordType()) {
840       // This is unlikely to be what the user intended. If the class has a
841       // 'c_str' member function, the user probably meant to call that.
842       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
843                           PDiag(diag::warn_pass_class_arg_to_vararg)
844                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
845     }
846     break;
847 
848   case VAK_Undefined:
849   case VAK_MSVCUndefined:
850     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
851                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
852                             << getLangOpts().CPlusPlus11 << Ty << CT);
853     break;
854 
855   case VAK_Invalid:
856     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
857       Diag(E->getBeginLoc(),
858            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
859           << Ty << CT;
860     else if (Ty->isObjCObjectType())
861       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
862                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
863                               << Ty << CT);
864     else
865       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
866           << isa<InitListExpr>(E) << Ty << CT;
867     break;
868   }
869 }
870 
871 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
872 /// will create a trap if the resulting type is not a POD type.
873 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
874                                                   FunctionDecl *FDecl) {
875   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
876     // Strip the unbridged-cast placeholder expression off, if applicable.
877     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
878         (CT == VariadicMethod ||
879          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
880       E = stripARCUnbridgedCast(E);
881 
882     // Otherwise, do normal placeholder checking.
883     } else {
884       ExprResult ExprRes = CheckPlaceholderExpr(E);
885       if (ExprRes.isInvalid())
886         return ExprError();
887       E = ExprRes.get();
888     }
889   }
890 
891   ExprResult ExprRes = DefaultArgumentPromotion(E);
892   if (ExprRes.isInvalid())
893     return ExprError();
894   E = ExprRes.get();
895 
896   // Diagnostics regarding non-POD argument types are
897   // emitted along with format string checking in Sema::CheckFunctionCall().
898   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
899     // Turn this into a trap.
900     CXXScopeSpec SS;
901     SourceLocation TemplateKWLoc;
902     UnqualifiedId Name;
903     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
904                        E->getBeginLoc());
905     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
906                                           Name, true, false);
907     if (TrapFn.isInvalid())
908       return ExprError();
909 
910     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
911                                     None, E->getEndLoc());
912     if (Call.isInvalid())
913       return ExprError();
914 
915     ExprResult Comma =
916         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
917     if (Comma.isInvalid())
918       return ExprError();
919     return Comma.get();
920   }
921 
922   if (!getLangOpts().CPlusPlus &&
923       RequireCompleteType(E->getExprLoc(), E->getType(),
924                           diag::err_call_incomplete_argument))
925     return ExprError();
926 
927   return E;
928 }
929 
930 /// Converts an integer to complex float type.  Helper function of
931 /// UsualArithmeticConversions()
932 ///
933 /// \return false if the integer expression is an integer type and is
934 /// successfully converted to the complex type.
935 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
936                                                   ExprResult &ComplexExpr,
937                                                   QualType IntTy,
938                                                   QualType ComplexTy,
939                                                   bool SkipCast) {
940   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
941   if (SkipCast) return false;
942   if (IntTy->isIntegerType()) {
943     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
944     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
945     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
946                                   CK_FloatingRealToComplex);
947   } else {
948     assert(IntTy->isComplexIntegerType());
949     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
950                                   CK_IntegralComplexToFloatingComplex);
951   }
952   return false;
953 }
954 
955 /// Handle arithmetic conversion with complex types.  Helper function of
956 /// UsualArithmeticConversions()
957 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
958                                              ExprResult &RHS, QualType LHSType,
959                                              QualType RHSType,
960                                              bool IsCompAssign) {
961   // if we have an integer operand, the result is the complex type.
962   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
963                                              /*skipCast*/false))
964     return LHSType;
965   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
966                                              /*skipCast*/IsCompAssign))
967     return RHSType;
968 
969   // This handles complex/complex, complex/float, or float/complex.
970   // When both operands are complex, the shorter operand is converted to the
971   // type of the longer, and that is the type of the result. This corresponds
972   // to what is done when combining two real floating-point operands.
973   // The fun begins when size promotion occur across type domains.
974   // From H&S 6.3.4: When one operand is complex and the other is a real
975   // floating-point type, the less precise type is converted, within it's
976   // real or complex domain, to the precision of the other type. For example,
977   // when combining a "long double" with a "double _Complex", the
978   // "double _Complex" is promoted to "long double _Complex".
979 
980   // Compute the rank of the two types, regardless of whether they are complex.
981   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
982 
983   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
984   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
985   QualType LHSElementType =
986       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
987   QualType RHSElementType =
988       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
989 
990   QualType ResultType = S.Context.getComplexType(LHSElementType);
991   if (Order < 0) {
992     // Promote the precision of the LHS if not an assignment.
993     ResultType = S.Context.getComplexType(RHSElementType);
994     if (!IsCompAssign) {
995       if (LHSComplexType)
996         LHS =
997             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
998       else
999         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1000     }
1001   } else if (Order > 0) {
1002     // Promote the precision of the RHS.
1003     if (RHSComplexType)
1004       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1005     else
1006       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1007   }
1008   return ResultType;
1009 }
1010 
1011 /// Handle arithmetic conversion from integer to float.  Helper function
1012 /// of UsualArithmeticConversions()
1013 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1014                                            ExprResult &IntExpr,
1015                                            QualType FloatTy, QualType IntTy,
1016                                            bool ConvertFloat, bool ConvertInt) {
1017   if (IntTy->isIntegerType()) {
1018     if (ConvertInt)
1019       // Convert intExpr to the lhs floating point type.
1020       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1021                                     CK_IntegralToFloating);
1022     return FloatTy;
1023   }
1024 
1025   // Convert both sides to the appropriate complex float.
1026   assert(IntTy->isComplexIntegerType());
1027   QualType result = S.Context.getComplexType(FloatTy);
1028 
1029   // _Complex int -> _Complex float
1030   if (ConvertInt)
1031     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1032                                   CK_IntegralComplexToFloatingComplex);
1033 
1034   // float -> _Complex float
1035   if (ConvertFloat)
1036     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1037                                     CK_FloatingRealToComplex);
1038 
1039   return result;
1040 }
1041 
1042 /// Handle arithmethic conversion with floating point types.  Helper
1043 /// function of UsualArithmeticConversions()
1044 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1045                                       ExprResult &RHS, QualType LHSType,
1046                                       QualType RHSType, bool IsCompAssign) {
1047   bool LHSFloat = LHSType->isRealFloatingType();
1048   bool RHSFloat = RHSType->isRealFloatingType();
1049 
1050   // If we have two real floating types, convert the smaller operand
1051   // to the bigger result.
1052   if (LHSFloat && RHSFloat) {
1053     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1054     if (order > 0) {
1055       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1056       return LHSType;
1057     }
1058 
1059     assert(order < 0 && "illegal float comparison");
1060     if (!IsCompAssign)
1061       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1062     return RHSType;
1063   }
1064 
1065   if (LHSFloat) {
1066     // Half FP has to be promoted to float unless it is natively supported
1067     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1068       LHSType = S.Context.FloatTy;
1069 
1070     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1071                                       /*convertFloat=*/!IsCompAssign,
1072                                       /*convertInt=*/ true);
1073   }
1074   assert(RHSFloat);
1075   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1076                                     /*convertInt=*/ true,
1077                                     /*convertFloat=*/!IsCompAssign);
1078 }
1079 
1080 /// Diagnose attempts to convert between __float128 and long double if
1081 /// there is no support for such conversion. Helper function of
1082 /// UsualArithmeticConversions().
1083 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1084                                       QualType RHSType) {
1085   /*  No issue converting if at least one of the types is not a floating point
1086       type or the two types have the same rank.
1087   */
1088   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1089       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1090     return false;
1091 
1092   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1093          "The remaining types must be floating point types.");
1094 
1095   auto *LHSComplex = LHSType->getAs<ComplexType>();
1096   auto *RHSComplex = RHSType->getAs<ComplexType>();
1097 
1098   QualType LHSElemType = LHSComplex ?
1099     LHSComplex->getElementType() : LHSType;
1100   QualType RHSElemType = RHSComplex ?
1101     RHSComplex->getElementType() : RHSType;
1102 
1103   // No issue if the two types have the same representation
1104   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1105       &S.Context.getFloatTypeSemantics(RHSElemType))
1106     return false;
1107 
1108   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1109                                 RHSElemType == S.Context.LongDoubleTy);
1110   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1111                             RHSElemType == S.Context.Float128Ty);
1112 
1113   // We've handled the situation where __float128 and long double have the same
1114   // representation. We allow all conversions for all possible long double types
1115   // except PPC's double double.
1116   return Float128AndLongDouble &&
1117     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1118      &llvm::APFloat::PPCDoubleDouble());
1119 }
1120 
1121 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1122 
1123 namespace {
1124 /// These helper callbacks are placed in an anonymous namespace to
1125 /// permit their use as function template parameters.
1126 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1127   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1128 }
1129 
1130 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1131   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1132                              CK_IntegralComplexCast);
1133 }
1134 }
1135 
1136 /// Handle integer arithmetic conversions.  Helper function of
1137 /// UsualArithmeticConversions()
1138 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1139 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1140                                         ExprResult &RHS, QualType LHSType,
1141                                         QualType RHSType, bool IsCompAssign) {
1142   // The rules for this case are in C99 6.3.1.8
1143   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1144   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1145   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1146   if (LHSSigned == RHSSigned) {
1147     // Same signedness; use the higher-ranked type
1148     if (order >= 0) {
1149       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1150       return LHSType;
1151     } else if (!IsCompAssign)
1152       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1153     return RHSType;
1154   } else if (order != (LHSSigned ? 1 : -1)) {
1155     // The unsigned type has greater than or equal rank to the
1156     // signed type, so use the unsigned type
1157     if (RHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1164     // The two types are different widths; if we are here, that
1165     // means the signed type is larger than the unsigned type, so
1166     // use the signed type.
1167     if (LHSSigned) {
1168       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1169       return LHSType;
1170     } else if (!IsCompAssign)
1171       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1172     return RHSType;
1173   } else {
1174     // The signed type is higher-ranked than the unsigned type,
1175     // but isn't actually any bigger (like unsigned int and long
1176     // on most 32-bit systems).  Use the unsigned type corresponding
1177     // to the signed type.
1178     QualType result =
1179       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1180     RHS = (*doRHSCast)(S, RHS.get(), result);
1181     if (!IsCompAssign)
1182       LHS = (*doLHSCast)(S, LHS.get(), result);
1183     return result;
1184   }
1185 }
1186 
1187 /// Handle conversions with GCC complex int extension.  Helper function
1188 /// of UsualArithmeticConversions()
1189 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1190                                            ExprResult &RHS, QualType LHSType,
1191                                            QualType RHSType,
1192                                            bool IsCompAssign) {
1193   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1194   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1195 
1196   if (LHSComplexInt && RHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType RHSEltType = RHSComplexInt->getElementType();
1199     QualType ScalarType =
1200       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1201         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1202 
1203     return S.Context.getComplexType(ScalarType);
1204   }
1205 
1206   if (LHSComplexInt) {
1207     QualType LHSEltType = LHSComplexInt->getElementType();
1208     QualType ScalarType =
1209       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1210         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1211     QualType ComplexType = S.Context.getComplexType(ScalarType);
1212     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1213                               CK_IntegralRealToComplex);
1214 
1215     return ComplexType;
1216   }
1217 
1218   assert(RHSComplexInt);
1219 
1220   QualType RHSEltType = RHSComplexInt->getElementType();
1221   QualType ScalarType =
1222     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1223       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1224   QualType ComplexType = S.Context.getComplexType(ScalarType);
1225 
1226   if (!IsCompAssign)
1227     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229   return ComplexType;
1230 }
1231 
1232 /// UsualArithmeticConversions - Performs various conversions that are common to
1233 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1234 /// routine returns the first non-arithmetic type found. The client is
1235 /// responsible for emitting appropriate error diagnostics.
1236 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1237                                           bool IsCompAssign) {
1238   if (!IsCompAssign) {
1239     LHS = UsualUnaryConversions(LHS.get());
1240     if (LHS.isInvalid())
1241       return QualType();
1242   }
1243 
1244   RHS = UsualUnaryConversions(RHS.get());
1245   if (RHS.isInvalid())
1246     return QualType();
1247 
1248   // For conversion purposes, we ignore any qualifiers.
1249   // For example, "const float" and "float" are equivalent.
1250   QualType LHSType =
1251     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1252   QualType RHSType =
1253     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1254 
1255   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1256   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1257     LHSType = AtomicLHS->getValueType();
1258 
1259   // If both types are identical, no conversion is needed.
1260   if (LHSType == RHSType)
1261     return LHSType;
1262 
1263   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1264   // The caller can deal with this (e.g. pointer + int).
1265   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1266     return QualType();
1267 
1268   // Apply unary and bitfield promotions to the LHS's type.
1269   QualType LHSUnpromotedType = LHSType;
1270   if (LHSType->isPromotableIntegerType())
1271     LHSType = Context.getPromotedIntegerType(LHSType);
1272   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1273   if (!LHSBitfieldPromoteTy.isNull())
1274     LHSType = LHSBitfieldPromoteTy;
1275   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1276     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1277 
1278   // If both types are identical, no conversion is needed.
1279   if (LHSType == RHSType)
1280     return LHSType;
1281 
1282   // At this point, we have two different arithmetic types.
1283 
1284   // Diagnose attempts to convert between __float128 and long double where
1285   // such conversions currently can't be handled.
1286   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1287     return QualType();
1288 
1289   // Handle complex types first (C99 6.3.1.8p1).
1290   if (LHSType->isComplexType() || RHSType->isComplexType())
1291     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                         IsCompAssign);
1293 
1294   // Now handle "real" floating types (i.e. float, double, long double).
1295   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1296     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1297                                  IsCompAssign);
1298 
1299   // Handle GCC complex int extension.
1300   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1301     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1302                                       IsCompAssign);
1303 
1304   // Finally, we have two differing integer types.
1305   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1306            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1307 }
1308 
1309 
1310 //===----------------------------------------------------------------------===//
1311 //  Semantic Analysis for various Expression Types
1312 //===----------------------------------------------------------------------===//
1313 
1314 
1315 ExprResult
1316 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1317                                 SourceLocation DefaultLoc,
1318                                 SourceLocation RParenLoc,
1319                                 Expr *ControllingExpr,
1320                                 ArrayRef<ParsedType> ArgTypes,
1321                                 ArrayRef<Expr *> ArgExprs) {
1322   unsigned NumAssocs = ArgTypes.size();
1323   assert(NumAssocs == ArgExprs.size());
1324 
1325   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1326   for (unsigned i = 0; i < NumAssocs; ++i) {
1327     if (ArgTypes[i])
1328       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1329     else
1330       Types[i] = nullptr;
1331   }
1332 
1333   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1334                                              ControllingExpr,
1335                                              llvm::makeArrayRef(Types, NumAssocs),
1336                                              ArgExprs);
1337   delete [] Types;
1338   return ER;
1339 }
1340 
1341 ExprResult
1342 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1343                                  SourceLocation DefaultLoc,
1344                                  SourceLocation RParenLoc,
1345                                  Expr *ControllingExpr,
1346                                  ArrayRef<TypeSourceInfo *> Types,
1347                                  ArrayRef<Expr *> Exprs) {
1348   unsigned NumAssocs = Types.size();
1349   assert(NumAssocs == Exprs.size());
1350 
1351   // Decay and strip qualifiers for the controlling expression type, and handle
1352   // placeholder type replacement. See committee discussion from WG14 DR423.
1353   {
1354     EnterExpressionEvaluationContext Unevaluated(
1355         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1356     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1357     if (R.isInvalid())
1358       return ExprError();
1359     ControllingExpr = R.get();
1360   }
1361 
1362   // The controlling expression is an unevaluated operand, so side effects are
1363   // likely unintended.
1364   if (!inTemplateInstantiation() &&
1365       ControllingExpr->HasSideEffects(Context, false))
1366     Diag(ControllingExpr->getExprLoc(),
1367          diag::warn_side_effects_unevaluated_context);
1368 
1369   bool TypeErrorFound = false,
1370        IsResultDependent = ControllingExpr->isTypeDependent(),
1371        ContainsUnexpandedParameterPack
1372          = ControllingExpr->containsUnexpandedParameterPack();
1373 
1374   for (unsigned i = 0; i < NumAssocs; ++i) {
1375     if (Exprs[i]->containsUnexpandedParameterPack())
1376       ContainsUnexpandedParameterPack = true;
1377 
1378     if (Types[i]) {
1379       if (Types[i]->getType()->containsUnexpandedParameterPack())
1380         ContainsUnexpandedParameterPack = true;
1381 
1382       if (Types[i]->getType()->isDependentType()) {
1383         IsResultDependent = true;
1384       } else {
1385         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1386         // complete object type other than a variably modified type."
1387         unsigned D = 0;
1388         if (Types[i]->getType()->isIncompleteType())
1389           D = diag::err_assoc_type_incomplete;
1390         else if (!Types[i]->getType()->isObjectType())
1391           D = diag::err_assoc_type_nonobject;
1392         else if (Types[i]->getType()->isVariablyModifiedType())
1393           D = diag::err_assoc_type_variably_modified;
1394 
1395         if (D != 0) {
1396           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1397             << Types[i]->getTypeLoc().getSourceRange()
1398             << Types[i]->getType();
1399           TypeErrorFound = true;
1400         }
1401 
1402         // C11 6.5.1.1p2 "No two generic associations in the same generic
1403         // selection shall specify compatible types."
1404         for (unsigned j = i+1; j < NumAssocs; ++j)
1405           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1406               Context.typesAreCompatible(Types[i]->getType(),
1407                                          Types[j]->getType())) {
1408             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1409                  diag::err_assoc_compatible_types)
1410               << Types[j]->getTypeLoc().getSourceRange()
1411               << Types[j]->getType()
1412               << Types[i]->getType();
1413             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1414                  diag::note_compat_assoc)
1415               << Types[i]->getTypeLoc().getSourceRange()
1416               << Types[i]->getType();
1417             TypeErrorFound = true;
1418           }
1419       }
1420     }
1421   }
1422   if (TypeErrorFound)
1423     return ExprError();
1424 
1425   // If we determined that the generic selection is result-dependent, don't
1426   // try to compute the result expression.
1427   if (IsResultDependent)
1428     return new (Context) GenericSelectionExpr(
1429         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1430         ContainsUnexpandedParameterPack);
1431 
1432   SmallVector<unsigned, 1> CompatIndices;
1433   unsigned DefaultIndex = -1U;
1434   for (unsigned i = 0; i < NumAssocs; ++i) {
1435     if (!Types[i])
1436       DefaultIndex = i;
1437     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1438                                         Types[i]->getType()))
1439       CompatIndices.push_back(i);
1440   }
1441 
1442   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1443   // type compatible with at most one of the types named in its generic
1444   // association list."
1445   if (CompatIndices.size() > 1) {
1446     // We strip parens here because the controlling expression is typically
1447     // parenthesized in macro definitions.
1448     ControllingExpr = ControllingExpr->IgnoreParens();
1449     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1450         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1451         << (unsigned)CompatIndices.size();
1452     for (unsigned I : CompatIndices) {
1453       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1454            diag::note_compat_assoc)
1455         << Types[I]->getTypeLoc().getSourceRange()
1456         << Types[I]->getType();
1457     }
1458     return ExprError();
1459   }
1460 
1461   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1462   // its controlling expression shall have type compatible with exactly one of
1463   // the types named in its generic association list."
1464   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1465     // We strip parens here because the controlling expression is typically
1466     // parenthesized in macro definitions.
1467     ControllingExpr = ControllingExpr->IgnoreParens();
1468     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1469         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1470     return ExprError();
1471   }
1472 
1473   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1474   // type name that is compatible with the type of the controlling expression,
1475   // then the result expression of the generic selection is the expression
1476   // in that generic association. Otherwise, the result expression of the
1477   // generic selection is the expression in the default generic association."
1478   unsigned ResultIndex =
1479     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1480 
1481   return new (Context) GenericSelectionExpr(
1482       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1483       ContainsUnexpandedParameterPack, ResultIndex);
1484 }
1485 
1486 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1487 /// location of the token and the offset of the ud-suffix within it.
1488 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1489                                      unsigned Offset) {
1490   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1491                                         S.getLangOpts());
1492 }
1493 
1494 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1495 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1496 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1497                                                  IdentifierInfo *UDSuffix,
1498                                                  SourceLocation UDSuffixLoc,
1499                                                  ArrayRef<Expr*> Args,
1500                                                  SourceLocation LitEndLoc) {
1501   assert(Args.size() <= 2 && "too many arguments for literal operator");
1502 
1503   QualType ArgTy[2];
1504   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1505     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1506     if (ArgTy[ArgIdx]->isArrayType())
1507       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1508   }
1509 
1510   DeclarationName OpName =
1511     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1512   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1513   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1514 
1515   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1516   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1517                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1518                               /*AllowStringTemplate*/ false,
1519                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1520     return ExprError();
1521 
1522   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1523 }
1524 
1525 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1526 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1527 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1528 /// multiple tokens.  However, the common case is that StringToks points to one
1529 /// string.
1530 ///
1531 ExprResult
1532 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1533   assert(!StringToks.empty() && "Must have at least one string!");
1534 
1535   StringLiteralParser Literal(StringToks, PP);
1536   if (Literal.hadError)
1537     return ExprError();
1538 
1539   SmallVector<SourceLocation, 4> StringTokLocs;
1540   for (const Token &Tok : StringToks)
1541     StringTokLocs.push_back(Tok.getLocation());
1542 
1543   QualType CharTy = Context.CharTy;
1544   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1545   if (Literal.isWide()) {
1546     CharTy = Context.getWideCharType();
1547     Kind = StringLiteral::Wide;
1548   } else if (Literal.isUTF8()) {
1549     if (getLangOpts().Char8)
1550       CharTy = Context.Char8Ty;
1551     Kind = StringLiteral::UTF8;
1552   } else if (Literal.isUTF16()) {
1553     CharTy = Context.Char16Ty;
1554     Kind = StringLiteral::UTF16;
1555   } else if (Literal.isUTF32()) {
1556     CharTy = Context.Char32Ty;
1557     Kind = StringLiteral::UTF32;
1558   } else if (Literal.isPascal()) {
1559     CharTy = Context.UnsignedCharTy;
1560   }
1561 
1562   QualType CharTyConst = CharTy;
1563   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1564   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1565     CharTyConst.addConst();
1566 
1567   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1568 
1569   // Get an array type for the string, according to C99 6.4.5.  This includes
1570   // the nul terminator character as well as the string length for pascal
1571   // strings.
1572   QualType StrTy = Context.getConstantArrayType(
1573       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1574       ArrayType::Normal, 0);
1575 
1576   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1577   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1578                                              Kind, Literal.Pascal, StrTy,
1579                                              &StringTokLocs[0],
1580                                              StringTokLocs.size());
1581   if (Literal.getUDSuffix().empty())
1582     return Lit;
1583 
1584   // We're building a user-defined literal.
1585   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1586   SourceLocation UDSuffixLoc =
1587     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1588                    Literal.getUDSuffixOffset());
1589 
1590   // Make sure we're allowed user-defined literals here.
1591   if (!UDLScope)
1592     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1593 
1594   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1595   //   operator "" X (str, len)
1596   QualType SizeType = Context.getSizeType();
1597 
1598   DeclarationName OpName =
1599     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1600   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1601   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1602 
1603   QualType ArgTy[] = {
1604     Context.getArrayDecayedType(StrTy), SizeType
1605   };
1606 
1607   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1608   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1609                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1610                                 /*AllowStringTemplate*/ true,
1611                                 /*DiagnoseMissing*/ true)) {
1612 
1613   case LOLR_Cooked: {
1614     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1615     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1616                                                     StringTokLocs[0]);
1617     Expr *Args[] = { Lit, LenArg };
1618 
1619     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1620   }
1621 
1622   case LOLR_StringTemplate: {
1623     TemplateArgumentListInfo ExplicitArgs;
1624 
1625     unsigned CharBits = Context.getIntWidth(CharTy);
1626     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1627     llvm::APSInt Value(CharBits, CharIsUnsigned);
1628 
1629     TemplateArgument TypeArg(CharTy);
1630     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1631     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1632 
1633     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1634       Value = Lit->getCodeUnit(I);
1635       TemplateArgument Arg(Context, Value, CharTy);
1636       TemplateArgumentLocInfo ArgInfo;
1637       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1638     }
1639     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1640                                     &ExplicitArgs);
1641   }
1642   case LOLR_Raw:
1643   case LOLR_Template:
1644   case LOLR_ErrorNoDiagnostic:
1645     llvm_unreachable("unexpected literal operator lookup result");
1646   case LOLR_Error:
1647     return ExprError();
1648   }
1649   llvm_unreachable("unexpected literal operator lookup result");
1650 }
1651 
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        SourceLocation Loc,
1655                        const CXXScopeSpec *SS) {
1656   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1657   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1658 }
1659 
1660 /// BuildDeclRefExpr - Build an expression that references a
1661 /// declaration that does not require a closure capture.
1662 ExprResult
1663 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1664                        const DeclarationNameInfo &NameInfo,
1665                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1666                        const TemplateArgumentListInfo *TemplateArgs) {
1667   bool RefersToCapturedVariable =
1668       isa<VarDecl>(D) &&
1669       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1670 
1671   DeclRefExpr *E;
1672   if (isa<VarTemplateSpecializationDecl>(D)) {
1673     VarTemplateSpecializationDecl *VarSpec =
1674         cast<VarTemplateSpecializationDecl>(D);
1675 
1676     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1677                                         : NestedNameSpecifierLoc(),
1678                             VarSpec->getTemplateKeywordLoc(), D,
1679                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1680                             FoundD, TemplateArgs);
1681   } else {
1682     assert(!TemplateArgs && "No template arguments for non-variable"
1683                             " template specialization references");
1684     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1685                                         : NestedNameSpecifierLoc(),
1686                             SourceLocation(), D, RefersToCapturedVariable,
1687                             NameInfo, Ty, VK, FoundD);
1688   }
1689 
1690   MarkDeclRefReferenced(E);
1691 
1692   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1693       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1694       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1695     getCurFunction()->recordUseOfWeak(E);
1696 
1697   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1698   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1699     FD = IFD->getAnonField();
1700   if (FD) {
1701     UnusedPrivateFields.remove(FD);
1702     // Just in case we're building an illegal pointer-to-member.
1703     if (FD->isBitField())
1704       E->setObjectKind(OK_BitField);
1705   }
1706 
1707   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1708   // designates a bit-field.
1709   if (auto *BD = dyn_cast<BindingDecl>(D))
1710     if (auto *BE = BD->getBinding())
1711       E->setObjectKind(BE->getObjectKind());
1712 
1713   return E;
1714 }
1715 
1716 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1717 /// possibly a list of template arguments.
1718 ///
1719 /// If this produces template arguments, it is permitted to call
1720 /// DecomposeTemplateName.
1721 ///
1722 /// This actually loses a lot of source location information for
1723 /// non-standard name kinds; we should consider preserving that in
1724 /// some way.
1725 void
1726 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1727                              TemplateArgumentListInfo &Buffer,
1728                              DeclarationNameInfo &NameInfo,
1729                              const TemplateArgumentListInfo *&TemplateArgs) {
1730   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1731     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1732     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1733 
1734     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1735                                        Id.TemplateId->NumArgs);
1736     translateTemplateArguments(TemplateArgsPtr, Buffer);
1737 
1738     TemplateName TName = Id.TemplateId->Template.get();
1739     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1740     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1741     TemplateArgs = &Buffer;
1742   } else {
1743     NameInfo = GetNameFromUnqualifiedId(Id);
1744     TemplateArgs = nullptr;
1745   }
1746 }
1747 
1748 static void emitEmptyLookupTypoDiagnostic(
1749     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1750     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1751     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1752   DeclContext *Ctx =
1753       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1754   if (!TC) {
1755     // Emit a special diagnostic for failed member lookups.
1756     // FIXME: computing the declaration context might fail here (?)
1757     if (Ctx)
1758       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1759                                                  << SS.getRange();
1760     else
1761       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1762     return;
1763   }
1764 
1765   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1766   bool DroppedSpecifier =
1767       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1768   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1769                         ? diag::note_implicit_param_decl
1770                         : diag::note_previous_decl;
1771   if (!Ctx)
1772     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1773                          SemaRef.PDiag(NoteID));
1774   else
1775     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1776                                  << Typo << Ctx << DroppedSpecifier
1777                                  << SS.getRange(),
1778                          SemaRef.PDiag(NoteID));
1779 }
1780 
1781 /// Diagnose an empty lookup.
1782 ///
1783 /// \return false if new lookup candidates were found
1784 bool
1785 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1786                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1787                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1788                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1789   DeclarationName Name = R.getLookupName();
1790 
1791   unsigned diagnostic = diag::err_undeclared_var_use;
1792   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1793   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1794       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1795       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1796     diagnostic = diag::err_undeclared_use;
1797     diagnostic_suggest = diag::err_undeclared_use_suggest;
1798   }
1799 
1800   // If the original lookup was an unqualified lookup, fake an
1801   // unqualified lookup.  This is useful when (for example) the
1802   // original lookup would not have found something because it was a
1803   // dependent name.
1804   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1805   while (DC) {
1806     if (isa<CXXRecordDecl>(DC)) {
1807       LookupQualifiedName(R, DC);
1808 
1809       if (!R.empty()) {
1810         // Don't give errors about ambiguities in this lookup.
1811         R.suppressDiagnostics();
1812 
1813         // During a default argument instantiation the CurContext points
1814         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1815         // function parameter list, hence add an explicit check.
1816         bool isDefaultArgument =
1817             !CodeSynthesisContexts.empty() &&
1818             CodeSynthesisContexts.back().Kind ==
1819                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1820         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1821         bool isInstance = CurMethod &&
1822                           CurMethod->isInstance() &&
1823                           DC == CurMethod->getParent() && !isDefaultArgument;
1824 
1825         // Give a code modification hint to insert 'this->'.
1826         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1827         // Actually quite difficult!
1828         if (getLangOpts().MSVCCompat)
1829           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1830         if (isInstance) {
1831           Diag(R.getNameLoc(), diagnostic) << Name
1832             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1833           CheckCXXThisCapture(R.getNameLoc());
1834         } else {
1835           Diag(R.getNameLoc(), diagnostic) << Name;
1836         }
1837 
1838         // Do we really want to note all of these?
1839         for (NamedDecl *D : R)
1840           Diag(D->getLocation(), diag::note_dependent_var_use);
1841 
1842         // Return true if we are inside a default argument instantiation
1843         // and the found name refers to an instance member function, otherwise
1844         // the function calling DiagnoseEmptyLookup will try to create an
1845         // implicit member call and this is wrong for default argument.
1846         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1847           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1848           return true;
1849         }
1850 
1851         // Tell the callee to try to recover.
1852         return false;
1853       }
1854 
1855       R.clear();
1856     }
1857 
1858     // In Microsoft mode, if we are performing lookup from within a friend
1859     // function definition declared at class scope then we must set
1860     // DC to the lexical parent to be able to search into the parent
1861     // class.
1862     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1863         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1864         DC->getLexicalParent()->isRecord())
1865       DC = DC->getLexicalParent();
1866     else
1867       DC = DC->getParent();
1868   }
1869 
1870   // We didn't find anything, so try to correct for a typo.
1871   TypoCorrection Corrected;
1872   if (S && Out) {
1873     SourceLocation TypoLoc = R.getNameLoc();
1874     assert(!ExplicitTemplateArgs &&
1875            "Diagnosing an empty lookup with explicit template args!");
1876     *Out = CorrectTypoDelayed(
1877         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1878         [=](const TypoCorrection &TC) {
1879           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1880                                         diagnostic, diagnostic_suggest);
1881         },
1882         nullptr, CTK_ErrorRecovery);
1883     if (*Out)
1884       return true;
1885   } else if (S && (Corrected =
1886                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1887                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1888     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1889     bool DroppedSpecifier =
1890         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1891     R.setLookupName(Corrected.getCorrection());
1892 
1893     bool AcceptableWithRecovery = false;
1894     bool AcceptableWithoutRecovery = false;
1895     NamedDecl *ND = Corrected.getFoundDecl();
1896     if (ND) {
1897       if (Corrected.isOverloaded()) {
1898         OverloadCandidateSet OCS(R.getNameLoc(),
1899                                  OverloadCandidateSet::CSK_Normal);
1900         OverloadCandidateSet::iterator Best;
1901         for (NamedDecl *CD : Corrected) {
1902           if (FunctionTemplateDecl *FTD =
1903                    dyn_cast<FunctionTemplateDecl>(CD))
1904             AddTemplateOverloadCandidate(
1905                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1906                 Args, OCS);
1907           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1908             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1909               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1910                                    Args, OCS);
1911         }
1912         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1913         case OR_Success:
1914           ND = Best->FoundDecl;
1915           Corrected.setCorrectionDecl(ND);
1916           break;
1917         default:
1918           // FIXME: Arbitrarily pick the first declaration for the note.
1919           Corrected.setCorrectionDecl(ND);
1920           break;
1921         }
1922       }
1923       R.addDecl(ND);
1924       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1925         CXXRecordDecl *Record = nullptr;
1926         if (Corrected.getCorrectionSpecifier()) {
1927           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1928           Record = Ty->getAsCXXRecordDecl();
1929         }
1930         if (!Record)
1931           Record = cast<CXXRecordDecl>(
1932               ND->getDeclContext()->getRedeclContext());
1933         R.setNamingClass(Record);
1934       }
1935 
1936       auto *UnderlyingND = ND->getUnderlyingDecl();
1937       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1938                                isa<FunctionTemplateDecl>(UnderlyingND);
1939       // FIXME: If we ended up with a typo for a type name or
1940       // Objective-C class name, we're in trouble because the parser
1941       // is in the wrong place to recover. Suggest the typo
1942       // correction, but don't make it a fix-it since we're not going
1943       // to recover well anyway.
1944       AcceptableWithoutRecovery =
1945           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1946     } else {
1947       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1948       // because we aren't able to recover.
1949       AcceptableWithoutRecovery = true;
1950     }
1951 
1952     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1953       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1954                             ? diag::note_implicit_param_decl
1955                             : diag::note_previous_decl;
1956       if (SS.isEmpty())
1957         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1958                      PDiag(NoteID), AcceptableWithRecovery);
1959       else
1960         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1961                                   << Name << computeDeclContext(SS, false)
1962                                   << DroppedSpecifier << SS.getRange(),
1963                      PDiag(NoteID), AcceptableWithRecovery);
1964 
1965       // Tell the callee whether to try to recover.
1966       return !AcceptableWithRecovery;
1967     }
1968   }
1969   R.clear();
1970 
1971   // Emit a special diagnostic for failed member lookups.
1972   // FIXME: computing the declaration context might fail here (?)
1973   if (!SS.isEmpty()) {
1974     Diag(R.getNameLoc(), diag::err_no_member)
1975       << Name << computeDeclContext(SS, false)
1976       << SS.getRange();
1977     return true;
1978   }
1979 
1980   // Give up, we can't recover.
1981   Diag(R.getNameLoc(), diagnostic) << Name;
1982   return true;
1983 }
1984 
1985 /// In Microsoft mode, if we are inside a template class whose parent class has
1986 /// dependent base classes, and we can't resolve an unqualified identifier, then
1987 /// assume the identifier is a member of a dependent base class.  We can only
1988 /// recover successfully in static methods, instance methods, and other contexts
1989 /// where 'this' is available.  This doesn't precisely match MSVC's
1990 /// instantiation model, but it's close enough.
1991 static Expr *
1992 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1993                                DeclarationNameInfo &NameInfo,
1994                                SourceLocation TemplateKWLoc,
1995                                const TemplateArgumentListInfo *TemplateArgs) {
1996   // Only try to recover from lookup into dependent bases in static methods or
1997   // contexts where 'this' is available.
1998   QualType ThisType = S.getCurrentThisType();
1999   const CXXRecordDecl *RD = nullptr;
2000   if (!ThisType.isNull())
2001     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2002   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2003     RD = MD->getParent();
2004   if (!RD || !RD->hasAnyDependentBases())
2005     return nullptr;
2006 
2007   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2008   // is available, suggest inserting 'this->' as a fixit.
2009   SourceLocation Loc = NameInfo.getLoc();
2010   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2011   DB << NameInfo.getName() << RD;
2012 
2013   if (!ThisType.isNull()) {
2014     DB << FixItHint::CreateInsertion(Loc, "this->");
2015     return CXXDependentScopeMemberExpr::Create(
2016         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2017         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2018         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2019   }
2020 
2021   // Synthesize a fake NNS that points to the derived class.  This will
2022   // perform name lookup during template instantiation.
2023   CXXScopeSpec SS;
2024   auto *NNS =
2025       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2026   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2027   return DependentScopeDeclRefExpr::Create(
2028       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2029       TemplateArgs);
2030 }
2031 
2032 ExprResult
2033 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2034                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2035                         bool HasTrailingLParen, bool IsAddressOfOperand,
2036                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2037                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2038   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2039          "cannot be direct & operand and have a trailing lparen");
2040   if (SS.isInvalid())
2041     return ExprError();
2042 
2043   TemplateArgumentListInfo TemplateArgsBuffer;
2044 
2045   // Decompose the UnqualifiedId into the following data.
2046   DeclarationNameInfo NameInfo;
2047   const TemplateArgumentListInfo *TemplateArgs;
2048   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2049 
2050   DeclarationName Name = NameInfo.getName();
2051   IdentifierInfo *II = Name.getAsIdentifierInfo();
2052   SourceLocation NameLoc = NameInfo.getLoc();
2053 
2054   if (II && II->isEditorPlaceholder()) {
2055     // FIXME: When typed placeholders are supported we can create a typed
2056     // placeholder expression node.
2057     return ExprError();
2058   }
2059 
2060   // C++ [temp.dep.expr]p3:
2061   //   An id-expression is type-dependent if it contains:
2062   //     -- an identifier that was declared with a dependent type,
2063   //        (note: handled after lookup)
2064   //     -- a template-id that is dependent,
2065   //        (note: handled in BuildTemplateIdExpr)
2066   //     -- a conversion-function-id that specifies a dependent type,
2067   //     -- a nested-name-specifier that contains a class-name that
2068   //        names a dependent type.
2069   // Determine whether this is a member of an unknown specialization;
2070   // we need to handle these differently.
2071   bool DependentID = false;
2072   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2073       Name.getCXXNameType()->isDependentType()) {
2074     DependentID = true;
2075   } else if (SS.isSet()) {
2076     if (DeclContext *DC = computeDeclContext(SS, false)) {
2077       if (RequireCompleteDeclContext(SS, DC))
2078         return ExprError();
2079     } else {
2080       DependentID = true;
2081     }
2082   }
2083 
2084   if (DependentID)
2085     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2086                                       IsAddressOfOperand, TemplateArgs);
2087 
2088   // Perform the required lookup.
2089   LookupResult R(*this, NameInfo,
2090                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2091                      ? LookupObjCImplicitSelfParam
2092                      : LookupOrdinaryName);
2093   if (TemplateKWLoc.isValid() || TemplateArgs) {
2094     // Lookup the template name again to correctly establish the context in
2095     // which it was found. This is really unfortunate as we already did the
2096     // lookup to determine that it was a template name in the first place. If
2097     // this becomes a performance hit, we can work harder to preserve those
2098     // results until we get here but it's likely not worth it.
2099     bool MemberOfUnknownSpecialization;
2100     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2101                            MemberOfUnknownSpecialization, TemplateKWLoc))
2102       return ExprError();
2103 
2104     if (MemberOfUnknownSpecialization ||
2105         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2106       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2107                                         IsAddressOfOperand, TemplateArgs);
2108   } else {
2109     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2110     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2111 
2112     // If the result might be in a dependent base class, this is a dependent
2113     // id-expression.
2114     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2115       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2116                                         IsAddressOfOperand, TemplateArgs);
2117 
2118     // If this reference is in an Objective-C method, then we need to do
2119     // some special Objective-C lookup, too.
2120     if (IvarLookupFollowUp) {
2121       ExprResult E(LookupInObjCMethod(R, S, II, true));
2122       if (E.isInvalid())
2123         return ExprError();
2124 
2125       if (Expr *Ex = E.getAs<Expr>())
2126         return Ex;
2127     }
2128   }
2129 
2130   if (R.isAmbiguous())
2131     return ExprError();
2132 
2133   // This could be an implicitly declared function reference (legal in C90,
2134   // extension in C99, forbidden in C++).
2135   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2136     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2137     if (D) R.addDecl(D);
2138   }
2139 
2140   // Determine whether this name might be a candidate for
2141   // argument-dependent lookup.
2142   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2143 
2144   if (R.empty() && !ADL) {
2145     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2146       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2147                                                    TemplateKWLoc, TemplateArgs))
2148         return E;
2149     }
2150 
2151     // Don't diagnose an empty lookup for inline assembly.
2152     if (IsInlineAsmIdentifier)
2153       return ExprError();
2154 
2155     // If this name wasn't predeclared and if this is not a function
2156     // call, diagnose the problem.
2157     TypoExpr *TE = nullptr;
2158     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2159         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2160     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2161     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2162            "Typo correction callback misconfigured");
2163     if (CCC) {
2164       // Make sure the callback knows what the typo being diagnosed is.
2165       CCC->setTypoName(II);
2166       if (SS.isValid())
2167         CCC->setTypoNNS(SS.getScopeRep());
2168     }
2169     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2170     // a template name, but we happen to have always already looked up the name
2171     // before we get here if it must be a template name.
2172     if (DiagnoseEmptyLookup(S, SS, R,
2173                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2174                             nullptr, None, &TE)) {
2175       if (TE && KeywordReplacement) {
2176         auto &State = getTypoExprState(TE);
2177         auto BestTC = State.Consumer->getNextCorrection();
2178         if (BestTC.isKeyword()) {
2179           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2180           if (State.DiagHandler)
2181             State.DiagHandler(BestTC);
2182           KeywordReplacement->startToken();
2183           KeywordReplacement->setKind(II->getTokenID());
2184           KeywordReplacement->setIdentifierInfo(II);
2185           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2186           // Clean up the state associated with the TypoExpr, since it has
2187           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2188           clearDelayedTypo(TE);
2189           // Signal that a correction to a keyword was performed by returning a
2190           // valid-but-null ExprResult.
2191           return (Expr*)nullptr;
2192         }
2193         State.Consumer->resetCorrectionStream();
2194       }
2195       return TE ? TE : ExprError();
2196     }
2197 
2198     assert(!R.empty() &&
2199            "DiagnoseEmptyLookup returned false but added no results");
2200 
2201     // If we found an Objective-C instance variable, let
2202     // LookupInObjCMethod build the appropriate expression to
2203     // reference the ivar.
2204     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2205       R.clear();
2206       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2207       // In a hopelessly buggy code, Objective-C instance variable
2208       // lookup fails and no expression will be built to reference it.
2209       if (!E.isInvalid() && !E.get())
2210         return ExprError();
2211       return E;
2212     }
2213   }
2214 
2215   // This is guaranteed from this point on.
2216   assert(!R.empty() || ADL);
2217 
2218   // Check whether this might be a C++ implicit instance member access.
2219   // C++ [class.mfct.non-static]p3:
2220   //   When an id-expression that is not part of a class member access
2221   //   syntax and not used to form a pointer to member is used in the
2222   //   body of a non-static member function of class X, if name lookup
2223   //   resolves the name in the id-expression to a non-static non-type
2224   //   member of some class C, the id-expression is transformed into a
2225   //   class member access expression using (*this) as the
2226   //   postfix-expression to the left of the . operator.
2227   //
2228   // But we don't actually need to do this for '&' operands if R
2229   // resolved to a function or overloaded function set, because the
2230   // expression is ill-formed if it actually works out to be a
2231   // non-static member function:
2232   //
2233   // C++ [expr.ref]p4:
2234   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2235   //   [t]he expression can be used only as the left-hand operand of a
2236   //   member function call.
2237   //
2238   // There are other safeguards against such uses, but it's important
2239   // to get this right here so that we don't end up making a
2240   // spuriously dependent expression if we're inside a dependent
2241   // instance method.
2242   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2243     bool MightBeImplicitMember;
2244     if (!IsAddressOfOperand)
2245       MightBeImplicitMember = true;
2246     else if (!SS.isEmpty())
2247       MightBeImplicitMember = false;
2248     else if (R.isOverloadedResult())
2249       MightBeImplicitMember = false;
2250     else if (R.isUnresolvableResult())
2251       MightBeImplicitMember = true;
2252     else
2253       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2254                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2255                               isa<MSPropertyDecl>(R.getFoundDecl());
2256 
2257     if (MightBeImplicitMember)
2258       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2259                                              R, TemplateArgs, S);
2260   }
2261 
2262   if (TemplateArgs || TemplateKWLoc.isValid()) {
2263 
2264     // In C++1y, if this is a variable template id, then check it
2265     // in BuildTemplateIdExpr().
2266     // The single lookup result must be a variable template declaration.
2267     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2268         Id.TemplateId->Kind == TNK_Var_template) {
2269       assert(R.getAsSingle<VarTemplateDecl>() &&
2270              "There should only be one declaration found.");
2271     }
2272 
2273     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2274   }
2275 
2276   return BuildDeclarationNameExpr(SS, R, ADL);
2277 }
2278 
2279 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2280 /// declaration name, generally during template instantiation.
2281 /// There's a large number of things which don't need to be done along
2282 /// this path.
2283 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2284     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2285     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2286   DeclContext *DC = computeDeclContext(SS, false);
2287   if (!DC)
2288     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2289                                      NameInfo, /*TemplateArgs=*/nullptr);
2290 
2291   if (RequireCompleteDeclContext(SS, DC))
2292     return ExprError();
2293 
2294   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2295   LookupQualifiedName(R, DC);
2296 
2297   if (R.isAmbiguous())
2298     return ExprError();
2299 
2300   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2301     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2302                                      NameInfo, /*TemplateArgs=*/nullptr);
2303 
2304   if (R.empty()) {
2305     Diag(NameInfo.getLoc(), diag::err_no_member)
2306       << NameInfo.getName() << DC << SS.getRange();
2307     return ExprError();
2308   }
2309 
2310   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2311     // Diagnose a missing typename if this resolved unambiguously to a type in
2312     // a dependent context.  If we can recover with a type, downgrade this to
2313     // a warning in Microsoft compatibility mode.
2314     unsigned DiagID = diag::err_typename_missing;
2315     if (RecoveryTSI && getLangOpts().MSVCCompat)
2316       DiagID = diag::ext_typename_missing;
2317     SourceLocation Loc = SS.getBeginLoc();
2318     auto D = Diag(Loc, DiagID);
2319     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2320       << SourceRange(Loc, NameInfo.getEndLoc());
2321 
2322     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2323     // context.
2324     if (!RecoveryTSI)
2325       return ExprError();
2326 
2327     // Only issue the fixit if we're prepared to recover.
2328     D << FixItHint::CreateInsertion(Loc, "typename ");
2329 
2330     // Recover by pretending this was an elaborated type.
2331     QualType Ty = Context.getTypeDeclType(TD);
2332     TypeLocBuilder TLB;
2333     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2334 
2335     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2336     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2337     QTL.setElaboratedKeywordLoc(SourceLocation());
2338     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2339 
2340     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2341 
2342     return ExprEmpty();
2343   }
2344 
2345   // Defend against this resolving to an implicit member access. We usually
2346   // won't get here if this might be a legitimate a class member (we end up in
2347   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2348   // a pointer-to-member or in an unevaluated context in C++11.
2349   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2350     return BuildPossibleImplicitMemberExpr(SS,
2351                                            /*TemplateKWLoc=*/SourceLocation(),
2352                                            R, /*TemplateArgs=*/nullptr, S);
2353 
2354   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2355 }
2356 
2357 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2358 /// detected that we're currently inside an ObjC method.  Perform some
2359 /// additional lookup.
2360 ///
2361 /// Ideally, most of this would be done by lookup, but there's
2362 /// actually quite a lot of extra work involved.
2363 ///
2364 /// Returns a null sentinel to indicate trivial success.
2365 ExprResult
2366 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2367                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2368   SourceLocation Loc = Lookup.getNameLoc();
2369   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2370 
2371   // Check for error condition which is already reported.
2372   if (!CurMethod)
2373     return ExprError();
2374 
2375   // There are two cases to handle here.  1) scoped lookup could have failed,
2376   // in which case we should look for an ivar.  2) scoped lookup could have
2377   // found a decl, but that decl is outside the current instance method (i.e.
2378   // a global variable).  In these two cases, we do a lookup for an ivar with
2379   // this name, if the lookup sucedes, we replace it our current decl.
2380 
2381   // If we're in a class method, we don't normally want to look for
2382   // ivars.  But if we don't find anything else, and there's an
2383   // ivar, that's an error.
2384   bool IsClassMethod = CurMethod->isClassMethod();
2385 
2386   bool LookForIvars;
2387   if (Lookup.empty())
2388     LookForIvars = true;
2389   else if (IsClassMethod)
2390     LookForIvars = false;
2391   else
2392     LookForIvars = (Lookup.isSingleResult() &&
2393                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2394   ObjCInterfaceDecl *IFace = nullptr;
2395   if (LookForIvars) {
2396     IFace = CurMethod->getClassInterface();
2397     ObjCInterfaceDecl *ClassDeclared;
2398     ObjCIvarDecl *IV = nullptr;
2399     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2400       // Diagnose using an ivar in a class method.
2401       if (IsClassMethod)
2402         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2403                          << IV->getDeclName());
2404 
2405       // If we're referencing an invalid decl, just return this as a silent
2406       // error node.  The error diagnostic was already emitted on the decl.
2407       if (IV->isInvalidDecl())
2408         return ExprError();
2409 
2410       // Check if referencing a field with __attribute__((deprecated)).
2411       if (DiagnoseUseOfDecl(IV, Loc))
2412         return ExprError();
2413 
2414       // Diagnose the use of an ivar outside of the declaring class.
2415       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2416           !declaresSameEntity(ClassDeclared, IFace) &&
2417           !getLangOpts().DebuggerSupport)
2418         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2419 
2420       // FIXME: This should use a new expr for a direct reference, don't
2421       // turn this into Self->ivar, just return a BareIVarExpr or something.
2422       IdentifierInfo &II = Context.Idents.get("self");
2423       UnqualifiedId SelfName;
2424       SelfName.setIdentifier(&II, SourceLocation());
2425       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2426       CXXScopeSpec SelfScopeSpec;
2427       SourceLocation TemplateKWLoc;
2428       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2429                                               SelfName, false, false);
2430       if (SelfExpr.isInvalid())
2431         return ExprError();
2432 
2433       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2434       if (SelfExpr.isInvalid())
2435         return ExprError();
2436 
2437       MarkAnyDeclReferenced(Loc, IV, true);
2438 
2439       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2440       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2441           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2442         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2443 
2444       ObjCIvarRefExpr *Result = new (Context)
2445           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2446                           IV->getLocation(), SelfExpr.get(), true, true);
2447 
2448       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2449         if (!isUnevaluatedContext() &&
2450             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2451           getCurFunction()->recordUseOfWeak(Result);
2452       }
2453       if (getLangOpts().ObjCAutoRefCount) {
2454         if (CurContext->isClosure())
2455           Diag(Loc, diag::warn_implicitly_retains_self)
2456             << FixItHint::CreateInsertion(Loc, "self->");
2457       }
2458 
2459       return Result;
2460     }
2461   } else if (CurMethod->isInstanceMethod()) {
2462     // We should warn if a local variable hides an ivar.
2463     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2464       ObjCInterfaceDecl *ClassDeclared;
2465       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2466         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2467             declaresSameEntity(IFace, ClassDeclared))
2468           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2469       }
2470     }
2471   } else if (Lookup.isSingleResult() &&
2472              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2473     // If accessing a stand-alone ivar in a class method, this is an error.
2474     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2475       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2476                        << IV->getDeclName());
2477   }
2478 
2479   if (Lookup.empty() && II && AllowBuiltinCreation) {
2480     // FIXME. Consolidate this with similar code in LookupName.
2481     if (unsigned BuiltinID = II->getBuiltinID()) {
2482       if (!(getLangOpts().CPlusPlus &&
2483             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2484         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2485                                            S, Lookup.isForRedeclaration(),
2486                                            Lookup.getNameLoc());
2487         if (D) Lookup.addDecl(D);
2488       }
2489     }
2490   }
2491   // Sentinel value saying that we didn't do anything special.
2492   return ExprResult((Expr *)nullptr);
2493 }
2494 
2495 /// Cast a base object to a member's actual type.
2496 ///
2497 /// Logically this happens in three phases:
2498 ///
2499 /// * First we cast from the base type to the naming class.
2500 ///   The naming class is the class into which we were looking
2501 ///   when we found the member;  it's the qualifier type if a
2502 ///   qualifier was provided, and otherwise it's the base type.
2503 ///
2504 /// * Next we cast from the naming class to the declaring class.
2505 ///   If the member we found was brought into a class's scope by
2506 ///   a using declaration, this is that class;  otherwise it's
2507 ///   the class declaring the member.
2508 ///
2509 /// * Finally we cast from the declaring class to the "true"
2510 ///   declaring class of the member.  This conversion does not
2511 ///   obey access control.
2512 ExprResult
2513 Sema::PerformObjectMemberConversion(Expr *From,
2514                                     NestedNameSpecifier *Qualifier,
2515                                     NamedDecl *FoundDecl,
2516                                     NamedDecl *Member) {
2517   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2518   if (!RD)
2519     return From;
2520 
2521   QualType DestRecordType;
2522   QualType DestType;
2523   QualType FromRecordType;
2524   QualType FromType = From->getType();
2525   bool PointerConversions = false;
2526   if (isa<FieldDecl>(Member)) {
2527     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2528 
2529     if (FromType->getAs<PointerType>()) {
2530       DestType = Context.getPointerType(DestRecordType);
2531       FromRecordType = FromType->getPointeeType();
2532       PointerConversions = true;
2533     } else {
2534       DestType = DestRecordType;
2535       FromRecordType = FromType;
2536     }
2537   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2538     if (Method->isStatic())
2539       return From;
2540 
2541     DestType = Method->getThisType(Context);
2542     DestRecordType = DestType->getPointeeType();
2543 
2544     if (FromType->getAs<PointerType>()) {
2545       FromRecordType = FromType->getPointeeType();
2546       PointerConversions = true;
2547     } else {
2548       FromRecordType = FromType;
2549       DestType = DestRecordType;
2550     }
2551   } else {
2552     // No conversion necessary.
2553     return From;
2554   }
2555 
2556   if (DestType->isDependentType() || FromType->isDependentType())
2557     return From;
2558 
2559   // If the unqualified types are the same, no conversion is necessary.
2560   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2561     return From;
2562 
2563   SourceRange FromRange = From->getSourceRange();
2564   SourceLocation FromLoc = FromRange.getBegin();
2565 
2566   ExprValueKind VK = From->getValueKind();
2567 
2568   // C++ [class.member.lookup]p8:
2569   //   [...] Ambiguities can often be resolved by qualifying a name with its
2570   //   class name.
2571   //
2572   // If the member was a qualified name and the qualified referred to a
2573   // specific base subobject type, we'll cast to that intermediate type
2574   // first and then to the object in which the member is declared. That allows
2575   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2576   //
2577   //   class Base { public: int x; };
2578   //   class Derived1 : public Base { };
2579   //   class Derived2 : public Base { };
2580   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2581   //
2582   //   void VeryDerived::f() {
2583   //     x = 17; // error: ambiguous base subobjects
2584   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2585   //   }
2586   if (Qualifier && Qualifier->getAsType()) {
2587     QualType QType = QualType(Qualifier->getAsType(), 0);
2588     assert(QType->isRecordType() && "lookup done with non-record type");
2589 
2590     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2591 
2592     // In C++98, the qualifier type doesn't actually have to be a base
2593     // type of the object type, in which case we just ignore it.
2594     // Otherwise build the appropriate casts.
2595     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2596       CXXCastPath BasePath;
2597       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2598                                        FromLoc, FromRange, &BasePath))
2599         return ExprError();
2600 
2601       if (PointerConversions)
2602         QType = Context.getPointerType(QType);
2603       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2604                                VK, &BasePath).get();
2605 
2606       FromType = QType;
2607       FromRecordType = QRecordType;
2608 
2609       // If the qualifier type was the same as the destination type,
2610       // we're done.
2611       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2612         return From;
2613     }
2614   }
2615 
2616   bool IgnoreAccess = false;
2617 
2618   // If we actually found the member through a using declaration, cast
2619   // down to the using declaration's type.
2620   //
2621   // Pointer equality is fine here because only one declaration of a
2622   // class ever has member declarations.
2623   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2624     assert(isa<UsingShadowDecl>(FoundDecl));
2625     QualType URecordType = Context.getTypeDeclType(
2626                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2627 
2628     // We only need to do this if the naming-class to declaring-class
2629     // conversion is non-trivial.
2630     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2631       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2632       CXXCastPath BasePath;
2633       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2634                                        FromLoc, FromRange, &BasePath))
2635         return ExprError();
2636 
2637       QualType UType = URecordType;
2638       if (PointerConversions)
2639         UType = Context.getPointerType(UType);
2640       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2641                                VK, &BasePath).get();
2642       FromType = UType;
2643       FromRecordType = URecordType;
2644     }
2645 
2646     // We don't do access control for the conversion from the
2647     // declaring class to the true declaring class.
2648     IgnoreAccess = true;
2649   }
2650 
2651   CXXCastPath BasePath;
2652   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2653                                    FromLoc, FromRange, &BasePath,
2654                                    IgnoreAccess))
2655     return ExprError();
2656 
2657   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2658                            VK, &BasePath);
2659 }
2660 
2661 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2662                                       const LookupResult &R,
2663                                       bool HasTrailingLParen) {
2664   // Only when used directly as the postfix-expression of a call.
2665   if (!HasTrailingLParen)
2666     return false;
2667 
2668   // Never if a scope specifier was provided.
2669   if (SS.isSet())
2670     return false;
2671 
2672   // Only in C++ or ObjC++.
2673   if (!getLangOpts().CPlusPlus)
2674     return false;
2675 
2676   // Turn off ADL when we find certain kinds of declarations during
2677   // normal lookup:
2678   for (NamedDecl *D : R) {
2679     // C++0x [basic.lookup.argdep]p3:
2680     //     -- a declaration of a class member
2681     // Since using decls preserve this property, we check this on the
2682     // original decl.
2683     if (D->isCXXClassMember())
2684       return false;
2685 
2686     // C++0x [basic.lookup.argdep]p3:
2687     //     -- a block-scope function declaration that is not a
2688     //        using-declaration
2689     // NOTE: we also trigger this for function templates (in fact, we
2690     // don't check the decl type at all, since all other decl types
2691     // turn off ADL anyway).
2692     if (isa<UsingShadowDecl>(D))
2693       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2694     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2695       return false;
2696 
2697     // C++0x [basic.lookup.argdep]p3:
2698     //     -- a declaration that is neither a function or a function
2699     //        template
2700     // And also for builtin functions.
2701     if (isa<FunctionDecl>(D)) {
2702       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2703 
2704       // But also builtin functions.
2705       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2706         return false;
2707     } else if (!isa<FunctionTemplateDecl>(D))
2708       return false;
2709   }
2710 
2711   return true;
2712 }
2713 
2714 
2715 /// Diagnoses obvious problems with the use of the given declaration
2716 /// as an expression.  This is only actually called for lookups that
2717 /// were not overloaded, and it doesn't promise that the declaration
2718 /// will in fact be used.
2719 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2720   if (D->isInvalidDecl())
2721     return true;
2722 
2723   if (isa<TypedefNameDecl>(D)) {
2724     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2725     return true;
2726   }
2727 
2728   if (isa<ObjCInterfaceDecl>(D)) {
2729     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2730     return true;
2731   }
2732 
2733   if (isa<NamespaceDecl>(D)) {
2734     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2735     return true;
2736   }
2737 
2738   return false;
2739 }
2740 
2741 // Certain multiversion types should be treated as overloaded even when there is
2742 // only one result.
2743 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2744   assert(R.isSingleResult() && "Expected only a single result");
2745   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2746   return FD &&
2747          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2748 }
2749 
2750 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2751                                           LookupResult &R, bool NeedsADL,
2752                                           bool AcceptInvalidDecl) {
2753   // If this is a single, fully-resolved result and we don't need ADL,
2754   // just build an ordinary singleton decl ref.
2755   if (!NeedsADL && R.isSingleResult() &&
2756       !R.getAsSingle<FunctionTemplateDecl>() &&
2757       !ShouldLookupResultBeMultiVersionOverload(R))
2758     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2759                                     R.getRepresentativeDecl(), nullptr,
2760                                     AcceptInvalidDecl);
2761 
2762   // We only need to check the declaration if there's exactly one
2763   // result, because in the overloaded case the results can only be
2764   // functions and function templates.
2765   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2766       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2767     return ExprError();
2768 
2769   // Otherwise, just build an unresolved lookup expression.  Suppress
2770   // any lookup-related diagnostics; we'll hash these out later, when
2771   // we've picked a target.
2772   R.suppressDiagnostics();
2773 
2774   UnresolvedLookupExpr *ULE
2775     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2776                                    SS.getWithLocInContext(Context),
2777                                    R.getLookupNameInfo(),
2778                                    NeedsADL, R.isOverloadedResult(),
2779                                    R.begin(), R.end());
2780 
2781   return ULE;
2782 }
2783 
2784 static void
2785 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2786                                    ValueDecl *var, DeclContext *DC);
2787 
2788 /// Complete semantic analysis for a reference to the given declaration.
2789 ExprResult Sema::BuildDeclarationNameExpr(
2790     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2791     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2792     bool AcceptInvalidDecl) {
2793   assert(D && "Cannot refer to a NULL declaration");
2794   assert(!isa<FunctionTemplateDecl>(D) &&
2795          "Cannot refer unambiguously to a function template");
2796 
2797   SourceLocation Loc = NameInfo.getLoc();
2798   if (CheckDeclInExpr(*this, Loc, D))
2799     return ExprError();
2800 
2801   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2802     // Specifically diagnose references to class templates that are missing
2803     // a template argument list.
2804     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2805     return ExprError();
2806   }
2807 
2808   // Make sure that we're referring to a value.
2809   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2810   if (!VD) {
2811     Diag(Loc, diag::err_ref_non_value)
2812       << D << SS.getRange();
2813     Diag(D->getLocation(), diag::note_declared_at);
2814     return ExprError();
2815   }
2816 
2817   // Check whether this declaration can be used. Note that we suppress
2818   // this check when we're going to perform argument-dependent lookup
2819   // on this function name, because this might not be the function
2820   // that overload resolution actually selects.
2821   if (DiagnoseUseOfDecl(VD, Loc))
2822     return ExprError();
2823 
2824   // Only create DeclRefExpr's for valid Decl's.
2825   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2826     return ExprError();
2827 
2828   // Handle members of anonymous structs and unions.  If we got here,
2829   // and the reference is to a class member indirect field, then this
2830   // must be the subject of a pointer-to-member expression.
2831   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2832     if (!indirectField->isCXXClassMember())
2833       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2834                                                       indirectField);
2835 
2836   {
2837     QualType type = VD->getType();
2838     if (type.isNull())
2839       return ExprError();
2840     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2841       // C++ [except.spec]p17:
2842       //   An exception-specification is considered to be needed when:
2843       //   - in an expression, the function is the unique lookup result or
2844       //     the selected member of a set of overloaded functions.
2845       ResolveExceptionSpec(Loc, FPT);
2846       type = VD->getType();
2847     }
2848     ExprValueKind valueKind = VK_RValue;
2849 
2850     switch (D->getKind()) {
2851     // Ignore all the non-ValueDecl kinds.
2852 #define ABSTRACT_DECL(kind)
2853 #define VALUE(type, base)
2854 #define DECL(type, base) \
2855     case Decl::type:
2856 #include "clang/AST/DeclNodes.inc"
2857       llvm_unreachable("invalid value decl kind");
2858 
2859     // These shouldn't make it here.
2860     case Decl::ObjCAtDefsField:
2861     case Decl::ObjCIvar:
2862       llvm_unreachable("forming non-member reference to ivar?");
2863 
2864     // Enum constants are always r-values and never references.
2865     // Unresolved using declarations are dependent.
2866     case Decl::EnumConstant:
2867     case Decl::UnresolvedUsingValue:
2868     case Decl::OMPDeclareReduction:
2869       valueKind = VK_RValue;
2870       break;
2871 
2872     // Fields and indirect fields that got here must be for
2873     // pointer-to-member expressions; we just call them l-values for
2874     // internal consistency, because this subexpression doesn't really
2875     // exist in the high-level semantics.
2876     case Decl::Field:
2877     case Decl::IndirectField:
2878       assert(getLangOpts().CPlusPlus &&
2879              "building reference to field in C?");
2880 
2881       // These can't have reference type in well-formed programs, but
2882       // for internal consistency we do this anyway.
2883       type = type.getNonReferenceType();
2884       valueKind = VK_LValue;
2885       break;
2886 
2887     // Non-type template parameters are either l-values or r-values
2888     // depending on the type.
2889     case Decl::NonTypeTemplateParm: {
2890       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2891         type = reftype->getPointeeType();
2892         valueKind = VK_LValue; // even if the parameter is an r-value reference
2893         break;
2894       }
2895 
2896       // For non-references, we need to strip qualifiers just in case
2897       // the template parameter was declared as 'const int' or whatever.
2898       valueKind = VK_RValue;
2899       type = type.getUnqualifiedType();
2900       break;
2901     }
2902 
2903     case Decl::Var:
2904     case Decl::VarTemplateSpecialization:
2905     case Decl::VarTemplatePartialSpecialization:
2906     case Decl::Decomposition:
2907     case Decl::OMPCapturedExpr:
2908       // In C, "extern void blah;" is valid and is an r-value.
2909       if (!getLangOpts().CPlusPlus &&
2910           !type.hasQualifiers() &&
2911           type->isVoidType()) {
2912         valueKind = VK_RValue;
2913         break;
2914       }
2915       LLVM_FALLTHROUGH;
2916 
2917     case Decl::ImplicitParam:
2918     case Decl::ParmVar: {
2919       // These are always l-values.
2920       valueKind = VK_LValue;
2921       type = type.getNonReferenceType();
2922 
2923       // FIXME: Does the addition of const really only apply in
2924       // potentially-evaluated contexts? Since the variable isn't actually
2925       // captured in an unevaluated context, it seems that the answer is no.
2926       if (!isUnevaluatedContext()) {
2927         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2928         if (!CapturedType.isNull())
2929           type = CapturedType;
2930       }
2931 
2932       break;
2933     }
2934 
2935     case Decl::Binding: {
2936       // These are always lvalues.
2937       valueKind = VK_LValue;
2938       type = type.getNonReferenceType();
2939       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2940       // decides how that's supposed to work.
2941       auto *BD = cast<BindingDecl>(VD);
2942       if (BD->getDeclContext()->isFunctionOrMethod() &&
2943           BD->getDeclContext() != CurContext)
2944         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2945       break;
2946     }
2947 
2948     case Decl::Function: {
2949       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2950         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2951           type = Context.BuiltinFnTy;
2952           valueKind = VK_RValue;
2953           break;
2954         }
2955       }
2956 
2957       const FunctionType *fty = type->castAs<FunctionType>();
2958 
2959       // If we're referring to a function with an __unknown_anytype
2960       // result type, make the entire expression __unknown_anytype.
2961       if (fty->getReturnType() == Context.UnknownAnyTy) {
2962         type = Context.UnknownAnyTy;
2963         valueKind = VK_RValue;
2964         break;
2965       }
2966 
2967       // Functions are l-values in C++.
2968       if (getLangOpts().CPlusPlus) {
2969         valueKind = VK_LValue;
2970         break;
2971       }
2972 
2973       // C99 DR 316 says that, if a function type comes from a
2974       // function definition (without a prototype), that type is only
2975       // used for checking compatibility. Therefore, when referencing
2976       // the function, we pretend that we don't have the full function
2977       // type.
2978       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2979           isa<FunctionProtoType>(fty))
2980         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2981                                               fty->getExtInfo());
2982 
2983       // Functions are r-values in C.
2984       valueKind = VK_RValue;
2985       break;
2986     }
2987 
2988     case Decl::CXXDeductionGuide:
2989       llvm_unreachable("building reference to deduction guide");
2990 
2991     case Decl::MSProperty:
2992       valueKind = VK_LValue;
2993       break;
2994 
2995     case Decl::CXXMethod:
2996       // If we're referring to a method with an __unknown_anytype
2997       // result type, make the entire expression __unknown_anytype.
2998       // This should only be possible with a type written directly.
2999       if (const FunctionProtoType *proto
3000             = dyn_cast<FunctionProtoType>(VD->getType()))
3001         if (proto->getReturnType() == Context.UnknownAnyTy) {
3002           type = Context.UnknownAnyTy;
3003           valueKind = VK_RValue;
3004           break;
3005         }
3006 
3007       // C++ methods are l-values if static, r-values if non-static.
3008       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3009         valueKind = VK_LValue;
3010         break;
3011       }
3012       LLVM_FALLTHROUGH;
3013 
3014     case Decl::CXXConversion:
3015     case Decl::CXXDestructor:
3016     case Decl::CXXConstructor:
3017       valueKind = VK_RValue;
3018       break;
3019     }
3020 
3021     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3022                             TemplateArgs);
3023   }
3024 }
3025 
3026 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3027                                     SmallString<32> &Target) {
3028   Target.resize(CharByteWidth * (Source.size() + 1));
3029   char *ResultPtr = &Target[0];
3030   const llvm::UTF8 *ErrorPtr;
3031   bool success =
3032       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3033   (void)success;
3034   assert(success);
3035   Target.resize(ResultPtr - &Target[0]);
3036 }
3037 
3038 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3039                                      PredefinedExpr::IdentType IT) {
3040   // Pick the current block, lambda, captured statement or function.
3041   Decl *currentDecl = nullptr;
3042   if (const BlockScopeInfo *BSI = getCurBlock())
3043     currentDecl = BSI->TheDecl;
3044   else if (const LambdaScopeInfo *LSI = getCurLambda())
3045     currentDecl = LSI->CallOperator;
3046   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3047     currentDecl = CSI->TheCapturedDecl;
3048   else
3049     currentDecl = getCurFunctionOrMethodDecl();
3050 
3051   if (!currentDecl) {
3052     Diag(Loc, diag::ext_predef_outside_function);
3053     currentDecl = Context.getTranslationUnitDecl();
3054   }
3055 
3056   QualType ResTy;
3057   StringLiteral *SL = nullptr;
3058   if (cast<DeclContext>(currentDecl)->isDependentContext())
3059     ResTy = Context.DependentTy;
3060   else {
3061     // Pre-defined identifiers are of type char[x], where x is the length of
3062     // the string.
3063     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3064     unsigned Length = Str.length();
3065 
3066     llvm::APInt LengthI(32, Length + 1);
3067     if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) {
3068       ResTy =
3069           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3070       SmallString<32> RawChars;
3071       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3072                               Str, RawChars);
3073       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3074                                            /*IndexTypeQuals*/ 0);
3075       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3076                                  /*Pascal*/ false, ResTy, Loc);
3077     } else {
3078       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3079       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3080                                            /*IndexTypeQuals*/ 0);
3081       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3082                                  /*Pascal*/ false, ResTy, Loc);
3083     }
3084   }
3085 
3086   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3087 }
3088 
3089 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3090   PredefinedExpr::IdentType IT;
3091 
3092   switch (Kind) {
3093   default: llvm_unreachable("Unknown simple primary expr!");
3094   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3095   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3096   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3097   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3098   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS]
3099   case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS]
3100   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3101   }
3102 
3103   return BuildPredefinedExpr(Loc, IT);
3104 }
3105 
3106 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3107   SmallString<16> CharBuffer;
3108   bool Invalid = false;
3109   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3110   if (Invalid)
3111     return ExprError();
3112 
3113   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3114                             PP, Tok.getKind());
3115   if (Literal.hadError())
3116     return ExprError();
3117 
3118   QualType Ty;
3119   if (Literal.isWide())
3120     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3121   else if (Literal.isUTF8() && getLangOpts().Char8)
3122     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3123   else if (Literal.isUTF16())
3124     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3125   else if (Literal.isUTF32())
3126     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3127   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3128     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3129   else
3130     Ty = Context.CharTy;  // 'x' -> char in C++
3131 
3132   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3133   if (Literal.isWide())
3134     Kind = CharacterLiteral::Wide;
3135   else if (Literal.isUTF16())
3136     Kind = CharacterLiteral::UTF16;
3137   else if (Literal.isUTF32())
3138     Kind = CharacterLiteral::UTF32;
3139   else if (Literal.isUTF8())
3140     Kind = CharacterLiteral::UTF8;
3141 
3142   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3143                                              Tok.getLocation());
3144 
3145   if (Literal.getUDSuffix().empty())
3146     return Lit;
3147 
3148   // We're building a user-defined literal.
3149   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3150   SourceLocation UDSuffixLoc =
3151     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3152 
3153   // Make sure we're allowed user-defined literals here.
3154   if (!UDLScope)
3155     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3156 
3157   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3158   //   operator "" X (ch)
3159   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3160                                         Lit, Tok.getLocation());
3161 }
3162 
3163 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3164   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3165   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3166                                 Context.IntTy, Loc);
3167 }
3168 
3169 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3170                                   QualType Ty, SourceLocation Loc) {
3171   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3172 
3173   using llvm::APFloat;
3174   APFloat Val(Format);
3175 
3176   APFloat::opStatus result = Literal.GetFloatValue(Val);
3177 
3178   // Overflow is always an error, but underflow is only an error if
3179   // we underflowed to zero (APFloat reports denormals as underflow).
3180   if ((result & APFloat::opOverflow) ||
3181       ((result & APFloat::opUnderflow) && Val.isZero())) {
3182     unsigned diagnostic;
3183     SmallString<20> buffer;
3184     if (result & APFloat::opOverflow) {
3185       diagnostic = diag::warn_float_overflow;
3186       APFloat::getLargest(Format).toString(buffer);
3187     } else {
3188       diagnostic = diag::warn_float_underflow;
3189       APFloat::getSmallest(Format).toString(buffer);
3190     }
3191 
3192     S.Diag(Loc, diagnostic)
3193       << Ty
3194       << StringRef(buffer.data(), buffer.size());
3195   }
3196 
3197   bool isExact = (result == APFloat::opOK);
3198   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3199 }
3200 
3201 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3202   assert(E && "Invalid expression");
3203 
3204   if (E->isValueDependent())
3205     return false;
3206 
3207   QualType QT = E->getType();
3208   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3209     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3210     return true;
3211   }
3212 
3213   llvm::APSInt ValueAPS;
3214   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3215 
3216   if (R.isInvalid())
3217     return true;
3218 
3219   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3220   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3221     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3222         << ValueAPS.toString(10) << ValueIsPositive;
3223     return true;
3224   }
3225 
3226   return false;
3227 }
3228 
3229 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3230   // Fast path for a single digit (which is quite common).  A single digit
3231   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3232   if (Tok.getLength() == 1) {
3233     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3234     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3235   }
3236 
3237   SmallString<128> SpellingBuffer;
3238   // NumericLiteralParser wants to overread by one character.  Add padding to
3239   // the buffer in case the token is copied to the buffer.  If getSpelling()
3240   // returns a StringRef to the memory buffer, it should have a null char at
3241   // the EOF, so it is also safe.
3242   SpellingBuffer.resize(Tok.getLength() + 1);
3243 
3244   // Get the spelling of the token, which eliminates trigraphs, etc.
3245   bool Invalid = false;
3246   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3247   if (Invalid)
3248     return ExprError();
3249 
3250   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3251   if (Literal.hadError)
3252     return ExprError();
3253 
3254   if (Literal.hasUDSuffix()) {
3255     // We're building a user-defined literal.
3256     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3257     SourceLocation UDSuffixLoc =
3258       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3259 
3260     // Make sure we're allowed user-defined literals here.
3261     if (!UDLScope)
3262       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3263 
3264     QualType CookedTy;
3265     if (Literal.isFloatingLiteral()) {
3266       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3267       // long double, the literal is treated as a call of the form
3268       //   operator "" X (f L)
3269       CookedTy = Context.LongDoubleTy;
3270     } else {
3271       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3272       // unsigned long long, the literal is treated as a call of the form
3273       //   operator "" X (n ULL)
3274       CookedTy = Context.UnsignedLongLongTy;
3275     }
3276 
3277     DeclarationName OpName =
3278       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3279     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3280     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3281 
3282     SourceLocation TokLoc = Tok.getLocation();
3283 
3284     // Perform literal operator lookup to determine if we're building a raw
3285     // literal or a cooked one.
3286     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3287     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3288                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3289                                   /*AllowStringTemplate*/ false,
3290                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3291     case LOLR_ErrorNoDiagnostic:
3292       // Lookup failure for imaginary constants isn't fatal, there's still the
3293       // GNU extension producing _Complex types.
3294       break;
3295     case LOLR_Error:
3296       return ExprError();
3297     case LOLR_Cooked: {
3298       Expr *Lit;
3299       if (Literal.isFloatingLiteral()) {
3300         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3301       } else {
3302         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3303         if (Literal.GetIntegerValue(ResultVal))
3304           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3305               << /* Unsigned */ 1;
3306         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3307                                      Tok.getLocation());
3308       }
3309       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3310     }
3311 
3312     case LOLR_Raw: {
3313       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3314       // literal is treated as a call of the form
3315       //   operator "" X ("n")
3316       unsigned Length = Literal.getUDSuffixOffset();
3317       QualType StrTy = Context.getConstantArrayType(
3318           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3319           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3320       Expr *Lit = StringLiteral::Create(
3321           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3322           /*Pascal*/false, StrTy, &TokLoc, 1);
3323       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3324     }
3325 
3326     case LOLR_Template: {
3327       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3328       // template), L is treated as a call fo the form
3329       //   operator "" X <'c1', 'c2', ... 'ck'>()
3330       // where n is the source character sequence c1 c2 ... ck.
3331       TemplateArgumentListInfo ExplicitArgs;
3332       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3333       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3334       llvm::APSInt Value(CharBits, CharIsUnsigned);
3335       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3336         Value = TokSpelling[I];
3337         TemplateArgument Arg(Context, Value, Context.CharTy);
3338         TemplateArgumentLocInfo ArgInfo;
3339         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3340       }
3341       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3342                                       &ExplicitArgs);
3343     }
3344     case LOLR_StringTemplate:
3345       llvm_unreachable("unexpected literal operator lookup result");
3346     }
3347   }
3348 
3349   Expr *Res;
3350 
3351   if (Literal.isFixedPointLiteral()) {
3352     QualType Ty;
3353 
3354     if (Literal.isAccum) {
3355       if (Literal.isHalf) {
3356         Ty = Context.ShortAccumTy;
3357       } else if (Literal.isLong) {
3358         Ty = Context.LongAccumTy;
3359       } else {
3360         Ty = Context.AccumTy;
3361       }
3362     } else if (Literal.isFract) {
3363       if (Literal.isHalf) {
3364         Ty = Context.ShortFractTy;
3365       } else if (Literal.isLong) {
3366         Ty = Context.LongFractTy;
3367       } else {
3368         Ty = Context.FractTy;
3369       }
3370     }
3371 
3372     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3373 
3374     bool isSigned = !Literal.isUnsigned;
3375     unsigned scale = Context.getFixedPointScale(Ty);
3376     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3377 
3378     llvm::APInt Val(bit_width, 0, isSigned);
3379     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3380     bool ValIsZero = Val.isNullValue() && !Overflowed;
3381 
3382     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3383     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3384       // Clause 6.4.4 - The value of a constant shall be in the range of
3385       // representable values for its type, with exception for constants of a
3386       // fract type with a value of exactly 1; such a constant shall denote
3387       // the maximal value for the type.
3388       --Val;
3389     else if (Val.ugt(MaxVal) || Overflowed)
3390       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3391 
3392     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3393                                               Tok.getLocation(), scale);
3394   } else if (Literal.isFloatingLiteral()) {
3395     QualType Ty;
3396     if (Literal.isHalf){
3397       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3398         Ty = Context.HalfTy;
3399       else {
3400         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3401         return ExprError();
3402       }
3403     } else if (Literal.isFloat)
3404       Ty = Context.FloatTy;
3405     else if (Literal.isLong)
3406       Ty = Context.LongDoubleTy;
3407     else if (Literal.isFloat16)
3408       Ty = Context.Float16Ty;
3409     else if (Literal.isFloat128)
3410       Ty = Context.Float128Ty;
3411     else
3412       Ty = Context.DoubleTy;
3413 
3414     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3415 
3416     if (Ty == Context.DoubleTy) {
3417       if (getLangOpts().SinglePrecisionConstants) {
3418         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3419         if (BTy->getKind() != BuiltinType::Float) {
3420           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3421         }
3422       } else if (getLangOpts().OpenCL &&
3423                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3424         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3425         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3426         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3427       }
3428     }
3429   } else if (!Literal.isIntegerLiteral()) {
3430     return ExprError();
3431   } else {
3432     QualType Ty;
3433 
3434     // 'long long' is a C99 or C++11 feature.
3435     if (!getLangOpts().C99 && Literal.isLongLong) {
3436       if (getLangOpts().CPlusPlus)
3437         Diag(Tok.getLocation(),
3438              getLangOpts().CPlusPlus11 ?
3439              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3440       else
3441         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3442     }
3443 
3444     // Get the value in the widest-possible width.
3445     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3446     llvm::APInt ResultVal(MaxWidth, 0);
3447 
3448     if (Literal.GetIntegerValue(ResultVal)) {
3449       // If this value didn't fit into uintmax_t, error and force to ull.
3450       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3451           << /* Unsigned */ 1;
3452       Ty = Context.UnsignedLongLongTy;
3453       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3454              "long long is not intmax_t?");
3455     } else {
3456       // If this value fits into a ULL, try to figure out what else it fits into
3457       // according to the rules of C99 6.4.4.1p5.
3458 
3459       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3460       // be an unsigned int.
3461       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3462 
3463       // Check from smallest to largest, picking the smallest type we can.
3464       unsigned Width = 0;
3465 
3466       // Microsoft specific integer suffixes are explicitly sized.
3467       if (Literal.MicrosoftInteger) {
3468         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3469           Width = 8;
3470           Ty = Context.CharTy;
3471         } else {
3472           Width = Literal.MicrosoftInteger;
3473           Ty = Context.getIntTypeForBitwidth(Width,
3474                                              /*Signed=*/!Literal.isUnsigned);
3475         }
3476       }
3477 
3478       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3479         // Are int/unsigned possibilities?
3480         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3481 
3482         // Does it fit in a unsigned int?
3483         if (ResultVal.isIntN(IntSize)) {
3484           // Does it fit in a signed int?
3485           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3486             Ty = Context.IntTy;
3487           else if (AllowUnsigned)
3488             Ty = Context.UnsignedIntTy;
3489           Width = IntSize;
3490         }
3491       }
3492 
3493       // Are long/unsigned long possibilities?
3494       if (Ty.isNull() && !Literal.isLongLong) {
3495         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3496 
3497         // Does it fit in a unsigned long?
3498         if (ResultVal.isIntN(LongSize)) {
3499           // Does it fit in a signed long?
3500           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3501             Ty = Context.LongTy;
3502           else if (AllowUnsigned)
3503             Ty = Context.UnsignedLongTy;
3504           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3505           // is compatible.
3506           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3507             const unsigned LongLongSize =
3508                 Context.getTargetInfo().getLongLongWidth();
3509             Diag(Tok.getLocation(),
3510                  getLangOpts().CPlusPlus
3511                      ? Literal.isLong
3512                            ? diag::warn_old_implicitly_unsigned_long_cxx
3513                            : /*C++98 UB*/ diag::
3514                                  ext_old_implicitly_unsigned_long_cxx
3515                      : diag::warn_old_implicitly_unsigned_long)
3516                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3517                                             : /*will be ill-formed*/ 1);
3518             Ty = Context.UnsignedLongTy;
3519           }
3520           Width = LongSize;
3521         }
3522       }
3523 
3524       // Check long long if needed.
3525       if (Ty.isNull()) {
3526         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3527 
3528         // Does it fit in a unsigned long long?
3529         if (ResultVal.isIntN(LongLongSize)) {
3530           // Does it fit in a signed long long?
3531           // To be compatible with MSVC, hex integer literals ending with the
3532           // LL or i64 suffix are always signed in Microsoft mode.
3533           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3534               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3535             Ty = Context.LongLongTy;
3536           else if (AllowUnsigned)
3537             Ty = Context.UnsignedLongLongTy;
3538           Width = LongLongSize;
3539         }
3540       }
3541 
3542       // If we still couldn't decide a type, we probably have something that
3543       // does not fit in a signed long long, but has no U suffix.
3544       if (Ty.isNull()) {
3545         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3546         Ty = Context.UnsignedLongLongTy;
3547         Width = Context.getTargetInfo().getLongLongWidth();
3548       }
3549 
3550       if (ResultVal.getBitWidth() != Width)
3551         ResultVal = ResultVal.trunc(Width);
3552     }
3553     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3554   }
3555 
3556   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3557   if (Literal.isImaginary) {
3558     Res = new (Context) ImaginaryLiteral(Res,
3559                                         Context.getComplexType(Res->getType()));
3560 
3561     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3562   }
3563   return Res;
3564 }
3565 
3566 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3567   assert(E && "ActOnParenExpr() missing expr");
3568   return new (Context) ParenExpr(L, R, E);
3569 }
3570 
3571 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3572                                          SourceLocation Loc,
3573                                          SourceRange ArgRange) {
3574   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3575   // scalar or vector data type argument..."
3576   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3577   // type (C99 6.2.5p18) or void.
3578   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3579     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3580       << T << ArgRange;
3581     return true;
3582   }
3583 
3584   assert((T->isVoidType() || !T->isIncompleteType()) &&
3585          "Scalar types should always be complete");
3586   return false;
3587 }
3588 
3589 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3590                                            SourceLocation Loc,
3591                                            SourceRange ArgRange,
3592                                            UnaryExprOrTypeTrait TraitKind) {
3593   // Invalid types must be hard errors for SFINAE in C++.
3594   if (S.LangOpts.CPlusPlus)
3595     return true;
3596 
3597   // C99 6.5.3.4p1:
3598   if (T->isFunctionType() &&
3599       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3600     // sizeof(function)/alignof(function) is allowed as an extension.
3601     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3602       << TraitKind << ArgRange;
3603     return false;
3604   }
3605 
3606   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3607   // this is an error (OpenCL v1.1 s6.3.k)
3608   if (T->isVoidType()) {
3609     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3610                                         : diag::ext_sizeof_alignof_void_type;
3611     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3612     return false;
3613   }
3614 
3615   return true;
3616 }
3617 
3618 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3619                                              SourceLocation Loc,
3620                                              SourceRange ArgRange,
3621                                              UnaryExprOrTypeTrait TraitKind) {
3622   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3623   // runtime doesn't allow it.
3624   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3625     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3626       << T << (TraitKind == UETT_SizeOf)
3627       << ArgRange;
3628     return true;
3629   }
3630 
3631   return false;
3632 }
3633 
3634 /// Check whether E is a pointer from a decayed array type (the decayed
3635 /// pointer type is equal to T) and emit a warning if it is.
3636 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3637                                      Expr *E) {
3638   // Don't warn if the operation changed the type.
3639   if (T != E->getType())
3640     return;
3641 
3642   // Now look for array decays.
3643   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3644   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3645     return;
3646 
3647   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3648                                              << ICE->getType()
3649                                              << ICE->getSubExpr()->getType();
3650 }
3651 
3652 /// Check the constraints on expression operands to unary type expression
3653 /// and type traits.
3654 ///
3655 /// Completes any types necessary and validates the constraints on the operand
3656 /// expression. The logic mostly mirrors the type-based overload, but may modify
3657 /// the expression as it completes the type for that expression through template
3658 /// instantiation, etc.
3659 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3660                                             UnaryExprOrTypeTrait ExprKind) {
3661   QualType ExprTy = E->getType();
3662   assert(!ExprTy->isReferenceType());
3663 
3664   if (ExprKind == UETT_VecStep)
3665     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3666                                         E->getSourceRange());
3667 
3668   // Whitelist some types as extensions
3669   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3670                                       E->getSourceRange(), ExprKind))
3671     return false;
3672 
3673   // 'alignof' applied to an expression only requires the base element type of
3674   // the expression to be complete. 'sizeof' requires the expression's type to
3675   // be complete (and will attempt to complete it if it's an array of unknown
3676   // bound).
3677   if (ExprKind == UETT_AlignOf) {
3678     if (RequireCompleteType(E->getExprLoc(),
3679                             Context.getBaseElementType(E->getType()),
3680                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3681                             E->getSourceRange()))
3682       return true;
3683   } else {
3684     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3685                                 ExprKind, E->getSourceRange()))
3686       return true;
3687   }
3688 
3689   // Completing the expression's type may have changed it.
3690   ExprTy = E->getType();
3691   assert(!ExprTy->isReferenceType());
3692 
3693   if (ExprTy->isFunctionType()) {
3694     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3695       << ExprKind << E->getSourceRange();
3696     return true;
3697   }
3698 
3699   // The operand for sizeof and alignof is in an unevaluated expression context,
3700   // so side effects could result in unintended consequences.
3701   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3702       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3703     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3704 
3705   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3706                                        E->getSourceRange(), ExprKind))
3707     return true;
3708 
3709   if (ExprKind == UETT_SizeOf) {
3710     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3711       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3712         QualType OType = PVD->getOriginalType();
3713         QualType Type = PVD->getType();
3714         if (Type->isPointerType() && OType->isArrayType()) {
3715           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3716             << Type << OType;
3717           Diag(PVD->getLocation(), diag::note_declared_at);
3718         }
3719       }
3720     }
3721 
3722     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3723     // decays into a pointer and returns an unintended result. This is most
3724     // likely a typo for "sizeof(array) op x".
3725     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3726       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3727                                BO->getLHS());
3728       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3729                                BO->getRHS());
3730     }
3731   }
3732 
3733   return false;
3734 }
3735 
3736 /// Check the constraints on operands to unary expression and type
3737 /// traits.
3738 ///
3739 /// This will complete any types necessary, and validate the various constraints
3740 /// on those operands.
3741 ///
3742 /// The UsualUnaryConversions() function is *not* called by this routine.
3743 /// C99 6.3.2.1p[2-4] all state:
3744 ///   Except when it is the operand of the sizeof operator ...
3745 ///
3746 /// C++ [expr.sizeof]p4
3747 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3748 ///   standard conversions are not applied to the operand of sizeof.
3749 ///
3750 /// This policy is followed for all of the unary trait expressions.
3751 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3752                                             SourceLocation OpLoc,
3753                                             SourceRange ExprRange,
3754                                             UnaryExprOrTypeTrait ExprKind) {
3755   if (ExprType->isDependentType())
3756     return false;
3757 
3758   // C++ [expr.sizeof]p2:
3759   //     When applied to a reference or a reference type, the result
3760   //     is the size of the referenced type.
3761   // C++11 [expr.alignof]p3:
3762   //     When alignof is applied to a reference type, the result
3763   //     shall be the alignment of the referenced type.
3764   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3765     ExprType = Ref->getPointeeType();
3766 
3767   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3768   //   When alignof or _Alignof is applied to an array type, the result
3769   //   is the alignment of the element type.
3770   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3771     ExprType = Context.getBaseElementType(ExprType);
3772 
3773   if (ExprKind == UETT_VecStep)
3774     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3775 
3776   // Whitelist some types as extensions
3777   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3778                                       ExprKind))
3779     return false;
3780 
3781   if (RequireCompleteType(OpLoc, ExprType,
3782                           diag::err_sizeof_alignof_incomplete_type,
3783                           ExprKind, ExprRange))
3784     return true;
3785 
3786   if (ExprType->isFunctionType()) {
3787     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3788       << ExprKind << ExprRange;
3789     return true;
3790   }
3791 
3792   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3793                                        ExprKind))
3794     return true;
3795 
3796   return false;
3797 }
3798 
3799 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3800   E = E->IgnoreParens();
3801 
3802   // Cannot know anything else if the expression is dependent.
3803   if (E->isTypeDependent())
3804     return false;
3805 
3806   if (E->getObjectKind() == OK_BitField) {
3807     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3808        << 1 << E->getSourceRange();
3809     return true;
3810   }
3811 
3812   ValueDecl *D = nullptr;
3813   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3814     D = DRE->getDecl();
3815   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3816     D = ME->getMemberDecl();
3817   }
3818 
3819   // If it's a field, require the containing struct to have a
3820   // complete definition so that we can compute the layout.
3821   //
3822   // This can happen in C++11 onwards, either by naming the member
3823   // in a way that is not transformed into a member access expression
3824   // (in an unevaluated operand, for instance), or by naming the member
3825   // in a trailing-return-type.
3826   //
3827   // For the record, since __alignof__ on expressions is a GCC
3828   // extension, GCC seems to permit this but always gives the
3829   // nonsensical answer 0.
3830   //
3831   // We don't really need the layout here --- we could instead just
3832   // directly check for all the appropriate alignment-lowing
3833   // attributes --- but that would require duplicating a lot of
3834   // logic that just isn't worth duplicating for such a marginal
3835   // use-case.
3836   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3837     // Fast path this check, since we at least know the record has a
3838     // definition if we can find a member of it.
3839     if (!FD->getParent()->isCompleteDefinition()) {
3840       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3841         << E->getSourceRange();
3842       return true;
3843     }
3844 
3845     // Otherwise, if it's a field, and the field doesn't have
3846     // reference type, then it must have a complete type (or be a
3847     // flexible array member, which we explicitly want to
3848     // white-list anyway), which makes the following checks trivial.
3849     if (!FD->getType()->isReferenceType())
3850       return false;
3851   }
3852 
3853   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3854 }
3855 
3856 bool Sema::CheckVecStepExpr(Expr *E) {
3857   E = E->IgnoreParens();
3858 
3859   // Cannot know anything else if the expression is dependent.
3860   if (E->isTypeDependent())
3861     return false;
3862 
3863   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3864 }
3865 
3866 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3867                                         CapturingScopeInfo *CSI) {
3868   assert(T->isVariablyModifiedType());
3869   assert(CSI != nullptr);
3870 
3871   // We're going to walk down into the type and look for VLA expressions.
3872   do {
3873     const Type *Ty = T.getTypePtr();
3874     switch (Ty->getTypeClass()) {
3875 #define TYPE(Class, Base)
3876 #define ABSTRACT_TYPE(Class, Base)
3877 #define NON_CANONICAL_TYPE(Class, Base)
3878 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3879 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3880 #include "clang/AST/TypeNodes.def"
3881       T = QualType();
3882       break;
3883     // These types are never variably-modified.
3884     case Type::Builtin:
3885     case Type::Complex:
3886     case Type::Vector:
3887     case Type::ExtVector:
3888     case Type::Record:
3889     case Type::Enum:
3890     case Type::Elaborated:
3891     case Type::TemplateSpecialization:
3892     case Type::ObjCObject:
3893     case Type::ObjCInterface:
3894     case Type::ObjCObjectPointer:
3895     case Type::ObjCTypeParam:
3896     case Type::Pipe:
3897       llvm_unreachable("type class is never variably-modified!");
3898     case Type::Adjusted:
3899       T = cast<AdjustedType>(Ty)->getOriginalType();
3900       break;
3901     case Type::Decayed:
3902       T = cast<DecayedType>(Ty)->getPointeeType();
3903       break;
3904     case Type::Pointer:
3905       T = cast<PointerType>(Ty)->getPointeeType();
3906       break;
3907     case Type::BlockPointer:
3908       T = cast<BlockPointerType>(Ty)->getPointeeType();
3909       break;
3910     case Type::LValueReference:
3911     case Type::RValueReference:
3912       T = cast<ReferenceType>(Ty)->getPointeeType();
3913       break;
3914     case Type::MemberPointer:
3915       T = cast<MemberPointerType>(Ty)->getPointeeType();
3916       break;
3917     case Type::ConstantArray:
3918     case Type::IncompleteArray:
3919       // Losing element qualification here is fine.
3920       T = cast<ArrayType>(Ty)->getElementType();
3921       break;
3922     case Type::VariableArray: {
3923       // Losing element qualification here is fine.
3924       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3925 
3926       // Unknown size indication requires no size computation.
3927       // Otherwise, evaluate and record it.
3928       if (auto Size = VAT->getSizeExpr()) {
3929         if (!CSI->isVLATypeCaptured(VAT)) {
3930           RecordDecl *CapRecord = nullptr;
3931           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3932             CapRecord = LSI->Lambda;
3933           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3934             CapRecord = CRSI->TheRecordDecl;
3935           }
3936           if (CapRecord) {
3937             auto ExprLoc = Size->getExprLoc();
3938             auto SizeType = Context.getSizeType();
3939             // Build the non-static data member.
3940             auto Field =
3941                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3942                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3943                                   /*BW*/ nullptr, /*Mutable*/ false,
3944                                   /*InitStyle*/ ICIS_NoInit);
3945             Field->setImplicit(true);
3946             Field->setAccess(AS_private);
3947             Field->setCapturedVLAType(VAT);
3948             CapRecord->addDecl(Field);
3949 
3950             CSI->addVLATypeCapture(ExprLoc, SizeType);
3951           }
3952         }
3953       }
3954       T = VAT->getElementType();
3955       break;
3956     }
3957     case Type::FunctionProto:
3958     case Type::FunctionNoProto:
3959       T = cast<FunctionType>(Ty)->getReturnType();
3960       break;
3961     case Type::Paren:
3962     case Type::TypeOf:
3963     case Type::UnaryTransform:
3964     case Type::Attributed:
3965     case Type::SubstTemplateTypeParm:
3966     case Type::PackExpansion:
3967       // Keep walking after single level desugaring.
3968       T = T.getSingleStepDesugaredType(Context);
3969       break;
3970     case Type::Typedef:
3971       T = cast<TypedefType>(Ty)->desugar();
3972       break;
3973     case Type::Decltype:
3974       T = cast<DecltypeType>(Ty)->desugar();
3975       break;
3976     case Type::Auto:
3977     case Type::DeducedTemplateSpecialization:
3978       T = cast<DeducedType>(Ty)->getDeducedType();
3979       break;
3980     case Type::TypeOfExpr:
3981       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3982       break;
3983     case Type::Atomic:
3984       T = cast<AtomicType>(Ty)->getValueType();
3985       break;
3986     }
3987   } while (!T.isNull() && T->isVariablyModifiedType());
3988 }
3989 
3990 /// Build a sizeof or alignof expression given a type operand.
3991 ExprResult
3992 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3993                                      SourceLocation OpLoc,
3994                                      UnaryExprOrTypeTrait ExprKind,
3995                                      SourceRange R) {
3996   if (!TInfo)
3997     return ExprError();
3998 
3999   QualType T = TInfo->getType();
4000 
4001   if (!T->isDependentType() &&
4002       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4003     return ExprError();
4004 
4005   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4006     if (auto *TT = T->getAs<TypedefType>()) {
4007       for (auto I = FunctionScopes.rbegin(),
4008                 E = std::prev(FunctionScopes.rend());
4009            I != E; ++I) {
4010         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4011         if (CSI == nullptr)
4012           break;
4013         DeclContext *DC = nullptr;
4014         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4015           DC = LSI->CallOperator;
4016         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4017           DC = CRSI->TheCapturedDecl;
4018         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4019           DC = BSI->TheDecl;
4020         if (DC) {
4021           if (DC->containsDecl(TT->getDecl()))
4022             break;
4023           captureVariablyModifiedType(Context, T, CSI);
4024         }
4025       }
4026     }
4027   }
4028 
4029   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4030   return new (Context) UnaryExprOrTypeTraitExpr(
4031       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4032 }
4033 
4034 /// Build a sizeof or alignof expression given an expression
4035 /// operand.
4036 ExprResult
4037 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4038                                      UnaryExprOrTypeTrait ExprKind) {
4039   ExprResult PE = CheckPlaceholderExpr(E);
4040   if (PE.isInvalid())
4041     return ExprError();
4042 
4043   E = PE.get();
4044 
4045   // Verify that the operand is valid.
4046   bool isInvalid = false;
4047   if (E->isTypeDependent()) {
4048     // Delay type-checking for type-dependent expressions.
4049   } else if (ExprKind == UETT_AlignOf) {
4050     isInvalid = CheckAlignOfExpr(*this, E);
4051   } else if (ExprKind == UETT_VecStep) {
4052     isInvalid = CheckVecStepExpr(E);
4053   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4054       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4055       isInvalid = true;
4056   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4057     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4058     isInvalid = true;
4059   } else {
4060     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4061   }
4062 
4063   if (isInvalid)
4064     return ExprError();
4065 
4066   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4067     PE = TransformToPotentiallyEvaluated(E);
4068     if (PE.isInvalid()) return ExprError();
4069     E = PE.get();
4070   }
4071 
4072   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4073   return new (Context) UnaryExprOrTypeTraitExpr(
4074       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4075 }
4076 
4077 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4078 /// expr and the same for @c alignof and @c __alignof
4079 /// Note that the ArgRange is invalid if isType is false.
4080 ExprResult
4081 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4082                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4083                                     void *TyOrEx, SourceRange ArgRange) {
4084   // If error parsing type, ignore.
4085   if (!TyOrEx) return ExprError();
4086 
4087   if (IsType) {
4088     TypeSourceInfo *TInfo;
4089     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4090     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4091   }
4092 
4093   Expr *ArgEx = (Expr *)TyOrEx;
4094   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4095   return Result;
4096 }
4097 
4098 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4099                                      bool IsReal) {
4100   if (V.get()->isTypeDependent())
4101     return S.Context.DependentTy;
4102 
4103   // _Real and _Imag are only l-values for normal l-values.
4104   if (V.get()->getObjectKind() != OK_Ordinary) {
4105     V = S.DefaultLvalueConversion(V.get());
4106     if (V.isInvalid())
4107       return QualType();
4108   }
4109 
4110   // These operators return the element type of a complex type.
4111   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4112     return CT->getElementType();
4113 
4114   // Otherwise they pass through real integer and floating point types here.
4115   if (V.get()->getType()->isArithmeticType())
4116     return V.get()->getType();
4117 
4118   // Test for placeholders.
4119   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4120   if (PR.isInvalid()) return QualType();
4121   if (PR.get() != V.get()) {
4122     V = PR;
4123     return CheckRealImagOperand(S, V, Loc, IsReal);
4124   }
4125 
4126   // Reject anything else.
4127   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4128     << (IsReal ? "__real" : "__imag");
4129   return QualType();
4130 }
4131 
4132 
4133 
4134 ExprResult
4135 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4136                           tok::TokenKind Kind, Expr *Input) {
4137   UnaryOperatorKind Opc;
4138   switch (Kind) {
4139   default: llvm_unreachable("Unknown unary op!");
4140   case tok::plusplus:   Opc = UO_PostInc; break;
4141   case tok::minusminus: Opc = UO_PostDec; break;
4142   }
4143 
4144   // Since this might is a postfix expression, get rid of ParenListExprs.
4145   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4146   if (Result.isInvalid()) return ExprError();
4147   Input = Result.get();
4148 
4149   return BuildUnaryOp(S, OpLoc, Opc, Input);
4150 }
4151 
4152 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4153 ///
4154 /// \return true on error
4155 static bool checkArithmeticOnObjCPointer(Sema &S,
4156                                          SourceLocation opLoc,
4157                                          Expr *op) {
4158   assert(op->getType()->isObjCObjectPointerType());
4159   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4160       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4161     return false;
4162 
4163   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4164     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4165     << op->getSourceRange();
4166   return true;
4167 }
4168 
4169 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4170   auto *BaseNoParens = Base->IgnoreParens();
4171   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4172     return MSProp->getPropertyDecl()->getType()->isArrayType();
4173   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4174 }
4175 
4176 ExprResult
4177 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4178                               Expr *idx, SourceLocation rbLoc) {
4179   if (base && !base->getType().isNull() &&
4180       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4181     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4182                                     /*Length=*/nullptr, rbLoc);
4183 
4184   // Since this might be a postfix expression, get rid of ParenListExprs.
4185   if (isa<ParenListExpr>(base)) {
4186     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4187     if (result.isInvalid()) return ExprError();
4188     base = result.get();
4189   }
4190 
4191   // Handle any non-overload placeholder types in the base and index
4192   // expressions.  We can't handle overloads here because the other
4193   // operand might be an overloadable type, in which case the overload
4194   // resolution for the operator overload should get the first crack
4195   // at the overload.
4196   bool IsMSPropertySubscript = false;
4197   if (base->getType()->isNonOverloadPlaceholderType()) {
4198     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4199     if (!IsMSPropertySubscript) {
4200       ExprResult result = CheckPlaceholderExpr(base);
4201       if (result.isInvalid())
4202         return ExprError();
4203       base = result.get();
4204     }
4205   }
4206   if (idx->getType()->isNonOverloadPlaceholderType()) {
4207     ExprResult result = CheckPlaceholderExpr(idx);
4208     if (result.isInvalid()) return ExprError();
4209     idx = result.get();
4210   }
4211 
4212   // Build an unanalyzed expression if either operand is type-dependent.
4213   if (getLangOpts().CPlusPlus &&
4214       (base->isTypeDependent() || idx->isTypeDependent())) {
4215     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4216                                             VK_LValue, OK_Ordinary, rbLoc);
4217   }
4218 
4219   // MSDN, property (C++)
4220   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4221   // This attribute can also be used in the declaration of an empty array in a
4222   // class or structure definition. For example:
4223   // __declspec(property(get=GetX, put=PutX)) int x[];
4224   // The above statement indicates that x[] can be used with one or more array
4225   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4226   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4227   if (IsMSPropertySubscript) {
4228     // Build MS property subscript expression if base is MS property reference
4229     // or MS property subscript.
4230     return new (Context) MSPropertySubscriptExpr(
4231         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4232   }
4233 
4234   // Use C++ overloaded-operator rules if either operand has record
4235   // type.  The spec says to do this if either type is *overloadable*,
4236   // but enum types can't declare subscript operators or conversion
4237   // operators, so there's nothing interesting for overload resolution
4238   // to do if there aren't any record types involved.
4239   //
4240   // ObjC pointers have their own subscripting logic that is not tied
4241   // to overload resolution and so should not take this path.
4242   if (getLangOpts().CPlusPlus &&
4243       (base->getType()->isRecordType() ||
4244        (!base->getType()->isObjCObjectPointerType() &&
4245         idx->getType()->isRecordType()))) {
4246     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4247   }
4248 
4249   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4250 }
4251 
4252 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4253                                           Expr *LowerBound,
4254                                           SourceLocation ColonLoc, Expr *Length,
4255                                           SourceLocation RBLoc) {
4256   if (Base->getType()->isPlaceholderType() &&
4257       !Base->getType()->isSpecificPlaceholderType(
4258           BuiltinType::OMPArraySection)) {
4259     ExprResult Result = CheckPlaceholderExpr(Base);
4260     if (Result.isInvalid())
4261       return ExprError();
4262     Base = Result.get();
4263   }
4264   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4265     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4266     if (Result.isInvalid())
4267       return ExprError();
4268     Result = DefaultLvalueConversion(Result.get());
4269     if (Result.isInvalid())
4270       return ExprError();
4271     LowerBound = Result.get();
4272   }
4273   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4274     ExprResult Result = CheckPlaceholderExpr(Length);
4275     if (Result.isInvalid())
4276       return ExprError();
4277     Result = DefaultLvalueConversion(Result.get());
4278     if (Result.isInvalid())
4279       return ExprError();
4280     Length = Result.get();
4281   }
4282 
4283   // Build an unanalyzed expression if either operand is type-dependent.
4284   if (Base->isTypeDependent() ||
4285       (LowerBound &&
4286        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4287       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4288     return new (Context)
4289         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4290                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4291   }
4292 
4293   // Perform default conversions.
4294   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4295   QualType ResultTy;
4296   if (OriginalTy->isAnyPointerType()) {
4297     ResultTy = OriginalTy->getPointeeType();
4298   } else if (OriginalTy->isArrayType()) {
4299     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4300   } else {
4301     return ExprError(
4302         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4303         << Base->getSourceRange());
4304   }
4305   // C99 6.5.2.1p1
4306   if (LowerBound) {
4307     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4308                                                       LowerBound);
4309     if (Res.isInvalid())
4310       return ExprError(Diag(LowerBound->getExprLoc(),
4311                             diag::err_omp_typecheck_section_not_integer)
4312                        << 0 << LowerBound->getSourceRange());
4313     LowerBound = Res.get();
4314 
4315     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4316         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4317       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4318           << 0 << LowerBound->getSourceRange();
4319   }
4320   if (Length) {
4321     auto Res =
4322         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4323     if (Res.isInvalid())
4324       return ExprError(Diag(Length->getExprLoc(),
4325                             diag::err_omp_typecheck_section_not_integer)
4326                        << 1 << Length->getSourceRange());
4327     Length = Res.get();
4328 
4329     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4330         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4331       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4332           << 1 << Length->getSourceRange();
4333   }
4334 
4335   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4336   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4337   // type. Note that functions are not objects, and that (in C99 parlance)
4338   // incomplete types are not object types.
4339   if (ResultTy->isFunctionType()) {
4340     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4341         << ResultTy << Base->getSourceRange();
4342     return ExprError();
4343   }
4344 
4345   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4346                           diag::err_omp_section_incomplete_type, Base))
4347     return ExprError();
4348 
4349   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4350     llvm::APSInt LowerBoundValue;
4351     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4352       // OpenMP 4.5, [2.4 Array Sections]
4353       // The array section must be a subset of the original array.
4354       if (LowerBoundValue.isNegative()) {
4355         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4356             << LowerBound->getSourceRange();
4357         return ExprError();
4358       }
4359     }
4360   }
4361 
4362   if (Length) {
4363     llvm::APSInt LengthValue;
4364     if (Length->EvaluateAsInt(LengthValue, Context)) {
4365       // OpenMP 4.5, [2.4 Array Sections]
4366       // The length must evaluate to non-negative integers.
4367       if (LengthValue.isNegative()) {
4368         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4369             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4370             << Length->getSourceRange();
4371         return ExprError();
4372       }
4373     }
4374   } else if (ColonLoc.isValid() &&
4375              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4376                                       !OriginalTy->isVariableArrayType()))) {
4377     // OpenMP 4.5, [2.4 Array Sections]
4378     // When the size of the array dimension is not known, the length must be
4379     // specified explicitly.
4380     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4381         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4382     return ExprError();
4383   }
4384 
4385   if (!Base->getType()->isSpecificPlaceholderType(
4386           BuiltinType::OMPArraySection)) {
4387     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4388     if (Result.isInvalid())
4389       return ExprError();
4390     Base = Result.get();
4391   }
4392   return new (Context)
4393       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4394                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4395 }
4396 
4397 ExprResult
4398 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4399                                       Expr *Idx, SourceLocation RLoc) {
4400   Expr *LHSExp = Base;
4401   Expr *RHSExp = Idx;
4402 
4403   ExprValueKind VK = VK_LValue;
4404   ExprObjectKind OK = OK_Ordinary;
4405 
4406   // Per C++ core issue 1213, the result is an xvalue if either operand is
4407   // a non-lvalue array, and an lvalue otherwise.
4408   if (getLangOpts().CPlusPlus11) {
4409     for (auto *Op : {LHSExp, RHSExp}) {
4410       Op = Op->IgnoreImplicit();
4411       if (Op->getType()->isArrayType() && !Op->isLValue())
4412         VK = VK_XValue;
4413     }
4414   }
4415 
4416   // Perform default conversions.
4417   if (!LHSExp->getType()->getAs<VectorType>()) {
4418     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4419     if (Result.isInvalid())
4420       return ExprError();
4421     LHSExp = Result.get();
4422   }
4423   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4424   if (Result.isInvalid())
4425     return ExprError();
4426   RHSExp = Result.get();
4427 
4428   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4429 
4430   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4431   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4432   // in the subscript position. As a result, we need to derive the array base
4433   // and index from the expression types.
4434   Expr *BaseExpr, *IndexExpr;
4435   QualType ResultType;
4436   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4437     BaseExpr = LHSExp;
4438     IndexExpr = RHSExp;
4439     ResultType = Context.DependentTy;
4440   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4441     BaseExpr = LHSExp;
4442     IndexExpr = RHSExp;
4443     ResultType = PTy->getPointeeType();
4444   } else if (const ObjCObjectPointerType *PTy =
4445                LHSTy->getAs<ObjCObjectPointerType>()) {
4446     BaseExpr = LHSExp;
4447     IndexExpr = RHSExp;
4448 
4449     // Use custom logic if this should be the pseudo-object subscript
4450     // expression.
4451     if (!LangOpts.isSubscriptPointerArithmetic())
4452       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4453                                           nullptr);
4454 
4455     ResultType = PTy->getPointeeType();
4456   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4457      // Handle the uncommon case of "123[Ptr]".
4458     BaseExpr = RHSExp;
4459     IndexExpr = LHSExp;
4460     ResultType = PTy->getPointeeType();
4461   } else if (const ObjCObjectPointerType *PTy =
4462                RHSTy->getAs<ObjCObjectPointerType>()) {
4463      // Handle the uncommon case of "123[Ptr]".
4464     BaseExpr = RHSExp;
4465     IndexExpr = LHSExp;
4466     ResultType = PTy->getPointeeType();
4467     if (!LangOpts.isSubscriptPointerArithmetic()) {
4468       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4469         << ResultType << BaseExpr->getSourceRange();
4470       return ExprError();
4471     }
4472   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4473     BaseExpr = LHSExp;    // vectors: V[123]
4474     IndexExpr = RHSExp;
4475     // We apply C++ DR1213 to vector subscripting too.
4476     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4477       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4478       if (Materialized.isInvalid())
4479         return ExprError();
4480       LHSExp = Materialized.get();
4481     }
4482     VK = LHSExp->getValueKind();
4483     if (VK != VK_RValue)
4484       OK = OK_VectorComponent;
4485 
4486     ResultType = VTy->getElementType();
4487     QualType BaseType = BaseExpr->getType();
4488     Qualifiers BaseQuals = BaseType.getQualifiers();
4489     Qualifiers MemberQuals = ResultType.getQualifiers();
4490     Qualifiers Combined = BaseQuals + MemberQuals;
4491     if (Combined != MemberQuals)
4492       ResultType = Context.getQualifiedType(ResultType, Combined);
4493   } else if (LHSTy->isArrayType()) {
4494     // If we see an array that wasn't promoted by
4495     // DefaultFunctionArrayLvalueConversion, it must be an array that
4496     // wasn't promoted because of the C90 rule that doesn't
4497     // allow promoting non-lvalue arrays.  Warn, then
4498     // force the promotion here.
4499     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4500         << LHSExp->getSourceRange();
4501     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4502                                CK_ArrayToPointerDecay).get();
4503     LHSTy = LHSExp->getType();
4504 
4505     BaseExpr = LHSExp;
4506     IndexExpr = RHSExp;
4507     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4508   } else if (RHSTy->isArrayType()) {
4509     // Same as previous, except for 123[f().a] case
4510     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4511         << RHSExp->getSourceRange();
4512     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4513                                CK_ArrayToPointerDecay).get();
4514     RHSTy = RHSExp->getType();
4515 
4516     BaseExpr = RHSExp;
4517     IndexExpr = LHSExp;
4518     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4519   } else {
4520     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4521        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4522   }
4523   // C99 6.5.2.1p1
4524   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4525     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4526                      << IndexExpr->getSourceRange());
4527 
4528   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4529        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4530          && !IndexExpr->isTypeDependent())
4531     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4532 
4533   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4534   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4535   // type. Note that Functions are not objects, and that (in C99 parlance)
4536   // incomplete types are not object types.
4537   if (ResultType->isFunctionType()) {
4538     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4539         << ResultType << BaseExpr->getSourceRange();
4540     return ExprError();
4541   }
4542 
4543   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4544     // GNU extension: subscripting on pointer to void
4545     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4546       << BaseExpr->getSourceRange();
4547 
4548     // C forbids expressions of unqualified void type from being l-values.
4549     // See IsCForbiddenLValueType.
4550     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4551   } else if (!ResultType->isDependentType() &&
4552       RequireCompleteType(LLoc, ResultType,
4553                           diag::err_subscript_incomplete_type, BaseExpr))
4554     return ExprError();
4555 
4556   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4557          !ResultType.isCForbiddenLValueType());
4558 
4559   return new (Context)
4560       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4561 }
4562 
4563 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4564                                   ParmVarDecl *Param) {
4565   if (Param->hasUnparsedDefaultArg()) {
4566     Diag(CallLoc,
4567          diag::err_use_of_default_argument_to_function_declared_later) <<
4568       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4569     Diag(UnparsedDefaultArgLocs[Param],
4570          diag::note_default_argument_declared_here);
4571     return true;
4572   }
4573 
4574   if (Param->hasUninstantiatedDefaultArg()) {
4575     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4576 
4577     EnterExpressionEvaluationContext EvalContext(
4578         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4579 
4580     // Instantiate the expression.
4581     //
4582     // FIXME: Pass in a correct Pattern argument, otherwise
4583     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4584     //
4585     // template<typename T>
4586     // struct A {
4587     //   static int FooImpl();
4588     //
4589     //   template<typename Tp>
4590     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4591     //   // template argument list [[T], [Tp]], should be [[Tp]].
4592     //   friend A<Tp> Foo(int a);
4593     // };
4594     //
4595     // template<typename T>
4596     // A<T> Foo(int a = A<T>::FooImpl());
4597     MultiLevelTemplateArgumentList MutiLevelArgList
4598       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4599 
4600     InstantiatingTemplate Inst(*this, CallLoc, Param,
4601                                MutiLevelArgList.getInnermost());
4602     if (Inst.isInvalid())
4603       return true;
4604     if (Inst.isAlreadyInstantiating()) {
4605       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4606       Param->setInvalidDecl();
4607       return true;
4608     }
4609 
4610     ExprResult Result;
4611     {
4612       // C++ [dcl.fct.default]p5:
4613       //   The names in the [default argument] expression are bound, and
4614       //   the semantic constraints are checked, at the point where the
4615       //   default argument expression appears.
4616       ContextRAII SavedContext(*this, FD);
4617       LocalInstantiationScope Local(*this);
4618       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4619                                 /*DirectInit*/false);
4620     }
4621     if (Result.isInvalid())
4622       return true;
4623 
4624     // Check the expression as an initializer for the parameter.
4625     InitializedEntity Entity
4626       = InitializedEntity::InitializeParameter(Context, Param);
4627     InitializationKind Kind = InitializationKind::CreateCopy(
4628         Param->getLocation(),
4629         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4630     Expr *ResultE = Result.getAs<Expr>();
4631 
4632     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4633     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4634     if (Result.isInvalid())
4635       return true;
4636 
4637     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4638                                  Param->getOuterLocStart());
4639     if (Result.isInvalid())
4640       return true;
4641 
4642     // Remember the instantiated default argument.
4643     Param->setDefaultArg(Result.getAs<Expr>());
4644     if (ASTMutationListener *L = getASTMutationListener()) {
4645       L->DefaultArgumentInstantiated(Param);
4646     }
4647   }
4648 
4649   // If the default argument expression is not set yet, we are building it now.
4650   if (!Param->hasInit()) {
4651     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4652     Param->setInvalidDecl();
4653     return true;
4654   }
4655 
4656   // If the default expression creates temporaries, we need to
4657   // push them to the current stack of expression temporaries so they'll
4658   // be properly destroyed.
4659   // FIXME: We should really be rebuilding the default argument with new
4660   // bound temporaries; see the comment in PR5810.
4661   // We don't need to do that with block decls, though, because
4662   // blocks in default argument expression can never capture anything.
4663   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4664     // Set the "needs cleanups" bit regardless of whether there are
4665     // any explicit objects.
4666     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4667 
4668     // Append all the objects to the cleanup list.  Right now, this
4669     // should always be a no-op, because blocks in default argument
4670     // expressions should never be able to capture anything.
4671     assert(!Init->getNumObjects() &&
4672            "default argument expression has capturing blocks?");
4673   }
4674 
4675   // We already type-checked the argument, so we know it works.
4676   // Just mark all of the declarations in this potentially-evaluated expression
4677   // as being "referenced".
4678   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4679                                    /*SkipLocalVariables=*/true);
4680   return false;
4681 }
4682 
4683 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4684                                         FunctionDecl *FD, ParmVarDecl *Param) {
4685   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4686     return ExprError();
4687   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4688 }
4689 
4690 Sema::VariadicCallType
4691 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4692                           Expr *Fn) {
4693   if (Proto && Proto->isVariadic()) {
4694     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4695       return VariadicConstructor;
4696     else if (Fn && Fn->getType()->isBlockPointerType())
4697       return VariadicBlock;
4698     else if (FDecl) {
4699       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4700         if (Method->isInstance())
4701           return VariadicMethod;
4702     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4703       return VariadicMethod;
4704     return VariadicFunction;
4705   }
4706   return VariadicDoesNotApply;
4707 }
4708 
4709 namespace {
4710 class FunctionCallCCC : public FunctionCallFilterCCC {
4711 public:
4712   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4713                   unsigned NumArgs, MemberExpr *ME)
4714       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4715         FunctionName(FuncName) {}
4716 
4717   bool ValidateCandidate(const TypoCorrection &candidate) override {
4718     if (!candidate.getCorrectionSpecifier() ||
4719         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4720       return false;
4721     }
4722 
4723     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4724   }
4725 
4726 private:
4727   const IdentifierInfo *const FunctionName;
4728 };
4729 }
4730 
4731 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4732                                                FunctionDecl *FDecl,
4733                                                ArrayRef<Expr *> Args) {
4734   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4735   DeclarationName FuncName = FDecl->getDeclName();
4736   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4737 
4738   if (TypoCorrection Corrected = S.CorrectTypo(
4739           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4740           S.getScopeForContext(S.CurContext), nullptr,
4741           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4742                                              Args.size(), ME),
4743           Sema::CTK_ErrorRecovery)) {
4744     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4745       if (Corrected.isOverloaded()) {
4746         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4747         OverloadCandidateSet::iterator Best;
4748         for (NamedDecl *CD : Corrected) {
4749           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4750             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4751                                    OCS);
4752         }
4753         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4754         case OR_Success:
4755           ND = Best->FoundDecl;
4756           Corrected.setCorrectionDecl(ND);
4757           break;
4758         default:
4759           break;
4760         }
4761       }
4762       ND = ND->getUnderlyingDecl();
4763       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4764         return Corrected;
4765     }
4766   }
4767   return TypoCorrection();
4768 }
4769 
4770 /// ConvertArgumentsForCall - Converts the arguments specified in
4771 /// Args/NumArgs to the parameter types of the function FDecl with
4772 /// function prototype Proto. Call is the call expression itself, and
4773 /// Fn is the function expression. For a C++ member function, this
4774 /// routine does not attempt to convert the object argument. Returns
4775 /// true if the call is ill-formed.
4776 bool
4777 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4778                               FunctionDecl *FDecl,
4779                               const FunctionProtoType *Proto,
4780                               ArrayRef<Expr *> Args,
4781                               SourceLocation RParenLoc,
4782                               bool IsExecConfig) {
4783   // Bail out early if calling a builtin with custom typechecking.
4784   if (FDecl)
4785     if (unsigned ID = FDecl->getBuiltinID())
4786       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4787         return false;
4788 
4789   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4790   // assignment, to the types of the corresponding parameter, ...
4791   unsigned NumParams = Proto->getNumParams();
4792   bool Invalid = false;
4793   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4794   unsigned FnKind = Fn->getType()->isBlockPointerType()
4795                        ? 1 /* block */
4796                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4797                                        : 0 /* function */);
4798 
4799   // If too few arguments are available (and we don't have default
4800   // arguments for the remaining parameters), don't make the call.
4801   if (Args.size() < NumParams) {
4802     if (Args.size() < MinArgs) {
4803       TypoCorrection TC;
4804       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4805         unsigned diag_id =
4806             MinArgs == NumParams && !Proto->isVariadic()
4807                 ? diag::err_typecheck_call_too_few_args_suggest
4808                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4809         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4810                                         << static_cast<unsigned>(Args.size())
4811                                         << TC.getCorrectionRange());
4812       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4813         Diag(RParenLoc,
4814              MinArgs == NumParams && !Proto->isVariadic()
4815                  ? diag::err_typecheck_call_too_few_args_one
4816                  : diag::err_typecheck_call_too_few_args_at_least_one)
4817             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4818       else
4819         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4820                             ? diag::err_typecheck_call_too_few_args
4821                             : diag::err_typecheck_call_too_few_args_at_least)
4822             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4823             << Fn->getSourceRange();
4824 
4825       // Emit the location of the prototype.
4826       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4827         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4828 
4829       return true;
4830     }
4831     Call->setNumArgs(Context, NumParams);
4832   }
4833 
4834   // If too many are passed and not variadic, error on the extras and drop
4835   // them.
4836   if (Args.size() > NumParams) {
4837     if (!Proto->isVariadic()) {
4838       TypoCorrection TC;
4839       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4840         unsigned diag_id =
4841             MinArgs == NumParams && !Proto->isVariadic()
4842                 ? diag::err_typecheck_call_too_many_args_suggest
4843                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4844         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4845                                         << static_cast<unsigned>(Args.size())
4846                                         << TC.getCorrectionRange());
4847       } else if (NumParams == 1 && FDecl &&
4848                  FDecl->getParamDecl(0)->getDeclName())
4849         Diag(Args[NumParams]->getBeginLoc(),
4850              MinArgs == NumParams
4851                  ? diag::err_typecheck_call_too_many_args_one
4852                  : diag::err_typecheck_call_too_many_args_at_most_one)
4853             << FnKind << FDecl->getParamDecl(0)
4854             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4855             << SourceRange(Args[NumParams]->getBeginLoc(),
4856                            Args.back()->getEndLoc());
4857       else
4858         Diag(Args[NumParams]->getBeginLoc(),
4859              MinArgs == NumParams
4860                  ? diag::err_typecheck_call_too_many_args
4861                  : diag::err_typecheck_call_too_many_args_at_most)
4862             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4863             << Fn->getSourceRange()
4864             << SourceRange(Args[NumParams]->getBeginLoc(),
4865                            Args.back()->getEndLoc());
4866 
4867       // Emit the location of the prototype.
4868       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4869         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4870 
4871       // This deletes the extra arguments.
4872       Call->setNumArgs(Context, NumParams);
4873       return true;
4874     }
4875   }
4876   SmallVector<Expr *, 8> AllArgs;
4877   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4878 
4879   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
4880                                    AllArgs, CallType);
4881   if (Invalid)
4882     return true;
4883   unsigned TotalNumArgs = AllArgs.size();
4884   for (unsigned i = 0; i < TotalNumArgs; ++i)
4885     Call->setArg(i, AllArgs[i]);
4886 
4887   return false;
4888 }
4889 
4890 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4891                                   const FunctionProtoType *Proto,
4892                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4893                                   SmallVectorImpl<Expr *> &AllArgs,
4894                                   VariadicCallType CallType, bool AllowExplicit,
4895                                   bool IsListInitialization) {
4896   unsigned NumParams = Proto->getNumParams();
4897   bool Invalid = false;
4898   size_t ArgIx = 0;
4899   // Continue to check argument types (even if we have too few/many args).
4900   for (unsigned i = FirstParam; i < NumParams; i++) {
4901     QualType ProtoArgType = Proto->getParamType(i);
4902 
4903     Expr *Arg;
4904     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4905     if (ArgIx < Args.size()) {
4906       Arg = Args[ArgIx++];
4907 
4908       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
4909                               diag::err_call_incomplete_argument, Arg))
4910         return true;
4911 
4912       // Strip the unbridged-cast placeholder expression off, if applicable.
4913       bool CFAudited = false;
4914       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4915           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4916           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4917         Arg = stripARCUnbridgedCast(Arg);
4918       else if (getLangOpts().ObjCAutoRefCount &&
4919                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4920                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4921         CFAudited = true;
4922 
4923       if (Proto->getExtParameterInfo(i).isNoEscape())
4924         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4925           BE->getBlockDecl()->setDoesNotEscape();
4926 
4927       InitializedEntity Entity =
4928           Param ? InitializedEntity::InitializeParameter(Context, Param,
4929                                                          ProtoArgType)
4930                 : InitializedEntity::InitializeParameter(
4931                       Context, ProtoArgType, Proto->isParamConsumed(i));
4932 
4933       // Remember that parameter belongs to a CF audited API.
4934       if (CFAudited)
4935         Entity.setParameterCFAudited();
4936 
4937       ExprResult ArgE = PerformCopyInitialization(
4938           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4939       if (ArgE.isInvalid())
4940         return true;
4941 
4942       Arg = ArgE.getAs<Expr>();
4943     } else {
4944       assert(Param && "can't use default arguments without a known callee");
4945 
4946       ExprResult ArgExpr =
4947         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4948       if (ArgExpr.isInvalid())
4949         return true;
4950 
4951       Arg = ArgExpr.getAs<Expr>();
4952     }
4953 
4954     // Check for array bounds violations for each argument to the call. This
4955     // check only triggers warnings when the argument isn't a more complex Expr
4956     // with its own checking, such as a BinaryOperator.
4957     CheckArrayAccess(Arg);
4958 
4959     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4960     CheckStaticArrayArgument(CallLoc, Param, Arg);
4961 
4962     AllArgs.push_back(Arg);
4963   }
4964 
4965   // If this is a variadic call, handle args passed through "...".
4966   if (CallType != VariadicDoesNotApply) {
4967     // Assume that extern "C" functions with variadic arguments that
4968     // return __unknown_anytype aren't *really* variadic.
4969     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4970         FDecl->isExternC()) {
4971       for (Expr *A : Args.slice(ArgIx)) {
4972         QualType paramType; // ignored
4973         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4974         Invalid |= arg.isInvalid();
4975         AllArgs.push_back(arg.get());
4976       }
4977 
4978     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4979     } else {
4980       for (Expr *A : Args.slice(ArgIx)) {
4981         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4982         Invalid |= Arg.isInvalid();
4983         AllArgs.push_back(Arg.get());
4984       }
4985     }
4986 
4987     // Check for array bounds violations.
4988     for (Expr *A : Args.slice(ArgIx))
4989       CheckArrayAccess(A);
4990   }
4991   return Invalid;
4992 }
4993 
4994 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4995   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4996   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4997     TL = DTL.getOriginalLoc();
4998   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4999     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5000       << ATL.getLocalSourceRange();
5001 }
5002 
5003 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5004 /// array parameter, check that it is non-null, and that if it is formed by
5005 /// array-to-pointer decay, the underlying array is sufficiently large.
5006 ///
5007 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5008 /// array type derivation, then for each call to the function, the value of the
5009 /// corresponding actual argument shall provide access to the first element of
5010 /// an array with at least as many elements as specified by the size expression.
5011 void
5012 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5013                                ParmVarDecl *Param,
5014                                const Expr *ArgExpr) {
5015   // Static array parameters are not supported in C++.
5016   if (!Param || getLangOpts().CPlusPlus)
5017     return;
5018 
5019   QualType OrigTy = Param->getOriginalType();
5020 
5021   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5022   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5023     return;
5024 
5025   if (ArgExpr->isNullPointerConstant(Context,
5026                                      Expr::NPC_NeverValueDependent)) {
5027     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5028     DiagnoseCalleeStaticArrayParam(*this, Param);
5029     return;
5030   }
5031 
5032   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5033   if (!CAT)
5034     return;
5035 
5036   const ConstantArrayType *ArgCAT =
5037     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5038   if (!ArgCAT)
5039     return;
5040 
5041   if (ArgCAT->getSize().ult(CAT->getSize())) {
5042     Diag(CallLoc, diag::warn_static_array_too_small)
5043       << ArgExpr->getSourceRange()
5044       << (unsigned) ArgCAT->getSize().getZExtValue()
5045       << (unsigned) CAT->getSize().getZExtValue();
5046     DiagnoseCalleeStaticArrayParam(*this, Param);
5047   }
5048 }
5049 
5050 /// Given a function expression of unknown-any type, try to rebuild it
5051 /// to have a function type.
5052 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5053 
5054 /// Is the given type a placeholder that we need to lower out
5055 /// immediately during argument processing?
5056 static bool isPlaceholderToRemoveAsArg(QualType type) {
5057   // Placeholders are never sugared.
5058   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5059   if (!placeholder) return false;
5060 
5061   switch (placeholder->getKind()) {
5062   // Ignore all the non-placeholder types.
5063 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5064   case BuiltinType::Id:
5065 #include "clang/Basic/OpenCLImageTypes.def"
5066 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5067 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5068 #include "clang/AST/BuiltinTypes.def"
5069     return false;
5070 
5071   // We cannot lower out overload sets; they might validly be resolved
5072   // by the call machinery.
5073   case BuiltinType::Overload:
5074     return false;
5075 
5076   // Unbridged casts in ARC can be handled in some call positions and
5077   // should be left in place.
5078   case BuiltinType::ARCUnbridgedCast:
5079     return false;
5080 
5081   // Pseudo-objects should be converted as soon as possible.
5082   case BuiltinType::PseudoObject:
5083     return true;
5084 
5085   // The debugger mode could theoretically but currently does not try
5086   // to resolve unknown-typed arguments based on known parameter types.
5087   case BuiltinType::UnknownAny:
5088     return true;
5089 
5090   // These are always invalid as call arguments and should be reported.
5091   case BuiltinType::BoundMember:
5092   case BuiltinType::BuiltinFn:
5093   case BuiltinType::OMPArraySection:
5094     return true;
5095 
5096   }
5097   llvm_unreachable("bad builtin type kind");
5098 }
5099 
5100 /// Check an argument list for placeholders that we won't try to
5101 /// handle later.
5102 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5103   // Apply this processing to all the arguments at once instead of
5104   // dying at the first failure.
5105   bool hasInvalid = false;
5106   for (size_t i = 0, e = args.size(); i != e; i++) {
5107     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5108       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5109       if (result.isInvalid()) hasInvalid = true;
5110       else args[i] = result.get();
5111     } else if (hasInvalid) {
5112       (void)S.CorrectDelayedTyposInExpr(args[i]);
5113     }
5114   }
5115   return hasInvalid;
5116 }
5117 
5118 /// If a builtin function has a pointer argument with no explicit address
5119 /// space, then it should be able to accept a pointer to any address
5120 /// space as input.  In order to do this, we need to replace the
5121 /// standard builtin declaration with one that uses the same address space
5122 /// as the call.
5123 ///
5124 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5125 ///                  it does not contain any pointer arguments without
5126 ///                  an address space qualifer.  Otherwise the rewritten
5127 ///                  FunctionDecl is returned.
5128 /// TODO: Handle pointer return types.
5129 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5130                                                 const FunctionDecl *FDecl,
5131                                                 MultiExprArg ArgExprs) {
5132 
5133   QualType DeclType = FDecl->getType();
5134   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5135 
5136   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5137       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5138     return nullptr;
5139 
5140   bool NeedsNewDecl = false;
5141   unsigned i = 0;
5142   SmallVector<QualType, 8> OverloadParams;
5143 
5144   for (QualType ParamType : FT->param_types()) {
5145 
5146     // Convert array arguments to pointer to simplify type lookup.
5147     ExprResult ArgRes =
5148         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5149     if (ArgRes.isInvalid())
5150       return nullptr;
5151     Expr *Arg = ArgRes.get();
5152     QualType ArgType = Arg->getType();
5153     if (!ParamType->isPointerType() ||
5154         ParamType.getQualifiers().hasAddressSpace() ||
5155         !ArgType->isPointerType() ||
5156         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5157       OverloadParams.push_back(ParamType);
5158       continue;
5159     }
5160 
5161     QualType PointeeType = ParamType->getPointeeType();
5162     if (PointeeType.getQualifiers().hasAddressSpace())
5163       continue;
5164 
5165     NeedsNewDecl = true;
5166     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5167 
5168     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5169     OverloadParams.push_back(Context.getPointerType(PointeeType));
5170   }
5171 
5172   if (!NeedsNewDecl)
5173     return nullptr;
5174 
5175   FunctionProtoType::ExtProtoInfo EPI;
5176   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5177                                                 OverloadParams, EPI);
5178   DeclContext *Parent = Context.getTranslationUnitDecl();
5179   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5180                                                     FDecl->getLocation(),
5181                                                     FDecl->getLocation(),
5182                                                     FDecl->getIdentifier(),
5183                                                     OverloadTy,
5184                                                     /*TInfo=*/nullptr,
5185                                                     SC_Extern, false,
5186                                                     /*hasPrototype=*/true);
5187   SmallVector<ParmVarDecl*, 16> Params;
5188   FT = cast<FunctionProtoType>(OverloadTy);
5189   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5190     QualType ParamType = FT->getParamType(i);
5191     ParmVarDecl *Parm =
5192         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5193                                 SourceLocation(), nullptr, ParamType,
5194                                 /*TInfo=*/nullptr, SC_None, nullptr);
5195     Parm->setScopeInfo(0, i);
5196     Params.push_back(Parm);
5197   }
5198   OverloadDecl->setParams(Params);
5199   return OverloadDecl;
5200 }
5201 
5202 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5203                                     FunctionDecl *Callee,
5204                                     MultiExprArg ArgExprs) {
5205   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5206   // similar attributes) really don't like it when functions are called with an
5207   // invalid number of args.
5208   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5209                          /*PartialOverloading=*/false) &&
5210       !Callee->isVariadic())
5211     return;
5212   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5213     return;
5214 
5215   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5216     S.Diag(Fn->getBeginLoc(),
5217            isa<CXXMethodDecl>(Callee)
5218                ? diag::err_ovl_no_viable_member_function_in_call
5219                : diag::err_ovl_no_viable_function_in_call)
5220         << Callee << Callee->getSourceRange();
5221     S.Diag(Callee->getLocation(),
5222            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5223         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5224     return;
5225   }
5226 }
5227 
5228 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5229     const UnresolvedMemberExpr *const UME, Sema &S) {
5230 
5231   const auto GetFunctionLevelDCIfCXXClass =
5232       [](Sema &S) -> const CXXRecordDecl * {
5233     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5234     if (!DC || !DC->getParent())
5235       return nullptr;
5236 
5237     // If the call to some member function was made from within a member
5238     // function body 'M' return return 'M's parent.
5239     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5240       return MD->getParent()->getCanonicalDecl();
5241     // else the call was made from within a default member initializer of a
5242     // class, so return the class.
5243     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5244       return RD->getCanonicalDecl();
5245     return nullptr;
5246   };
5247   // If our DeclContext is neither a member function nor a class (in the
5248   // case of a lambda in a default member initializer), we can't have an
5249   // enclosing 'this'.
5250 
5251   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5252   if (!CurParentClass)
5253     return false;
5254 
5255   // The naming class for implicit member functions call is the class in which
5256   // name lookup starts.
5257   const CXXRecordDecl *const NamingClass =
5258       UME->getNamingClass()->getCanonicalDecl();
5259   assert(NamingClass && "Must have naming class even for implicit access");
5260 
5261   // If the unresolved member functions were found in a 'naming class' that is
5262   // related (either the same or derived from) to the class that contains the
5263   // member function that itself contained the implicit member access.
5264 
5265   return CurParentClass == NamingClass ||
5266          CurParentClass->isDerivedFrom(NamingClass);
5267 }
5268 
5269 static void
5270 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5271     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5272 
5273   if (!UME)
5274     return;
5275 
5276   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5277   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5278   // already been captured, or if this is an implicit member function call (if
5279   // it isn't, an attempt to capture 'this' should already have been made).
5280   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5281       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5282     return;
5283 
5284   // Check if the naming class in which the unresolved members were found is
5285   // related (same as or is a base of) to the enclosing class.
5286 
5287   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5288     return;
5289 
5290 
5291   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5292   // If the enclosing function is not dependent, then this lambda is
5293   // capture ready, so if we can capture this, do so.
5294   if (!EnclosingFunctionCtx->isDependentContext()) {
5295     // If the current lambda and all enclosing lambdas can capture 'this' -
5296     // then go ahead and capture 'this' (since our unresolved overload set
5297     // contains at least one non-static member function).
5298     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5299       S.CheckCXXThisCapture(CallLoc);
5300   } else if (S.CurContext->isDependentContext()) {
5301     // ... since this is an implicit member reference, that might potentially
5302     // involve a 'this' capture, mark 'this' for potential capture in
5303     // enclosing lambdas.
5304     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5305       CurLSI->addPotentialThisCapture(CallLoc);
5306   }
5307 }
5308 
5309 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5310 /// This provides the location of the left/right parens and a list of comma
5311 /// locations.
5312 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5313                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5314                                Expr *ExecConfig, bool IsExecConfig) {
5315   // Since this might be a postfix expression, get rid of ParenListExprs.
5316   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5317   if (Result.isInvalid()) return ExprError();
5318   Fn = Result.get();
5319 
5320   if (checkArgsForPlaceholders(*this, ArgExprs))
5321     return ExprError();
5322 
5323   if (getLangOpts().CPlusPlus) {
5324     // If this is a pseudo-destructor expression, build the call immediately.
5325     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5326       if (!ArgExprs.empty()) {
5327         // Pseudo-destructor calls should not have any arguments.
5328         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5329             << FixItHint::CreateRemoval(
5330                    SourceRange(ArgExprs.front()->getBeginLoc(),
5331                                ArgExprs.back()->getEndLoc()));
5332       }
5333 
5334       return new (Context)
5335           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5336     }
5337     if (Fn->getType() == Context.PseudoObjectTy) {
5338       ExprResult result = CheckPlaceholderExpr(Fn);
5339       if (result.isInvalid()) return ExprError();
5340       Fn = result.get();
5341     }
5342 
5343     // Determine whether this is a dependent call inside a C++ template,
5344     // in which case we won't do any semantic analysis now.
5345     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5346       if (ExecConfig) {
5347         return new (Context) CUDAKernelCallExpr(
5348             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5349             Context.DependentTy, VK_RValue, RParenLoc);
5350       } else {
5351 
5352         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5353             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5354             Fn->getBeginLoc());
5355 
5356         return new (Context) CallExpr(
5357             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5358       }
5359     }
5360 
5361     // Determine whether this is a call to an object (C++ [over.call.object]).
5362     if (Fn->getType()->isRecordType())
5363       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5364                                           RParenLoc);
5365 
5366     if (Fn->getType() == Context.UnknownAnyTy) {
5367       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5368       if (result.isInvalid()) return ExprError();
5369       Fn = result.get();
5370     }
5371 
5372     if (Fn->getType() == Context.BoundMemberTy) {
5373       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5374                                        RParenLoc);
5375     }
5376   }
5377 
5378   // Check for overloaded calls.  This can happen even in C due to extensions.
5379   if (Fn->getType() == Context.OverloadTy) {
5380     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5381 
5382     // We aren't supposed to apply this logic if there's an '&' involved.
5383     if (!find.HasFormOfMemberPointer) {
5384       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5385         return new (Context) CallExpr(
5386             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5387       OverloadExpr *ovl = find.Expression;
5388       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5389         return BuildOverloadedCallExpr(
5390             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5391             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5392       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5393                                        RParenLoc);
5394     }
5395   }
5396 
5397   // If we're directly calling a function, get the appropriate declaration.
5398   if (Fn->getType() == Context.UnknownAnyTy) {
5399     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5400     if (result.isInvalid()) return ExprError();
5401     Fn = result.get();
5402   }
5403 
5404   Expr *NakedFn = Fn->IgnoreParens();
5405 
5406   bool CallingNDeclIndirectly = false;
5407   NamedDecl *NDecl = nullptr;
5408   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5409     if (UnOp->getOpcode() == UO_AddrOf) {
5410       CallingNDeclIndirectly = true;
5411       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5412     }
5413   }
5414 
5415   if (isa<DeclRefExpr>(NakedFn)) {
5416     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5417 
5418     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5419     if (FDecl && FDecl->getBuiltinID()) {
5420       // Rewrite the function decl for this builtin by replacing parameters
5421       // with no explicit address space with the address space of the arguments
5422       // in ArgExprs.
5423       if ((FDecl =
5424                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5425         NDecl = FDecl;
5426         Fn = DeclRefExpr::Create(
5427             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5428             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5429       }
5430     }
5431   } else if (isa<MemberExpr>(NakedFn))
5432     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5433 
5434   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5435     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5436                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5437       return ExprError();
5438 
5439     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5440       return ExprError();
5441 
5442     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5443   }
5444 
5445   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5446                                ExecConfig, IsExecConfig);
5447 }
5448 
5449 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5450 ///
5451 /// __builtin_astype( value, dst type )
5452 ///
5453 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5454                                  SourceLocation BuiltinLoc,
5455                                  SourceLocation RParenLoc) {
5456   ExprValueKind VK = VK_RValue;
5457   ExprObjectKind OK = OK_Ordinary;
5458   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5459   QualType SrcTy = E->getType();
5460   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5461     return ExprError(Diag(BuiltinLoc,
5462                           diag::err_invalid_astype_of_different_size)
5463                      << DstTy
5464                      << SrcTy
5465                      << E->getSourceRange());
5466   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5467 }
5468 
5469 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5470 /// provided arguments.
5471 ///
5472 /// __builtin_convertvector( value, dst type )
5473 ///
5474 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5475                                         SourceLocation BuiltinLoc,
5476                                         SourceLocation RParenLoc) {
5477   TypeSourceInfo *TInfo;
5478   GetTypeFromParser(ParsedDestTy, &TInfo);
5479   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5480 }
5481 
5482 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5483 /// i.e. an expression not of \p OverloadTy.  The expression should
5484 /// unary-convert to an expression of function-pointer or
5485 /// block-pointer type.
5486 ///
5487 /// \param NDecl the declaration being called, if available
5488 ExprResult
5489 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5490                             SourceLocation LParenLoc,
5491                             ArrayRef<Expr *> Args,
5492                             SourceLocation RParenLoc,
5493                             Expr *Config, bool IsExecConfig) {
5494   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5495   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5496 
5497   // Functions with 'interrupt' attribute cannot be called directly.
5498   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5499     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5500     return ExprError();
5501   }
5502 
5503   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5504   // so there's some risk when calling out to non-interrupt handler functions
5505   // that the callee might not preserve them. This is easy to diagnose here,
5506   // but can be very challenging to debug.
5507   if (auto *Caller = getCurFunctionDecl())
5508     if (Caller->hasAttr<ARMInterruptAttr>()) {
5509       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5510       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5511         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5512     }
5513 
5514   // Promote the function operand.
5515   // We special-case function promotion here because we only allow promoting
5516   // builtin functions to function pointers in the callee of a call.
5517   ExprResult Result;
5518   if (BuiltinID &&
5519       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5520     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5521                                CK_BuiltinFnToFnPtr).get();
5522   } else {
5523     Result = CallExprUnaryConversions(Fn);
5524   }
5525   if (Result.isInvalid())
5526     return ExprError();
5527   Fn = Result.get();
5528 
5529   // Make the call expr early, before semantic checks.  This guarantees cleanup
5530   // of arguments and function on error.
5531   CallExpr *TheCall;
5532   if (Config)
5533     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5534                                                cast<CallExpr>(Config), Args,
5535                                                Context.BoolTy, VK_RValue,
5536                                                RParenLoc);
5537   else
5538     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5539                                      VK_RValue, RParenLoc);
5540 
5541   if (!getLangOpts().CPlusPlus) {
5542     // C cannot always handle TypoExpr nodes in builtin calls and direct
5543     // function calls as their argument checking don't necessarily handle
5544     // dependent types properly, so make sure any TypoExprs have been
5545     // dealt with.
5546     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5547     if (!Result.isUsable()) return ExprError();
5548     TheCall = dyn_cast<CallExpr>(Result.get());
5549     if (!TheCall) return Result;
5550     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5551   }
5552 
5553   // Bail out early if calling a builtin with custom typechecking.
5554   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5555     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5556 
5557  retry:
5558   const FunctionType *FuncT;
5559   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5560     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5561     // have type pointer to function".
5562     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5563     if (!FuncT)
5564       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5565                          << Fn->getType() << Fn->getSourceRange());
5566   } else if (const BlockPointerType *BPT =
5567                Fn->getType()->getAs<BlockPointerType>()) {
5568     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5569   } else {
5570     // Handle calls to expressions of unknown-any type.
5571     if (Fn->getType() == Context.UnknownAnyTy) {
5572       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5573       if (rewrite.isInvalid()) return ExprError();
5574       Fn = rewrite.get();
5575       TheCall->setCallee(Fn);
5576       goto retry;
5577     }
5578 
5579     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5580       << Fn->getType() << Fn->getSourceRange());
5581   }
5582 
5583   if (getLangOpts().CUDA) {
5584     if (Config) {
5585       // CUDA: Kernel calls must be to global functions
5586       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5587         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5588             << FDecl << Fn->getSourceRange());
5589 
5590       // CUDA: Kernel function must have 'void' return type
5591       if (!FuncT->getReturnType()->isVoidType())
5592         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5593             << Fn->getType() << Fn->getSourceRange());
5594     } else {
5595       // CUDA: Calls to global functions must be configured
5596       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5597         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5598             << FDecl << Fn->getSourceRange());
5599     }
5600   }
5601 
5602   // Check for a valid return type
5603   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5604                           FDecl))
5605     return ExprError();
5606 
5607   // We know the result type of the call, set it.
5608   TheCall->setType(FuncT->getCallResultType(Context));
5609   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5610 
5611   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5612   if (Proto) {
5613     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5614                                 IsExecConfig))
5615       return ExprError();
5616   } else {
5617     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5618 
5619     if (FDecl) {
5620       // Check if we have too few/too many template arguments, based
5621       // on our knowledge of the function definition.
5622       const FunctionDecl *Def = nullptr;
5623       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5624         Proto = Def->getType()->getAs<FunctionProtoType>();
5625        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5626           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5627           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5628       }
5629 
5630       // If the function we're calling isn't a function prototype, but we have
5631       // a function prototype from a prior declaratiom, use that prototype.
5632       if (!FDecl->hasPrototype())
5633         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5634     }
5635 
5636     // Promote the arguments (C99 6.5.2.2p6).
5637     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5638       Expr *Arg = Args[i];
5639 
5640       if (Proto && i < Proto->getNumParams()) {
5641         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5642             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5643         ExprResult ArgE =
5644             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5645         if (ArgE.isInvalid())
5646           return true;
5647 
5648         Arg = ArgE.getAs<Expr>();
5649 
5650       } else {
5651         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5652 
5653         if (ArgE.isInvalid())
5654           return true;
5655 
5656         Arg = ArgE.getAs<Expr>();
5657       }
5658 
5659       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5660                               diag::err_call_incomplete_argument, Arg))
5661         return ExprError();
5662 
5663       TheCall->setArg(i, Arg);
5664     }
5665   }
5666 
5667   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5668     if (!Method->isStatic())
5669       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5670         << Fn->getSourceRange());
5671 
5672   // Check for sentinels
5673   if (NDecl)
5674     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5675 
5676   // Do special checking on direct calls to functions.
5677   if (FDecl) {
5678     if (CheckFunctionCall(FDecl, TheCall, Proto))
5679       return ExprError();
5680 
5681     if (BuiltinID)
5682       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5683   } else if (NDecl) {
5684     if (CheckPointerCall(NDecl, TheCall, Proto))
5685       return ExprError();
5686   } else {
5687     if (CheckOtherCall(TheCall, Proto))
5688       return ExprError();
5689   }
5690 
5691   return MaybeBindToTemporary(TheCall);
5692 }
5693 
5694 ExprResult
5695 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5696                            SourceLocation RParenLoc, Expr *InitExpr) {
5697   assert(Ty && "ActOnCompoundLiteral(): missing type");
5698   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5699 
5700   TypeSourceInfo *TInfo;
5701   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5702   if (!TInfo)
5703     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5704 
5705   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5706 }
5707 
5708 ExprResult
5709 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5710                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5711   QualType literalType = TInfo->getType();
5712 
5713   if (literalType->isArrayType()) {
5714     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5715           diag::err_illegal_decl_array_incomplete_type,
5716           SourceRange(LParenLoc,
5717                       LiteralExpr->getSourceRange().getEnd())))
5718       return ExprError();
5719     if (literalType->isVariableArrayType())
5720       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5721         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5722   } else if (!literalType->isDependentType() &&
5723              RequireCompleteType(LParenLoc, literalType,
5724                diag::err_typecheck_decl_incomplete_type,
5725                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5726     return ExprError();
5727 
5728   InitializedEntity Entity
5729     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5730   InitializationKind Kind
5731     = InitializationKind::CreateCStyleCast(LParenLoc,
5732                                            SourceRange(LParenLoc, RParenLoc),
5733                                            /*InitList=*/true);
5734   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5735   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5736                                       &literalType);
5737   if (Result.isInvalid())
5738     return ExprError();
5739   LiteralExpr = Result.get();
5740 
5741   bool isFileScope = !CurContext->isFunctionOrMethod();
5742   if (isFileScope) {
5743     if (!LiteralExpr->isTypeDependent() &&
5744         !LiteralExpr->isValueDependent() &&
5745         !literalType->isDependentType()) // C99 6.5.2.5p3
5746       if (CheckForConstantInitializer(LiteralExpr, literalType))
5747         return ExprError();
5748   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
5749              literalType.getAddressSpace() != LangAS::Default) {
5750     // Embedded-C extensions to C99 6.5.2.5:
5751     //   "If the compound literal occurs inside the body of a function, the
5752     //   type name shall not be qualified by an address-space qualifier."
5753     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
5754       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
5755     return ExprError();
5756   }
5757 
5758   // In C, compound literals are l-values for some reason.
5759   // For GCC compatibility, in C++, file-scope array compound literals with
5760   // constant initializers are also l-values, and compound literals are
5761   // otherwise prvalues.
5762   //
5763   // (GCC also treats C++ list-initialized file-scope array prvalues with
5764   // constant initializers as l-values, but that's non-conforming, so we don't
5765   // follow it there.)
5766   //
5767   // FIXME: It would be better to handle the lvalue cases as materializing and
5768   // lifetime-extending a temporary object, but our materialized temporaries
5769   // representation only supports lifetime extension from a variable, not "out
5770   // of thin air".
5771   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5772   // is bound to the result of applying array-to-pointer decay to the compound
5773   // literal.
5774   // FIXME: GCC supports compound literals of reference type, which should
5775   // obviously have a value kind derived from the kind of reference involved.
5776   ExprValueKind VK =
5777       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5778           ? VK_RValue
5779           : VK_LValue;
5780 
5781   return MaybeBindToTemporary(
5782       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5783                                         VK, LiteralExpr, isFileScope));
5784 }
5785 
5786 ExprResult
5787 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5788                     SourceLocation RBraceLoc) {
5789   // Immediately handle non-overload placeholders.  Overloads can be
5790   // resolved contextually, but everything else here can't.
5791   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5792     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5793       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5794 
5795       // Ignore failures; dropping the entire initializer list because
5796       // of one failure would be terrible for indexing/etc.
5797       if (result.isInvalid()) continue;
5798 
5799       InitArgList[I] = result.get();
5800     }
5801   }
5802 
5803   // Semantic analysis for initializers is done by ActOnDeclarator() and
5804   // CheckInitializer() - it requires knowledge of the object being initialized.
5805 
5806   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5807                                                RBraceLoc);
5808   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5809   return E;
5810 }
5811 
5812 /// Do an explicit extend of the given block pointer if we're in ARC.
5813 void Sema::maybeExtendBlockObject(ExprResult &E) {
5814   assert(E.get()->getType()->isBlockPointerType());
5815   assert(E.get()->isRValue());
5816 
5817   // Only do this in an r-value context.
5818   if (!getLangOpts().ObjCAutoRefCount) return;
5819 
5820   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5821                                CK_ARCExtendBlockObject, E.get(),
5822                                /*base path*/ nullptr, VK_RValue);
5823   Cleanup.setExprNeedsCleanups(true);
5824 }
5825 
5826 /// Prepare a conversion of the given expression to an ObjC object
5827 /// pointer type.
5828 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5829   QualType type = E.get()->getType();
5830   if (type->isObjCObjectPointerType()) {
5831     return CK_BitCast;
5832   } else if (type->isBlockPointerType()) {
5833     maybeExtendBlockObject(E);
5834     return CK_BlockPointerToObjCPointerCast;
5835   } else {
5836     assert(type->isPointerType());
5837     return CK_CPointerToObjCPointerCast;
5838   }
5839 }
5840 
5841 /// Prepares for a scalar cast, performing all the necessary stages
5842 /// except the final cast and returning the kind required.
5843 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5844   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5845   // Also, callers should have filtered out the invalid cases with
5846   // pointers.  Everything else should be possible.
5847 
5848   QualType SrcTy = Src.get()->getType();
5849   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5850     return CK_NoOp;
5851 
5852   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5853   case Type::STK_MemberPointer:
5854     llvm_unreachable("member pointer type in C");
5855 
5856   case Type::STK_CPointer:
5857   case Type::STK_BlockPointer:
5858   case Type::STK_ObjCObjectPointer:
5859     switch (DestTy->getScalarTypeKind()) {
5860     case Type::STK_CPointer: {
5861       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5862       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5863       if (SrcAS != DestAS)
5864         return CK_AddressSpaceConversion;
5865       if (Context.hasCvrSimilarType(SrcTy, DestTy))
5866         return CK_NoOp;
5867       return CK_BitCast;
5868     }
5869     case Type::STK_BlockPointer:
5870       return (SrcKind == Type::STK_BlockPointer
5871                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5872     case Type::STK_ObjCObjectPointer:
5873       if (SrcKind == Type::STK_ObjCObjectPointer)
5874         return CK_BitCast;
5875       if (SrcKind == Type::STK_CPointer)
5876         return CK_CPointerToObjCPointerCast;
5877       maybeExtendBlockObject(Src);
5878       return CK_BlockPointerToObjCPointerCast;
5879     case Type::STK_Bool:
5880       return CK_PointerToBoolean;
5881     case Type::STK_Integral:
5882       return CK_PointerToIntegral;
5883     case Type::STK_Floating:
5884     case Type::STK_FloatingComplex:
5885     case Type::STK_IntegralComplex:
5886     case Type::STK_MemberPointer:
5887     case Type::STK_FixedPoint:
5888       llvm_unreachable("illegal cast from pointer");
5889     }
5890     llvm_unreachable("Should have returned before this");
5891 
5892   case Type::STK_FixedPoint:
5893     switch (DestTy->getScalarTypeKind()) {
5894     case Type::STK_FixedPoint:
5895       return CK_FixedPointCast;
5896     case Type::STK_Bool:
5897       Diag(Src.get()->getExprLoc(),
5898            diag::err_unimplemented_conversion_with_fixed_point_type)
5899           << DestTy;
5900       return CK_IntegralToBoolean;
5901     case Type::STK_Integral:
5902     case Type::STK_Floating:
5903     case Type::STK_IntegralComplex:
5904     case Type::STK_FloatingComplex:
5905       Diag(Src.get()->getExprLoc(),
5906            diag::err_unimplemented_conversion_with_fixed_point_type)
5907           << DestTy;
5908       return CK_IntegralCast;
5909     case Type::STK_CPointer:
5910     case Type::STK_ObjCObjectPointer:
5911     case Type::STK_BlockPointer:
5912     case Type::STK_MemberPointer:
5913       llvm_unreachable("illegal cast to pointer type");
5914     }
5915     llvm_unreachable("Should have returned before this");
5916 
5917   case Type::STK_Bool: // casting from bool is like casting from an integer
5918   case Type::STK_Integral:
5919     switch (DestTy->getScalarTypeKind()) {
5920     case Type::STK_CPointer:
5921     case Type::STK_ObjCObjectPointer:
5922     case Type::STK_BlockPointer:
5923       if (Src.get()->isNullPointerConstant(Context,
5924                                            Expr::NPC_ValueDependentIsNull))
5925         return CK_NullToPointer;
5926       return CK_IntegralToPointer;
5927     case Type::STK_Bool:
5928       return CK_IntegralToBoolean;
5929     case Type::STK_Integral:
5930       return CK_IntegralCast;
5931     case Type::STK_Floating:
5932       return CK_IntegralToFloating;
5933     case Type::STK_IntegralComplex:
5934       Src = ImpCastExprToType(Src.get(),
5935                       DestTy->castAs<ComplexType>()->getElementType(),
5936                       CK_IntegralCast);
5937       return CK_IntegralRealToComplex;
5938     case Type::STK_FloatingComplex:
5939       Src = ImpCastExprToType(Src.get(),
5940                       DestTy->castAs<ComplexType>()->getElementType(),
5941                       CK_IntegralToFloating);
5942       return CK_FloatingRealToComplex;
5943     case Type::STK_MemberPointer:
5944       llvm_unreachable("member pointer type in C");
5945     case Type::STK_FixedPoint:
5946       Diag(Src.get()->getExprLoc(),
5947            diag::err_unimplemented_conversion_with_fixed_point_type)
5948           << SrcTy;
5949       return CK_IntegralCast;
5950     }
5951     llvm_unreachable("Should have returned before this");
5952 
5953   case Type::STK_Floating:
5954     switch (DestTy->getScalarTypeKind()) {
5955     case Type::STK_Floating:
5956       return CK_FloatingCast;
5957     case Type::STK_Bool:
5958       return CK_FloatingToBoolean;
5959     case Type::STK_Integral:
5960       return CK_FloatingToIntegral;
5961     case Type::STK_FloatingComplex:
5962       Src = ImpCastExprToType(Src.get(),
5963                               DestTy->castAs<ComplexType>()->getElementType(),
5964                               CK_FloatingCast);
5965       return CK_FloatingRealToComplex;
5966     case Type::STK_IntegralComplex:
5967       Src = ImpCastExprToType(Src.get(),
5968                               DestTy->castAs<ComplexType>()->getElementType(),
5969                               CK_FloatingToIntegral);
5970       return CK_IntegralRealToComplex;
5971     case Type::STK_CPointer:
5972     case Type::STK_ObjCObjectPointer:
5973     case Type::STK_BlockPointer:
5974       llvm_unreachable("valid float->pointer cast?");
5975     case Type::STK_MemberPointer:
5976       llvm_unreachable("member pointer type in C");
5977     case Type::STK_FixedPoint:
5978       Diag(Src.get()->getExprLoc(),
5979            diag::err_unimplemented_conversion_with_fixed_point_type)
5980           << SrcTy;
5981       return CK_IntegralCast;
5982     }
5983     llvm_unreachable("Should have returned before this");
5984 
5985   case Type::STK_FloatingComplex:
5986     switch (DestTy->getScalarTypeKind()) {
5987     case Type::STK_FloatingComplex:
5988       return CK_FloatingComplexCast;
5989     case Type::STK_IntegralComplex:
5990       return CK_FloatingComplexToIntegralComplex;
5991     case Type::STK_Floating: {
5992       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5993       if (Context.hasSameType(ET, DestTy))
5994         return CK_FloatingComplexToReal;
5995       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5996       return CK_FloatingCast;
5997     }
5998     case Type::STK_Bool:
5999       return CK_FloatingComplexToBoolean;
6000     case Type::STK_Integral:
6001       Src = ImpCastExprToType(Src.get(),
6002                               SrcTy->castAs<ComplexType>()->getElementType(),
6003                               CK_FloatingComplexToReal);
6004       return CK_FloatingToIntegral;
6005     case Type::STK_CPointer:
6006     case Type::STK_ObjCObjectPointer:
6007     case Type::STK_BlockPointer:
6008       llvm_unreachable("valid complex float->pointer cast?");
6009     case Type::STK_MemberPointer:
6010       llvm_unreachable("member pointer type in C");
6011     case Type::STK_FixedPoint:
6012       Diag(Src.get()->getExprLoc(),
6013            diag::err_unimplemented_conversion_with_fixed_point_type)
6014           << SrcTy;
6015       return CK_IntegralCast;
6016     }
6017     llvm_unreachable("Should have returned before this");
6018 
6019   case Type::STK_IntegralComplex:
6020     switch (DestTy->getScalarTypeKind()) {
6021     case Type::STK_FloatingComplex:
6022       return CK_IntegralComplexToFloatingComplex;
6023     case Type::STK_IntegralComplex:
6024       return CK_IntegralComplexCast;
6025     case Type::STK_Integral: {
6026       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6027       if (Context.hasSameType(ET, DestTy))
6028         return CK_IntegralComplexToReal;
6029       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6030       return CK_IntegralCast;
6031     }
6032     case Type::STK_Bool:
6033       return CK_IntegralComplexToBoolean;
6034     case Type::STK_Floating:
6035       Src = ImpCastExprToType(Src.get(),
6036                               SrcTy->castAs<ComplexType>()->getElementType(),
6037                               CK_IntegralComplexToReal);
6038       return CK_IntegralToFloating;
6039     case Type::STK_CPointer:
6040     case Type::STK_ObjCObjectPointer:
6041     case Type::STK_BlockPointer:
6042       llvm_unreachable("valid complex int->pointer cast?");
6043     case Type::STK_MemberPointer:
6044       llvm_unreachable("member pointer type in C");
6045     case Type::STK_FixedPoint:
6046       Diag(Src.get()->getExprLoc(),
6047            diag::err_unimplemented_conversion_with_fixed_point_type)
6048           << SrcTy;
6049       return CK_IntegralCast;
6050     }
6051     llvm_unreachable("Should have returned before this");
6052   }
6053 
6054   llvm_unreachable("Unhandled scalar cast");
6055 }
6056 
6057 static bool breakDownVectorType(QualType type, uint64_t &len,
6058                                 QualType &eltType) {
6059   // Vectors are simple.
6060   if (const VectorType *vecType = type->getAs<VectorType>()) {
6061     len = vecType->getNumElements();
6062     eltType = vecType->getElementType();
6063     assert(eltType->isScalarType());
6064     return true;
6065   }
6066 
6067   // We allow lax conversion to and from non-vector types, but only if
6068   // they're real types (i.e. non-complex, non-pointer scalar types).
6069   if (!type->isRealType()) return false;
6070 
6071   len = 1;
6072   eltType = type;
6073   return true;
6074 }
6075 
6076 /// Are the two types lax-compatible vector types?  That is, given
6077 /// that one of them is a vector, do they have equal storage sizes,
6078 /// where the storage size is the number of elements times the element
6079 /// size?
6080 ///
6081 /// This will also return false if either of the types is neither a
6082 /// vector nor a real type.
6083 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6084   assert(destTy->isVectorType() || srcTy->isVectorType());
6085 
6086   // Disallow lax conversions between scalars and ExtVectors (these
6087   // conversions are allowed for other vector types because common headers
6088   // depend on them).  Most scalar OP ExtVector cases are handled by the
6089   // splat path anyway, which does what we want (convert, not bitcast).
6090   // What this rules out for ExtVectors is crazy things like char4*float.
6091   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6092   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6093 
6094   uint64_t srcLen, destLen;
6095   QualType srcEltTy, destEltTy;
6096   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6097   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6098 
6099   // ASTContext::getTypeSize will return the size rounded up to a
6100   // power of 2, so instead of using that, we need to use the raw
6101   // element size multiplied by the element count.
6102   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6103   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6104 
6105   return (srcLen * srcEltSize == destLen * destEltSize);
6106 }
6107 
6108 /// Is this a legal conversion between two types, one of which is
6109 /// known to be a vector type?
6110 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6111   assert(destTy->isVectorType() || srcTy->isVectorType());
6112 
6113   if (!Context.getLangOpts().LaxVectorConversions)
6114     return false;
6115   return areLaxCompatibleVectorTypes(srcTy, destTy);
6116 }
6117 
6118 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6119                            CastKind &Kind) {
6120   assert(VectorTy->isVectorType() && "Not a vector type!");
6121 
6122   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6123     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6124       return Diag(R.getBegin(),
6125                   Ty->isVectorType() ?
6126                   diag::err_invalid_conversion_between_vectors :
6127                   diag::err_invalid_conversion_between_vector_and_integer)
6128         << VectorTy << Ty << R;
6129   } else
6130     return Diag(R.getBegin(),
6131                 diag::err_invalid_conversion_between_vector_and_scalar)
6132       << VectorTy << Ty << R;
6133 
6134   Kind = CK_BitCast;
6135   return false;
6136 }
6137 
6138 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6139   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6140 
6141   if (DestElemTy == SplattedExpr->getType())
6142     return SplattedExpr;
6143 
6144   assert(DestElemTy->isFloatingType() ||
6145          DestElemTy->isIntegralOrEnumerationType());
6146 
6147   CastKind CK;
6148   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6149     // OpenCL requires that we convert `true` boolean expressions to -1, but
6150     // only when splatting vectors.
6151     if (DestElemTy->isFloatingType()) {
6152       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6153       // in two steps: boolean to signed integral, then to floating.
6154       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6155                                                  CK_BooleanToSignedIntegral);
6156       SplattedExpr = CastExprRes.get();
6157       CK = CK_IntegralToFloating;
6158     } else {
6159       CK = CK_BooleanToSignedIntegral;
6160     }
6161   } else {
6162     ExprResult CastExprRes = SplattedExpr;
6163     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6164     if (CastExprRes.isInvalid())
6165       return ExprError();
6166     SplattedExpr = CastExprRes.get();
6167   }
6168   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6169 }
6170 
6171 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6172                                     Expr *CastExpr, CastKind &Kind) {
6173   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6174 
6175   QualType SrcTy = CastExpr->getType();
6176 
6177   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6178   // an ExtVectorType.
6179   // In OpenCL, casts between vectors of different types are not allowed.
6180   // (See OpenCL 6.2).
6181   if (SrcTy->isVectorType()) {
6182     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6183         (getLangOpts().OpenCL &&
6184          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6185       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6186         << DestTy << SrcTy << R;
6187       return ExprError();
6188     }
6189     Kind = CK_BitCast;
6190     return CastExpr;
6191   }
6192 
6193   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6194   // conversion will take place first from scalar to elt type, and then
6195   // splat from elt type to vector.
6196   if (SrcTy->isPointerType())
6197     return Diag(R.getBegin(),
6198                 diag::err_invalid_conversion_between_vector_and_scalar)
6199       << DestTy << SrcTy << R;
6200 
6201   Kind = CK_VectorSplat;
6202   return prepareVectorSplat(DestTy, CastExpr);
6203 }
6204 
6205 ExprResult
6206 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6207                     Declarator &D, ParsedType &Ty,
6208                     SourceLocation RParenLoc, Expr *CastExpr) {
6209   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6210          "ActOnCastExpr(): missing type or expr");
6211 
6212   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6213   if (D.isInvalidType())
6214     return ExprError();
6215 
6216   if (getLangOpts().CPlusPlus) {
6217     // Check that there are no default arguments (C++ only).
6218     CheckExtraCXXDefaultArguments(D);
6219   } else {
6220     // Make sure any TypoExprs have been dealt with.
6221     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6222     if (!Res.isUsable())
6223       return ExprError();
6224     CastExpr = Res.get();
6225   }
6226 
6227   checkUnusedDeclAttributes(D);
6228 
6229   QualType castType = castTInfo->getType();
6230   Ty = CreateParsedType(castType, castTInfo);
6231 
6232   bool isVectorLiteral = false;
6233 
6234   // Check for an altivec or OpenCL literal,
6235   // i.e. all the elements are integer constants.
6236   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6237   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6238   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6239        && castType->isVectorType() && (PE || PLE)) {
6240     if (PLE && PLE->getNumExprs() == 0) {
6241       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6242       return ExprError();
6243     }
6244     if (PE || PLE->getNumExprs() == 1) {
6245       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6246       if (!E->getType()->isVectorType())
6247         isVectorLiteral = true;
6248     }
6249     else
6250       isVectorLiteral = true;
6251   }
6252 
6253   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6254   // then handle it as such.
6255   if (isVectorLiteral)
6256     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6257 
6258   // If the Expr being casted is a ParenListExpr, handle it specially.
6259   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6260   // sequence of BinOp comma operators.
6261   if (isa<ParenListExpr>(CastExpr)) {
6262     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6263     if (Result.isInvalid()) return ExprError();
6264     CastExpr = Result.get();
6265   }
6266 
6267   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6268       !getSourceManager().isInSystemMacro(LParenLoc))
6269     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6270 
6271   CheckTollFreeBridgeCast(castType, CastExpr);
6272 
6273   CheckObjCBridgeRelatedCast(castType, CastExpr);
6274 
6275   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6276 
6277   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6278 }
6279 
6280 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6281                                     SourceLocation RParenLoc, Expr *E,
6282                                     TypeSourceInfo *TInfo) {
6283   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6284          "Expected paren or paren list expression");
6285 
6286   Expr **exprs;
6287   unsigned numExprs;
6288   Expr *subExpr;
6289   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6290   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6291     LiteralLParenLoc = PE->getLParenLoc();
6292     LiteralRParenLoc = PE->getRParenLoc();
6293     exprs = PE->getExprs();
6294     numExprs = PE->getNumExprs();
6295   } else { // isa<ParenExpr> by assertion at function entrance
6296     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6297     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6298     subExpr = cast<ParenExpr>(E)->getSubExpr();
6299     exprs = &subExpr;
6300     numExprs = 1;
6301   }
6302 
6303   QualType Ty = TInfo->getType();
6304   assert(Ty->isVectorType() && "Expected vector type");
6305 
6306   SmallVector<Expr *, 8> initExprs;
6307   const VectorType *VTy = Ty->getAs<VectorType>();
6308   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6309 
6310   // '(...)' form of vector initialization in AltiVec: the number of
6311   // initializers must be one or must match the size of the vector.
6312   // If a single value is specified in the initializer then it will be
6313   // replicated to all the components of the vector
6314   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6315     // The number of initializers must be one or must match the size of the
6316     // vector. If a single value is specified in the initializer then it will
6317     // be replicated to all the components of the vector
6318     if (numExprs == 1) {
6319       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6320       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6321       if (Literal.isInvalid())
6322         return ExprError();
6323       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6324                                   PrepareScalarCast(Literal, ElemTy));
6325       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6326     }
6327     else if (numExprs < numElems) {
6328       Diag(E->getExprLoc(),
6329            diag::err_incorrect_number_of_vector_initializers);
6330       return ExprError();
6331     }
6332     else
6333       initExprs.append(exprs, exprs + numExprs);
6334   }
6335   else {
6336     // For OpenCL, when the number of initializers is a single value,
6337     // it will be replicated to all components of the vector.
6338     if (getLangOpts().OpenCL &&
6339         VTy->getVectorKind() == VectorType::GenericVector &&
6340         numExprs == 1) {
6341         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6342         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6343         if (Literal.isInvalid())
6344           return ExprError();
6345         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6346                                     PrepareScalarCast(Literal, ElemTy));
6347         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6348     }
6349 
6350     initExprs.append(exprs, exprs + numExprs);
6351   }
6352   // FIXME: This means that pretty-printing the final AST will produce curly
6353   // braces instead of the original commas.
6354   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6355                                                    initExprs, LiteralRParenLoc);
6356   initE->setType(Ty);
6357   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6358 }
6359 
6360 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6361 /// the ParenListExpr into a sequence of comma binary operators.
6362 ExprResult
6363 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6364   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6365   if (!E)
6366     return OrigExpr;
6367 
6368   ExprResult Result(E->getExpr(0));
6369 
6370   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6371     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6372                         E->getExpr(i));
6373 
6374   if (Result.isInvalid()) return ExprError();
6375 
6376   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6377 }
6378 
6379 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6380                                     SourceLocation R,
6381                                     MultiExprArg Val) {
6382   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6383   return expr;
6384 }
6385 
6386 /// Emit a specialized diagnostic when one expression is a null pointer
6387 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6388 /// emitted.
6389 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6390                                       SourceLocation QuestionLoc) {
6391   Expr *NullExpr = LHSExpr;
6392   Expr *NonPointerExpr = RHSExpr;
6393   Expr::NullPointerConstantKind NullKind =
6394       NullExpr->isNullPointerConstant(Context,
6395                                       Expr::NPC_ValueDependentIsNotNull);
6396 
6397   if (NullKind == Expr::NPCK_NotNull) {
6398     NullExpr = RHSExpr;
6399     NonPointerExpr = LHSExpr;
6400     NullKind =
6401         NullExpr->isNullPointerConstant(Context,
6402                                         Expr::NPC_ValueDependentIsNotNull);
6403   }
6404 
6405   if (NullKind == Expr::NPCK_NotNull)
6406     return false;
6407 
6408   if (NullKind == Expr::NPCK_ZeroExpression)
6409     return false;
6410 
6411   if (NullKind == Expr::NPCK_ZeroLiteral) {
6412     // In this case, check to make sure that we got here from a "NULL"
6413     // string in the source code.
6414     NullExpr = NullExpr->IgnoreParenImpCasts();
6415     SourceLocation loc = NullExpr->getExprLoc();
6416     if (!findMacroSpelling(loc, "NULL"))
6417       return false;
6418   }
6419 
6420   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6421   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6422       << NonPointerExpr->getType() << DiagType
6423       << NonPointerExpr->getSourceRange();
6424   return true;
6425 }
6426 
6427 /// Return false if the condition expression is valid, true otherwise.
6428 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6429   QualType CondTy = Cond->getType();
6430 
6431   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6432   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6433     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6434       << CondTy << Cond->getSourceRange();
6435     return true;
6436   }
6437 
6438   // C99 6.5.15p2
6439   if (CondTy->isScalarType()) return false;
6440 
6441   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6442     << CondTy << Cond->getSourceRange();
6443   return true;
6444 }
6445 
6446 /// Handle when one or both operands are void type.
6447 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6448                                          ExprResult &RHS) {
6449     Expr *LHSExpr = LHS.get();
6450     Expr *RHSExpr = RHS.get();
6451 
6452     if (!LHSExpr->getType()->isVoidType())
6453       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6454           << RHSExpr->getSourceRange();
6455     if (!RHSExpr->getType()->isVoidType())
6456       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6457           << LHSExpr->getSourceRange();
6458     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6459     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6460     return S.Context.VoidTy;
6461 }
6462 
6463 /// Return false if the NullExpr can be promoted to PointerTy,
6464 /// true otherwise.
6465 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6466                                         QualType PointerTy) {
6467   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6468       !NullExpr.get()->isNullPointerConstant(S.Context,
6469                                             Expr::NPC_ValueDependentIsNull))
6470     return true;
6471 
6472   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6473   return false;
6474 }
6475 
6476 /// Checks compatibility between two pointers and return the resulting
6477 /// type.
6478 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6479                                                      ExprResult &RHS,
6480                                                      SourceLocation Loc) {
6481   QualType LHSTy = LHS.get()->getType();
6482   QualType RHSTy = RHS.get()->getType();
6483 
6484   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6485     // Two identical pointers types are always compatible.
6486     return LHSTy;
6487   }
6488 
6489   QualType lhptee, rhptee;
6490 
6491   // Get the pointee types.
6492   bool IsBlockPointer = false;
6493   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6494     lhptee = LHSBTy->getPointeeType();
6495     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6496     IsBlockPointer = true;
6497   } else {
6498     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6499     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6500   }
6501 
6502   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6503   // differently qualified versions of compatible types, the result type is
6504   // a pointer to an appropriately qualified version of the composite
6505   // type.
6506 
6507   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6508   // clause doesn't make sense for our extensions. E.g. address space 2 should
6509   // be incompatible with address space 3: they may live on different devices or
6510   // anything.
6511   Qualifiers lhQual = lhptee.getQualifiers();
6512   Qualifiers rhQual = rhptee.getQualifiers();
6513 
6514   LangAS ResultAddrSpace = LangAS::Default;
6515   LangAS LAddrSpace = lhQual.getAddressSpace();
6516   LangAS RAddrSpace = rhQual.getAddressSpace();
6517 
6518   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6519   // spaces is disallowed.
6520   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6521     ResultAddrSpace = LAddrSpace;
6522   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6523     ResultAddrSpace = RAddrSpace;
6524   else {
6525     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6526         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6527         << RHS.get()->getSourceRange();
6528     return QualType();
6529   }
6530 
6531   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6532   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6533   lhQual.removeCVRQualifiers();
6534   rhQual.removeCVRQualifiers();
6535 
6536   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6537   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6538   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6539   // qual types are compatible iff
6540   //  * corresponded types are compatible
6541   //  * CVR qualifiers are equal
6542   //  * address spaces are equal
6543   // Thus for conditional operator we merge CVR and address space unqualified
6544   // pointees and if there is a composite type we return a pointer to it with
6545   // merged qualifiers.
6546   LHSCastKind =
6547       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6548   RHSCastKind =
6549       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6550   lhQual.removeAddressSpace();
6551   rhQual.removeAddressSpace();
6552 
6553   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6554   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6555 
6556   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6557 
6558   if (CompositeTy.isNull()) {
6559     // In this situation, we assume void* type. No especially good
6560     // reason, but this is what gcc does, and we do have to pick
6561     // to get a consistent AST.
6562     QualType incompatTy;
6563     incompatTy = S.Context.getPointerType(
6564         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6565     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6566     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6567 
6568     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6569     // for casts between types with incompatible address space qualifiers.
6570     // For the following code the compiler produces casts between global and
6571     // local address spaces of the corresponded innermost pointees:
6572     // local int *global *a;
6573     // global int *global *b;
6574     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6575     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6576         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6577         << RHS.get()->getSourceRange();
6578 
6579     return incompatTy;
6580   }
6581 
6582   // The pointer types are compatible.
6583   // In case of OpenCL ResultTy should have the address space qualifier
6584   // which is a superset of address spaces of both the 2nd and the 3rd
6585   // operands of the conditional operator.
6586   QualType ResultTy = [&, ResultAddrSpace]() {
6587     if (S.getLangOpts().OpenCL) {
6588       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6589       CompositeQuals.setAddressSpace(ResultAddrSpace);
6590       return S.Context
6591           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6592           .withCVRQualifiers(MergedCVRQual);
6593     }
6594     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6595   }();
6596   if (IsBlockPointer)
6597     ResultTy = S.Context.getBlockPointerType(ResultTy);
6598   else
6599     ResultTy = S.Context.getPointerType(ResultTy);
6600 
6601   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6602   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6603   return ResultTy;
6604 }
6605 
6606 /// Return the resulting type when the operands are both block pointers.
6607 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6608                                                           ExprResult &LHS,
6609                                                           ExprResult &RHS,
6610                                                           SourceLocation Loc) {
6611   QualType LHSTy = LHS.get()->getType();
6612   QualType RHSTy = RHS.get()->getType();
6613 
6614   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6615     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6616       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6617       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6618       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6619       return destType;
6620     }
6621     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6622       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6623       << RHS.get()->getSourceRange();
6624     return QualType();
6625   }
6626 
6627   // We have 2 block pointer types.
6628   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6629 }
6630 
6631 /// Return the resulting type when the operands are both pointers.
6632 static QualType
6633 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6634                                             ExprResult &RHS,
6635                                             SourceLocation Loc) {
6636   // get the pointer types
6637   QualType LHSTy = LHS.get()->getType();
6638   QualType RHSTy = RHS.get()->getType();
6639 
6640   // get the "pointed to" types
6641   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6642   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6643 
6644   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6645   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6646     // Figure out necessary qualifiers (C99 6.5.15p6)
6647     QualType destPointee
6648       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6649     QualType destType = S.Context.getPointerType(destPointee);
6650     // Add qualifiers if necessary.
6651     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6652     // Promote to void*.
6653     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6654     return destType;
6655   }
6656   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6657     QualType destPointee
6658       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6659     QualType destType = S.Context.getPointerType(destPointee);
6660     // Add qualifiers if necessary.
6661     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6662     // Promote to void*.
6663     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6664     return destType;
6665   }
6666 
6667   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6668 }
6669 
6670 /// Return false if the first expression is not an integer and the second
6671 /// expression is not a pointer, true otherwise.
6672 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6673                                         Expr* PointerExpr, SourceLocation Loc,
6674                                         bool IsIntFirstExpr) {
6675   if (!PointerExpr->getType()->isPointerType() ||
6676       !Int.get()->getType()->isIntegerType())
6677     return false;
6678 
6679   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6680   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6681 
6682   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6683     << Expr1->getType() << Expr2->getType()
6684     << Expr1->getSourceRange() << Expr2->getSourceRange();
6685   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6686                             CK_IntegralToPointer);
6687   return true;
6688 }
6689 
6690 /// Simple conversion between integer and floating point types.
6691 ///
6692 /// Used when handling the OpenCL conditional operator where the
6693 /// condition is a vector while the other operands are scalar.
6694 ///
6695 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6696 /// types are either integer or floating type. Between the two
6697 /// operands, the type with the higher rank is defined as the "result
6698 /// type". The other operand needs to be promoted to the same type. No
6699 /// other type promotion is allowed. We cannot use
6700 /// UsualArithmeticConversions() for this purpose, since it always
6701 /// promotes promotable types.
6702 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6703                                             ExprResult &RHS,
6704                                             SourceLocation QuestionLoc) {
6705   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6706   if (LHS.isInvalid())
6707     return QualType();
6708   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6709   if (RHS.isInvalid())
6710     return QualType();
6711 
6712   // For conversion purposes, we ignore any qualifiers.
6713   // For example, "const float" and "float" are equivalent.
6714   QualType LHSType =
6715     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6716   QualType RHSType =
6717     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6718 
6719   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6720     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6721       << LHSType << LHS.get()->getSourceRange();
6722     return QualType();
6723   }
6724 
6725   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6726     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6727       << RHSType << RHS.get()->getSourceRange();
6728     return QualType();
6729   }
6730 
6731   // If both types are identical, no conversion is needed.
6732   if (LHSType == RHSType)
6733     return LHSType;
6734 
6735   // Now handle "real" floating types (i.e. float, double, long double).
6736   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6737     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6738                                  /*IsCompAssign = */ false);
6739 
6740   // Finally, we have two differing integer types.
6741   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6742   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6743 }
6744 
6745 /// Convert scalar operands to a vector that matches the
6746 ///        condition in length.
6747 ///
6748 /// Used when handling the OpenCL conditional operator where the
6749 /// condition is a vector while the other operands are scalar.
6750 ///
6751 /// We first compute the "result type" for the scalar operands
6752 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6753 /// into a vector of that type where the length matches the condition
6754 /// vector type. s6.11.6 requires that the element types of the result
6755 /// and the condition must have the same number of bits.
6756 static QualType
6757 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6758                               QualType CondTy, SourceLocation QuestionLoc) {
6759   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6760   if (ResTy.isNull()) return QualType();
6761 
6762   const VectorType *CV = CondTy->getAs<VectorType>();
6763   assert(CV);
6764 
6765   // Determine the vector result type
6766   unsigned NumElements = CV->getNumElements();
6767   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6768 
6769   // Ensure that all types have the same number of bits
6770   if (S.Context.getTypeSize(CV->getElementType())
6771       != S.Context.getTypeSize(ResTy)) {
6772     // Since VectorTy is created internally, it does not pretty print
6773     // with an OpenCL name. Instead, we just print a description.
6774     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6775     SmallString<64> Str;
6776     llvm::raw_svector_ostream OS(Str);
6777     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6778     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6779       << CondTy << OS.str();
6780     return QualType();
6781   }
6782 
6783   // Convert operands to the vector result type
6784   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6785   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6786 
6787   return VectorTy;
6788 }
6789 
6790 /// Return false if this is a valid OpenCL condition vector
6791 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6792                                        SourceLocation QuestionLoc) {
6793   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6794   // integral type.
6795   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6796   assert(CondTy);
6797   QualType EleTy = CondTy->getElementType();
6798   if (EleTy->isIntegerType()) return false;
6799 
6800   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6801     << Cond->getType() << Cond->getSourceRange();
6802   return true;
6803 }
6804 
6805 /// Return false if the vector condition type and the vector
6806 ///        result type are compatible.
6807 ///
6808 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6809 /// number of elements, and their element types have the same number
6810 /// of bits.
6811 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6812                               SourceLocation QuestionLoc) {
6813   const VectorType *CV = CondTy->getAs<VectorType>();
6814   const VectorType *RV = VecResTy->getAs<VectorType>();
6815   assert(CV && RV);
6816 
6817   if (CV->getNumElements() != RV->getNumElements()) {
6818     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6819       << CondTy << VecResTy;
6820     return true;
6821   }
6822 
6823   QualType CVE = CV->getElementType();
6824   QualType RVE = RV->getElementType();
6825 
6826   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6827     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6828       << CondTy << VecResTy;
6829     return true;
6830   }
6831 
6832   return false;
6833 }
6834 
6835 /// Return the resulting type for the conditional operator in
6836 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6837 ///        s6.3.i) when the condition is a vector type.
6838 static QualType
6839 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6840                              ExprResult &LHS, ExprResult &RHS,
6841                              SourceLocation QuestionLoc) {
6842   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6843   if (Cond.isInvalid())
6844     return QualType();
6845   QualType CondTy = Cond.get()->getType();
6846 
6847   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6848     return QualType();
6849 
6850   // If either operand is a vector then find the vector type of the
6851   // result as specified in OpenCL v1.1 s6.3.i.
6852   if (LHS.get()->getType()->isVectorType() ||
6853       RHS.get()->getType()->isVectorType()) {
6854     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6855                                               /*isCompAssign*/false,
6856                                               /*AllowBothBool*/true,
6857                                               /*AllowBoolConversions*/false);
6858     if (VecResTy.isNull()) return QualType();
6859     // The result type must match the condition type as specified in
6860     // OpenCL v1.1 s6.11.6.
6861     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6862       return QualType();
6863     return VecResTy;
6864   }
6865 
6866   // Both operands are scalar.
6867   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6868 }
6869 
6870 /// Return true if the Expr is block type
6871 static bool checkBlockType(Sema &S, const Expr *E) {
6872   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6873     QualType Ty = CE->getCallee()->getType();
6874     if (Ty->isBlockPointerType()) {
6875       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6876       return true;
6877     }
6878   }
6879   return false;
6880 }
6881 
6882 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6883 /// In that case, LHS = cond.
6884 /// C99 6.5.15
6885 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6886                                         ExprResult &RHS, ExprValueKind &VK,
6887                                         ExprObjectKind &OK,
6888                                         SourceLocation QuestionLoc) {
6889 
6890   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6891   if (!LHSResult.isUsable()) return QualType();
6892   LHS = LHSResult;
6893 
6894   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6895   if (!RHSResult.isUsable()) return QualType();
6896   RHS = RHSResult;
6897 
6898   // C++ is sufficiently different to merit its own checker.
6899   if (getLangOpts().CPlusPlus)
6900     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6901 
6902   VK = VK_RValue;
6903   OK = OK_Ordinary;
6904 
6905   // The OpenCL operator with a vector condition is sufficiently
6906   // different to merit its own checker.
6907   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6908     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6909 
6910   // First, check the condition.
6911   Cond = UsualUnaryConversions(Cond.get());
6912   if (Cond.isInvalid())
6913     return QualType();
6914   if (checkCondition(*this, Cond.get(), QuestionLoc))
6915     return QualType();
6916 
6917   // Now check the two expressions.
6918   if (LHS.get()->getType()->isVectorType() ||
6919       RHS.get()->getType()->isVectorType())
6920     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6921                                /*AllowBothBool*/true,
6922                                /*AllowBoolConversions*/false);
6923 
6924   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6925   if (LHS.isInvalid() || RHS.isInvalid())
6926     return QualType();
6927 
6928   QualType LHSTy = LHS.get()->getType();
6929   QualType RHSTy = RHS.get()->getType();
6930 
6931   // Diagnose attempts to convert between __float128 and long double where
6932   // such conversions currently can't be handled.
6933   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6934     Diag(QuestionLoc,
6935          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6936       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6937     return QualType();
6938   }
6939 
6940   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6941   // selection operator (?:).
6942   if (getLangOpts().OpenCL &&
6943       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6944     return QualType();
6945   }
6946 
6947   // If both operands have arithmetic type, do the usual arithmetic conversions
6948   // to find a common type: C99 6.5.15p3,5.
6949   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6950     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6951     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6952 
6953     return ResTy;
6954   }
6955 
6956   // If both operands are the same structure or union type, the result is that
6957   // type.
6958   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6959     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6960       if (LHSRT->getDecl() == RHSRT->getDecl())
6961         // "If both the operands have structure or union type, the result has
6962         // that type."  This implies that CV qualifiers are dropped.
6963         return LHSTy.getUnqualifiedType();
6964     // FIXME: Type of conditional expression must be complete in C mode.
6965   }
6966 
6967   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6968   // The following || allows only one side to be void (a GCC-ism).
6969   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6970     return checkConditionalVoidType(*this, LHS, RHS);
6971   }
6972 
6973   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6974   // the type of the other operand."
6975   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6976   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6977 
6978   // All objective-c pointer type analysis is done here.
6979   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6980                                                         QuestionLoc);
6981   if (LHS.isInvalid() || RHS.isInvalid())
6982     return QualType();
6983   if (!compositeType.isNull())
6984     return compositeType;
6985 
6986 
6987   // Handle block pointer types.
6988   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6989     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6990                                                      QuestionLoc);
6991 
6992   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6993   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6994     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6995                                                        QuestionLoc);
6996 
6997   // GCC compatibility: soften pointer/integer mismatch.  Note that
6998   // null pointers have been filtered out by this point.
6999   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7000       /*isIntFirstExpr=*/true))
7001     return RHSTy;
7002   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7003       /*isIntFirstExpr=*/false))
7004     return LHSTy;
7005 
7006   // Emit a better diagnostic if one of the expressions is a null pointer
7007   // constant and the other is not a pointer type. In this case, the user most
7008   // likely forgot to take the address of the other expression.
7009   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7010     return QualType();
7011 
7012   // Otherwise, the operands are not compatible.
7013   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7014     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7015     << RHS.get()->getSourceRange();
7016   return QualType();
7017 }
7018 
7019 /// FindCompositeObjCPointerType - Helper method to find composite type of
7020 /// two objective-c pointer types of the two input expressions.
7021 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7022                                             SourceLocation QuestionLoc) {
7023   QualType LHSTy = LHS.get()->getType();
7024   QualType RHSTy = RHS.get()->getType();
7025 
7026   // Handle things like Class and struct objc_class*.  Here we case the result
7027   // to the pseudo-builtin, because that will be implicitly cast back to the
7028   // redefinition type if an attempt is made to access its fields.
7029   if (LHSTy->isObjCClassType() &&
7030       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7031     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7032     return LHSTy;
7033   }
7034   if (RHSTy->isObjCClassType() &&
7035       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7036     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7037     return RHSTy;
7038   }
7039   // And the same for struct objc_object* / id
7040   if (LHSTy->isObjCIdType() &&
7041       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7042     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7043     return LHSTy;
7044   }
7045   if (RHSTy->isObjCIdType() &&
7046       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7047     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7048     return RHSTy;
7049   }
7050   // And the same for struct objc_selector* / SEL
7051   if (Context.isObjCSelType(LHSTy) &&
7052       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7053     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7054     return LHSTy;
7055   }
7056   if (Context.isObjCSelType(RHSTy) &&
7057       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7058     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7059     return RHSTy;
7060   }
7061   // Check constraints for Objective-C object pointers types.
7062   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7063 
7064     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7065       // Two identical object pointer types are always compatible.
7066       return LHSTy;
7067     }
7068     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7069     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7070     QualType compositeType = LHSTy;
7071 
7072     // If both operands are interfaces and either operand can be
7073     // assigned to the other, use that type as the composite
7074     // type. This allows
7075     //   xxx ? (A*) a : (B*) b
7076     // where B is a subclass of A.
7077     //
7078     // Additionally, as for assignment, if either type is 'id'
7079     // allow silent coercion. Finally, if the types are
7080     // incompatible then make sure to use 'id' as the composite
7081     // type so the result is acceptable for sending messages to.
7082 
7083     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7084     // It could return the composite type.
7085     if (!(compositeType =
7086           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7087       // Nothing more to do.
7088     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7089       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7090     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7091       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7092     } else if ((LHSTy->isObjCQualifiedIdType() ||
7093                 RHSTy->isObjCQualifiedIdType()) &&
7094                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7095       // Need to handle "id<xx>" explicitly.
7096       // GCC allows qualified id and any Objective-C type to devolve to
7097       // id. Currently localizing to here until clear this should be
7098       // part of ObjCQualifiedIdTypesAreCompatible.
7099       compositeType = Context.getObjCIdType();
7100     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7101       compositeType = Context.getObjCIdType();
7102     } else {
7103       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7104       << LHSTy << RHSTy
7105       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7106       QualType incompatTy = Context.getObjCIdType();
7107       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7108       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7109       return incompatTy;
7110     }
7111     // The object pointer types are compatible.
7112     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7113     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7114     return compositeType;
7115   }
7116   // Check Objective-C object pointer types and 'void *'
7117   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7118     if (getLangOpts().ObjCAutoRefCount) {
7119       // ARC forbids the implicit conversion of object pointers to 'void *',
7120       // so these types are not compatible.
7121       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7122           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7123       LHS = RHS = true;
7124       return QualType();
7125     }
7126     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7127     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7128     QualType destPointee
7129     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7130     QualType destType = Context.getPointerType(destPointee);
7131     // Add qualifiers if necessary.
7132     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7133     // Promote to void*.
7134     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7135     return destType;
7136   }
7137   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7138     if (getLangOpts().ObjCAutoRefCount) {
7139       // ARC forbids the implicit conversion of object pointers to 'void *',
7140       // so these types are not compatible.
7141       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7142           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7143       LHS = RHS = true;
7144       return QualType();
7145     }
7146     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7147     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7148     QualType destPointee
7149     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7150     QualType destType = Context.getPointerType(destPointee);
7151     // Add qualifiers if necessary.
7152     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7153     // Promote to void*.
7154     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7155     return destType;
7156   }
7157   return QualType();
7158 }
7159 
7160 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7161 /// ParenRange in parentheses.
7162 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7163                                const PartialDiagnostic &Note,
7164                                SourceRange ParenRange) {
7165   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7166   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7167       EndLoc.isValid()) {
7168     Self.Diag(Loc, Note)
7169       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7170       << FixItHint::CreateInsertion(EndLoc, ")");
7171   } else {
7172     // We can't display the parentheses, so just show the bare note.
7173     Self.Diag(Loc, Note) << ParenRange;
7174   }
7175 }
7176 
7177 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7178   return BinaryOperator::isAdditiveOp(Opc) ||
7179          BinaryOperator::isMultiplicativeOp(Opc) ||
7180          BinaryOperator::isShiftOp(Opc);
7181 }
7182 
7183 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7184 /// expression, either using a built-in or overloaded operator,
7185 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7186 /// expression.
7187 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7188                                    Expr **RHSExprs) {
7189   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7190   E = E->IgnoreImpCasts();
7191   E = E->IgnoreConversionOperator();
7192   E = E->IgnoreImpCasts();
7193   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7194     E = MTE->GetTemporaryExpr();
7195     E = E->IgnoreImpCasts();
7196   }
7197 
7198   // Built-in binary operator.
7199   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7200     if (IsArithmeticOp(OP->getOpcode())) {
7201       *Opcode = OP->getOpcode();
7202       *RHSExprs = OP->getRHS();
7203       return true;
7204     }
7205   }
7206 
7207   // Overloaded operator.
7208   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7209     if (Call->getNumArgs() != 2)
7210       return false;
7211 
7212     // Make sure this is really a binary operator that is safe to pass into
7213     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7214     OverloadedOperatorKind OO = Call->getOperator();
7215     if (OO < OO_Plus || OO > OO_Arrow ||
7216         OO == OO_PlusPlus || OO == OO_MinusMinus)
7217       return false;
7218 
7219     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7220     if (IsArithmeticOp(OpKind)) {
7221       *Opcode = OpKind;
7222       *RHSExprs = Call->getArg(1);
7223       return true;
7224     }
7225   }
7226 
7227   return false;
7228 }
7229 
7230 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7231 /// or is a logical expression such as (x==y) which has int type, but is
7232 /// commonly interpreted as boolean.
7233 static bool ExprLooksBoolean(Expr *E) {
7234   E = E->IgnoreParenImpCasts();
7235 
7236   if (E->getType()->isBooleanType())
7237     return true;
7238   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7239     return OP->isComparisonOp() || OP->isLogicalOp();
7240   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7241     return OP->getOpcode() == UO_LNot;
7242   if (E->getType()->isPointerType())
7243     return true;
7244   // FIXME: What about overloaded operator calls returning "unspecified boolean
7245   // type"s (commonly pointer-to-members)?
7246 
7247   return false;
7248 }
7249 
7250 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7251 /// and binary operator are mixed in a way that suggests the programmer assumed
7252 /// the conditional operator has higher precedence, for example:
7253 /// "int x = a + someBinaryCondition ? 1 : 2".
7254 static void DiagnoseConditionalPrecedence(Sema &Self,
7255                                           SourceLocation OpLoc,
7256                                           Expr *Condition,
7257                                           Expr *LHSExpr,
7258                                           Expr *RHSExpr) {
7259   BinaryOperatorKind CondOpcode;
7260   Expr *CondRHS;
7261 
7262   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7263     return;
7264   if (!ExprLooksBoolean(CondRHS))
7265     return;
7266 
7267   // The condition is an arithmetic binary expression, with a right-
7268   // hand side that looks boolean, so warn.
7269 
7270   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7271       << Condition->getSourceRange()
7272       << BinaryOperator::getOpcodeStr(CondOpcode);
7273 
7274   SuggestParentheses(
7275       Self, OpLoc,
7276       Self.PDiag(diag::note_precedence_silence)
7277           << BinaryOperator::getOpcodeStr(CondOpcode),
7278       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7279 
7280   SuggestParentheses(Self, OpLoc,
7281                      Self.PDiag(diag::note_precedence_conditional_first),
7282                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7283 }
7284 
7285 /// Compute the nullability of a conditional expression.
7286 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7287                                               QualType LHSTy, QualType RHSTy,
7288                                               ASTContext &Ctx) {
7289   if (!ResTy->isAnyPointerType())
7290     return ResTy;
7291 
7292   auto GetNullability = [&Ctx](QualType Ty) {
7293     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7294     if (Kind)
7295       return *Kind;
7296     return NullabilityKind::Unspecified;
7297   };
7298 
7299   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7300   NullabilityKind MergedKind;
7301 
7302   // Compute nullability of a binary conditional expression.
7303   if (IsBin) {
7304     if (LHSKind == NullabilityKind::NonNull)
7305       MergedKind = NullabilityKind::NonNull;
7306     else
7307       MergedKind = RHSKind;
7308   // Compute nullability of a normal conditional expression.
7309   } else {
7310     if (LHSKind == NullabilityKind::Nullable ||
7311         RHSKind == NullabilityKind::Nullable)
7312       MergedKind = NullabilityKind::Nullable;
7313     else if (LHSKind == NullabilityKind::NonNull)
7314       MergedKind = RHSKind;
7315     else if (RHSKind == NullabilityKind::NonNull)
7316       MergedKind = LHSKind;
7317     else
7318       MergedKind = NullabilityKind::Unspecified;
7319   }
7320 
7321   // Return if ResTy already has the correct nullability.
7322   if (GetNullability(ResTy) == MergedKind)
7323     return ResTy;
7324 
7325   // Strip all nullability from ResTy.
7326   while (ResTy->getNullability(Ctx))
7327     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7328 
7329   // Create a new AttributedType with the new nullability kind.
7330   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7331   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7332 }
7333 
7334 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7335 /// in the case of a the GNU conditional expr extension.
7336 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7337                                     SourceLocation ColonLoc,
7338                                     Expr *CondExpr, Expr *LHSExpr,
7339                                     Expr *RHSExpr) {
7340   if (!getLangOpts().CPlusPlus) {
7341     // C cannot handle TypoExpr nodes in the condition because it
7342     // doesn't handle dependent types properly, so make sure any TypoExprs have
7343     // been dealt with before checking the operands.
7344     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7345     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7346     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7347 
7348     if (!CondResult.isUsable())
7349       return ExprError();
7350 
7351     if (LHSExpr) {
7352       if (!LHSResult.isUsable())
7353         return ExprError();
7354     }
7355 
7356     if (!RHSResult.isUsable())
7357       return ExprError();
7358 
7359     CondExpr = CondResult.get();
7360     LHSExpr = LHSResult.get();
7361     RHSExpr = RHSResult.get();
7362   }
7363 
7364   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7365   // was the condition.
7366   OpaqueValueExpr *opaqueValue = nullptr;
7367   Expr *commonExpr = nullptr;
7368   if (!LHSExpr) {
7369     commonExpr = CondExpr;
7370     // Lower out placeholder types first.  This is important so that we don't
7371     // try to capture a placeholder. This happens in few cases in C++; such
7372     // as Objective-C++'s dictionary subscripting syntax.
7373     if (commonExpr->hasPlaceholderType()) {
7374       ExprResult result = CheckPlaceholderExpr(commonExpr);
7375       if (!result.isUsable()) return ExprError();
7376       commonExpr = result.get();
7377     }
7378     // We usually want to apply unary conversions *before* saving, except
7379     // in the special case of a C++ l-value conditional.
7380     if (!(getLangOpts().CPlusPlus
7381           && !commonExpr->isTypeDependent()
7382           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7383           && commonExpr->isGLValue()
7384           && commonExpr->isOrdinaryOrBitFieldObject()
7385           && RHSExpr->isOrdinaryOrBitFieldObject()
7386           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7387       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7388       if (commonRes.isInvalid())
7389         return ExprError();
7390       commonExpr = commonRes.get();
7391     }
7392 
7393     // If the common expression is a class or array prvalue, materialize it
7394     // so that we can safely refer to it multiple times.
7395     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7396                                    commonExpr->getType()->isArrayType())) {
7397       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7398       if (MatExpr.isInvalid())
7399         return ExprError();
7400       commonExpr = MatExpr.get();
7401     }
7402 
7403     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7404                                                 commonExpr->getType(),
7405                                                 commonExpr->getValueKind(),
7406                                                 commonExpr->getObjectKind(),
7407                                                 commonExpr);
7408     LHSExpr = CondExpr = opaqueValue;
7409   }
7410 
7411   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7412   ExprValueKind VK = VK_RValue;
7413   ExprObjectKind OK = OK_Ordinary;
7414   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7415   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7416                                              VK, OK, QuestionLoc);
7417   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7418       RHS.isInvalid())
7419     return ExprError();
7420 
7421   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7422                                 RHS.get());
7423 
7424   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7425 
7426   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7427                                          Context);
7428 
7429   if (!commonExpr)
7430     return new (Context)
7431         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7432                             RHS.get(), result, VK, OK);
7433 
7434   return new (Context) BinaryConditionalOperator(
7435       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7436       ColonLoc, result, VK, OK);
7437 }
7438 
7439 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7440 // being closely modeled after the C99 spec:-). The odd characteristic of this
7441 // routine is it effectively iqnores the qualifiers on the top level pointee.
7442 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7443 // FIXME: add a couple examples in this comment.
7444 static Sema::AssignConvertType
7445 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7446   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7447   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7448 
7449   // get the "pointed to" type (ignoring qualifiers at the top level)
7450   const Type *lhptee, *rhptee;
7451   Qualifiers lhq, rhq;
7452   std::tie(lhptee, lhq) =
7453       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7454   std::tie(rhptee, rhq) =
7455       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7456 
7457   Sema::AssignConvertType ConvTy = Sema::Compatible;
7458 
7459   // C99 6.5.16.1p1: This following citation is common to constraints
7460   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7461   // qualifiers of the type *pointed to* by the right;
7462 
7463   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7464   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7465       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7466     // Ignore lifetime for further calculation.
7467     lhq.removeObjCLifetime();
7468     rhq.removeObjCLifetime();
7469   }
7470 
7471   if (!lhq.compatiblyIncludes(rhq)) {
7472     // Treat address-space mismatches as fatal.  TODO: address subspaces
7473     if (!lhq.isAddressSpaceSupersetOf(rhq))
7474       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7475 
7476     // It's okay to add or remove GC or lifetime qualifiers when converting to
7477     // and from void*.
7478     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7479                         .compatiblyIncludes(
7480                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7481              && (lhptee->isVoidType() || rhptee->isVoidType()))
7482       ; // keep old
7483 
7484     // Treat lifetime mismatches as fatal.
7485     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7486       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7487 
7488     // For GCC/MS compatibility, other qualifier mismatches are treated
7489     // as still compatible in C.
7490     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7491   }
7492 
7493   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7494   // incomplete type and the other is a pointer to a qualified or unqualified
7495   // version of void...
7496   if (lhptee->isVoidType()) {
7497     if (rhptee->isIncompleteOrObjectType())
7498       return ConvTy;
7499 
7500     // As an extension, we allow cast to/from void* to function pointer.
7501     assert(rhptee->isFunctionType());
7502     return Sema::FunctionVoidPointer;
7503   }
7504 
7505   if (rhptee->isVoidType()) {
7506     if (lhptee->isIncompleteOrObjectType())
7507       return ConvTy;
7508 
7509     // As an extension, we allow cast to/from void* to function pointer.
7510     assert(lhptee->isFunctionType());
7511     return Sema::FunctionVoidPointer;
7512   }
7513 
7514   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7515   // unqualified versions of compatible types, ...
7516   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7517   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7518     // Check if the pointee types are compatible ignoring the sign.
7519     // We explicitly check for char so that we catch "char" vs
7520     // "unsigned char" on systems where "char" is unsigned.
7521     if (lhptee->isCharType())
7522       ltrans = S.Context.UnsignedCharTy;
7523     else if (lhptee->hasSignedIntegerRepresentation())
7524       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7525 
7526     if (rhptee->isCharType())
7527       rtrans = S.Context.UnsignedCharTy;
7528     else if (rhptee->hasSignedIntegerRepresentation())
7529       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7530 
7531     if (ltrans == rtrans) {
7532       // Types are compatible ignoring the sign. Qualifier incompatibility
7533       // takes priority over sign incompatibility because the sign
7534       // warning can be disabled.
7535       if (ConvTy != Sema::Compatible)
7536         return ConvTy;
7537 
7538       return Sema::IncompatiblePointerSign;
7539     }
7540 
7541     // If we are a multi-level pointer, it's possible that our issue is simply
7542     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7543     // the eventual target type is the same and the pointers have the same
7544     // level of indirection, this must be the issue.
7545     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7546       do {
7547         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7548         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7549       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7550 
7551       if (lhptee == rhptee)
7552         return Sema::IncompatibleNestedPointerQualifiers;
7553     }
7554 
7555     // General pointer incompatibility takes priority over qualifiers.
7556     return Sema::IncompatiblePointer;
7557   }
7558   if (!S.getLangOpts().CPlusPlus &&
7559       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7560     return Sema::IncompatiblePointer;
7561   return ConvTy;
7562 }
7563 
7564 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7565 /// block pointer types are compatible or whether a block and normal pointer
7566 /// are compatible. It is more restrict than comparing two function pointer
7567 // types.
7568 static Sema::AssignConvertType
7569 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7570                                     QualType RHSType) {
7571   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7572   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7573 
7574   QualType lhptee, rhptee;
7575 
7576   // get the "pointed to" type (ignoring qualifiers at the top level)
7577   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7578   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7579 
7580   // In C++, the types have to match exactly.
7581   if (S.getLangOpts().CPlusPlus)
7582     return Sema::IncompatibleBlockPointer;
7583 
7584   Sema::AssignConvertType ConvTy = Sema::Compatible;
7585 
7586   // For blocks we enforce that qualifiers are identical.
7587   Qualifiers LQuals = lhptee.getLocalQualifiers();
7588   Qualifiers RQuals = rhptee.getLocalQualifiers();
7589   if (S.getLangOpts().OpenCL) {
7590     LQuals.removeAddressSpace();
7591     RQuals.removeAddressSpace();
7592   }
7593   if (LQuals != RQuals)
7594     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7595 
7596   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7597   // assignment.
7598   // The current behavior is similar to C++ lambdas. A block might be
7599   // assigned to a variable iff its return type and parameters are compatible
7600   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7601   // an assignment. Presumably it should behave in way that a function pointer
7602   // assignment does in C, so for each parameter and return type:
7603   //  * CVR and address space of LHS should be a superset of CVR and address
7604   //  space of RHS.
7605   //  * unqualified types should be compatible.
7606   if (S.getLangOpts().OpenCL) {
7607     if (!S.Context.typesAreBlockPointerCompatible(
7608             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7609             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7610       return Sema::IncompatibleBlockPointer;
7611   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7612     return Sema::IncompatibleBlockPointer;
7613 
7614   return ConvTy;
7615 }
7616 
7617 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7618 /// for assignment compatibility.
7619 static Sema::AssignConvertType
7620 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7621                                    QualType RHSType) {
7622   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7623   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7624 
7625   if (LHSType->isObjCBuiltinType()) {
7626     // Class is not compatible with ObjC object pointers.
7627     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7628         !RHSType->isObjCQualifiedClassType())
7629       return Sema::IncompatiblePointer;
7630     return Sema::Compatible;
7631   }
7632   if (RHSType->isObjCBuiltinType()) {
7633     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7634         !LHSType->isObjCQualifiedClassType())
7635       return Sema::IncompatiblePointer;
7636     return Sema::Compatible;
7637   }
7638   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7639   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7640 
7641   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7642       // make an exception for id<P>
7643       !LHSType->isObjCQualifiedIdType())
7644     return Sema::CompatiblePointerDiscardsQualifiers;
7645 
7646   if (S.Context.typesAreCompatible(LHSType, RHSType))
7647     return Sema::Compatible;
7648   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7649     return Sema::IncompatibleObjCQualifiedId;
7650   return Sema::IncompatiblePointer;
7651 }
7652 
7653 Sema::AssignConvertType
7654 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7655                                  QualType LHSType, QualType RHSType) {
7656   // Fake up an opaque expression.  We don't actually care about what
7657   // cast operations are required, so if CheckAssignmentConstraints
7658   // adds casts to this they'll be wasted, but fortunately that doesn't
7659   // usually happen on valid code.
7660   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7661   ExprResult RHSPtr = &RHSExpr;
7662   CastKind K;
7663 
7664   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7665 }
7666 
7667 /// This helper function returns true if QT is a vector type that has element
7668 /// type ElementType.
7669 static bool isVector(QualType QT, QualType ElementType) {
7670   if (const VectorType *VT = QT->getAs<VectorType>())
7671     return VT->getElementType() == ElementType;
7672   return false;
7673 }
7674 
7675 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7676 /// has code to accommodate several GCC extensions when type checking
7677 /// pointers. Here are some objectionable examples that GCC considers warnings:
7678 ///
7679 ///  int a, *pint;
7680 ///  short *pshort;
7681 ///  struct foo *pfoo;
7682 ///
7683 ///  pint = pshort; // warning: assignment from incompatible pointer type
7684 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7685 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7686 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7687 ///
7688 /// As a result, the code for dealing with pointers is more complex than the
7689 /// C99 spec dictates.
7690 ///
7691 /// Sets 'Kind' for any result kind except Incompatible.
7692 Sema::AssignConvertType
7693 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7694                                  CastKind &Kind, bool ConvertRHS) {
7695   QualType RHSType = RHS.get()->getType();
7696   QualType OrigLHSType = LHSType;
7697 
7698   // Get canonical types.  We're not formatting these types, just comparing
7699   // them.
7700   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7701   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7702 
7703   // Common case: no conversion required.
7704   if (LHSType == RHSType) {
7705     Kind = CK_NoOp;
7706     return Compatible;
7707   }
7708 
7709   // If we have an atomic type, try a non-atomic assignment, then just add an
7710   // atomic qualification step.
7711   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7712     Sema::AssignConvertType result =
7713       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7714     if (result != Compatible)
7715       return result;
7716     if (Kind != CK_NoOp && ConvertRHS)
7717       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7718     Kind = CK_NonAtomicToAtomic;
7719     return Compatible;
7720   }
7721 
7722   // If the left-hand side is a reference type, then we are in a
7723   // (rare!) case where we've allowed the use of references in C,
7724   // e.g., as a parameter type in a built-in function. In this case,
7725   // just make sure that the type referenced is compatible with the
7726   // right-hand side type. The caller is responsible for adjusting
7727   // LHSType so that the resulting expression does not have reference
7728   // type.
7729   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7730     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7731       Kind = CK_LValueBitCast;
7732       return Compatible;
7733     }
7734     return Incompatible;
7735   }
7736 
7737   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7738   // to the same ExtVector type.
7739   if (LHSType->isExtVectorType()) {
7740     if (RHSType->isExtVectorType())
7741       return Incompatible;
7742     if (RHSType->isArithmeticType()) {
7743       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7744       if (ConvertRHS)
7745         RHS = prepareVectorSplat(LHSType, RHS.get());
7746       Kind = CK_VectorSplat;
7747       return Compatible;
7748     }
7749   }
7750 
7751   // Conversions to or from vector type.
7752   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7753     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7754       // Allow assignments of an AltiVec vector type to an equivalent GCC
7755       // vector type and vice versa
7756       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7757         Kind = CK_BitCast;
7758         return Compatible;
7759       }
7760 
7761       // If we are allowing lax vector conversions, and LHS and RHS are both
7762       // vectors, the total size only needs to be the same. This is a bitcast;
7763       // no bits are changed but the result type is different.
7764       if (isLaxVectorConversion(RHSType, LHSType)) {
7765         Kind = CK_BitCast;
7766         return IncompatibleVectors;
7767       }
7768     }
7769 
7770     // When the RHS comes from another lax conversion (e.g. binops between
7771     // scalars and vectors) the result is canonicalized as a vector. When the
7772     // LHS is also a vector, the lax is allowed by the condition above. Handle
7773     // the case where LHS is a scalar.
7774     if (LHSType->isScalarType()) {
7775       const VectorType *VecType = RHSType->getAs<VectorType>();
7776       if (VecType && VecType->getNumElements() == 1 &&
7777           isLaxVectorConversion(RHSType, LHSType)) {
7778         ExprResult *VecExpr = &RHS;
7779         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7780         Kind = CK_BitCast;
7781         return Compatible;
7782       }
7783     }
7784 
7785     return Incompatible;
7786   }
7787 
7788   // Diagnose attempts to convert between __float128 and long double where
7789   // such conversions currently can't be handled.
7790   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7791     return Incompatible;
7792 
7793   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7794   // discards the imaginary part.
7795   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7796       !LHSType->getAs<ComplexType>())
7797     return Incompatible;
7798 
7799   // Arithmetic conversions.
7800   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7801       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7802     if (ConvertRHS)
7803       Kind = PrepareScalarCast(RHS, LHSType);
7804     return Compatible;
7805   }
7806 
7807   // Conversions to normal pointers.
7808   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7809     // U* -> T*
7810     if (isa<PointerType>(RHSType)) {
7811       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7812       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7813       if (AddrSpaceL != AddrSpaceR)
7814         Kind = CK_AddressSpaceConversion;
7815       else if (Context.hasCvrSimilarType(RHSType, LHSType))
7816         Kind = CK_NoOp;
7817       else
7818         Kind = CK_BitCast;
7819       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7820     }
7821 
7822     // int -> T*
7823     if (RHSType->isIntegerType()) {
7824       Kind = CK_IntegralToPointer; // FIXME: null?
7825       return IntToPointer;
7826     }
7827 
7828     // C pointers are not compatible with ObjC object pointers,
7829     // with two exceptions:
7830     if (isa<ObjCObjectPointerType>(RHSType)) {
7831       //  - conversions to void*
7832       if (LHSPointer->getPointeeType()->isVoidType()) {
7833         Kind = CK_BitCast;
7834         return Compatible;
7835       }
7836 
7837       //  - conversions from 'Class' to the redefinition type
7838       if (RHSType->isObjCClassType() &&
7839           Context.hasSameType(LHSType,
7840                               Context.getObjCClassRedefinitionType())) {
7841         Kind = CK_BitCast;
7842         return Compatible;
7843       }
7844 
7845       Kind = CK_BitCast;
7846       return IncompatiblePointer;
7847     }
7848 
7849     // U^ -> void*
7850     if (RHSType->getAs<BlockPointerType>()) {
7851       if (LHSPointer->getPointeeType()->isVoidType()) {
7852         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7853         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7854                                 ->getPointeeType()
7855                                 .getAddressSpace();
7856         Kind =
7857             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7858         return Compatible;
7859       }
7860     }
7861 
7862     return Incompatible;
7863   }
7864 
7865   // Conversions to block pointers.
7866   if (isa<BlockPointerType>(LHSType)) {
7867     // U^ -> T^
7868     if (RHSType->isBlockPointerType()) {
7869       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7870                               ->getPointeeType()
7871                               .getAddressSpace();
7872       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7873                               ->getPointeeType()
7874                               .getAddressSpace();
7875       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7876       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7877     }
7878 
7879     // int or null -> T^
7880     if (RHSType->isIntegerType()) {
7881       Kind = CK_IntegralToPointer; // FIXME: null
7882       return IntToBlockPointer;
7883     }
7884 
7885     // id -> T^
7886     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7887       Kind = CK_AnyPointerToBlockPointerCast;
7888       return Compatible;
7889     }
7890 
7891     // void* -> T^
7892     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7893       if (RHSPT->getPointeeType()->isVoidType()) {
7894         Kind = CK_AnyPointerToBlockPointerCast;
7895         return Compatible;
7896       }
7897 
7898     return Incompatible;
7899   }
7900 
7901   // Conversions to Objective-C pointers.
7902   if (isa<ObjCObjectPointerType>(LHSType)) {
7903     // A* -> B*
7904     if (RHSType->isObjCObjectPointerType()) {
7905       Kind = CK_BitCast;
7906       Sema::AssignConvertType result =
7907         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7908       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7909           result == Compatible &&
7910           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7911         result = IncompatibleObjCWeakRef;
7912       return result;
7913     }
7914 
7915     // int or null -> A*
7916     if (RHSType->isIntegerType()) {
7917       Kind = CK_IntegralToPointer; // FIXME: null
7918       return IntToPointer;
7919     }
7920 
7921     // In general, C pointers are not compatible with ObjC object pointers,
7922     // with two exceptions:
7923     if (isa<PointerType>(RHSType)) {
7924       Kind = CK_CPointerToObjCPointerCast;
7925 
7926       //  - conversions from 'void*'
7927       if (RHSType->isVoidPointerType()) {
7928         return Compatible;
7929       }
7930 
7931       //  - conversions to 'Class' from its redefinition type
7932       if (LHSType->isObjCClassType() &&
7933           Context.hasSameType(RHSType,
7934                               Context.getObjCClassRedefinitionType())) {
7935         return Compatible;
7936       }
7937 
7938       return IncompatiblePointer;
7939     }
7940 
7941     // Only under strict condition T^ is compatible with an Objective-C pointer.
7942     if (RHSType->isBlockPointerType() &&
7943         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7944       if (ConvertRHS)
7945         maybeExtendBlockObject(RHS);
7946       Kind = CK_BlockPointerToObjCPointerCast;
7947       return Compatible;
7948     }
7949 
7950     return Incompatible;
7951   }
7952 
7953   // Conversions from pointers that are not covered by the above.
7954   if (isa<PointerType>(RHSType)) {
7955     // T* -> _Bool
7956     if (LHSType == Context.BoolTy) {
7957       Kind = CK_PointerToBoolean;
7958       return Compatible;
7959     }
7960 
7961     // T* -> int
7962     if (LHSType->isIntegerType()) {
7963       Kind = CK_PointerToIntegral;
7964       return PointerToInt;
7965     }
7966 
7967     return Incompatible;
7968   }
7969 
7970   // Conversions from Objective-C pointers that are not covered by the above.
7971   if (isa<ObjCObjectPointerType>(RHSType)) {
7972     // T* -> _Bool
7973     if (LHSType == Context.BoolTy) {
7974       Kind = CK_PointerToBoolean;
7975       return Compatible;
7976     }
7977 
7978     // T* -> int
7979     if (LHSType->isIntegerType()) {
7980       Kind = CK_PointerToIntegral;
7981       return PointerToInt;
7982     }
7983 
7984     return Incompatible;
7985   }
7986 
7987   // struct A -> struct B
7988   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7989     if (Context.typesAreCompatible(LHSType, RHSType)) {
7990       Kind = CK_NoOp;
7991       return Compatible;
7992     }
7993   }
7994 
7995   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7996     Kind = CK_IntToOCLSampler;
7997     return Compatible;
7998   }
7999 
8000   return Incompatible;
8001 }
8002 
8003 /// Constructs a transparent union from an expression that is
8004 /// used to initialize the transparent union.
8005 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8006                                       ExprResult &EResult, QualType UnionType,
8007                                       FieldDecl *Field) {
8008   // Build an initializer list that designates the appropriate member
8009   // of the transparent union.
8010   Expr *E = EResult.get();
8011   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8012                                                    E, SourceLocation());
8013   Initializer->setType(UnionType);
8014   Initializer->setInitializedFieldInUnion(Field);
8015 
8016   // Build a compound literal constructing a value of the transparent
8017   // union type from this initializer list.
8018   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8019   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8020                                         VK_RValue, Initializer, false);
8021 }
8022 
8023 Sema::AssignConvertType
8024 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8025                                                ExprResult &RHS) {
8026   QualType RHSType = RHS.get()->getType();
8027 
8028   // If the ArgType is a Union type, we want to handle a potential
8029   // transparent_union GCC extension.
8030   const RecordType *UT = ArgType->getAsUnionType();
8031   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8032     return Incompatible;
8033 
8034   // The field to initialize within the transparent union.
8035   RecordDecl *UD = UT->getDecl();
8036   FieldDecl *InitField = nullptr;
8037   // It's compatible if the expression matches any of the fields.
8038   for (auto *it : UD->fields()) {
8039     if (it->getType()->isPointerType()) {
8040       // If the transparent union contains a pointer type, we allow:
8041       // 1) void pointer
8042       // 2) null pointer constant
8043       if (RHSType->isPointerType())
8044         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8045           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8046           InitField = it;
8047           break;
8048         }
8049 
8050       if (RHS.get()->isNullPointerConstant(Context,
8051                                            Expr::NPC_ValueDependentIsNull)) {
8052         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8053                                 CK_NullToPointer);
8054         InitField = it;
8055         break;
8056       }
8057     }
8058 
8059     CastKind Kind;
8060     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8061           == Compatible) {
8062       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8063       InitField = it;
8064       break;
8065     }
8066   }
8067 
8068   if (!InitField)
8069     return Incompatible;
8070 
8071   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8072   return Compatible;
8073 }
8074 
8075 Sema::AssignConvertType
8076 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8077                                        bool Diagnose,
8078                                        bool DiagnoseCFAudited,
8079                                        bool ConvertRHS) {
8080   // We need to be able to tell the caller whether we diagnosed a problem, if
8081   // they ask us to issue diagnostics.
8082   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8083 
8084   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8085   // we can't avoid *all* modifications at the moment, so we need some somewhere
8086   // to put the updated value.
8087   ExprResult LocalRHS = CallerRHS;
8088   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8089 
8090   if (getLangOpts().CPlusPlus) {
8091     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8092       // C++ 5.17p3: If the left operand is not of class type, the
8093       // expression is implicitly converted (C++ 4) to the
8094       // cv-unqualified type of the left operand.
8095       QualType RHSType = RHS.get()->getType();
8096       if (Diagnose) {
8097         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8098                                         AA_Assigning);
8099       } else {
8100         ImplicitConversionSequence ICS =
8101             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8102                                   /*SuppressUserConversions=*/false,
8103                                   /*AllowExplicit=*/false,
8104                                   /*InOverloadResolution=*/false,
8105                                   /*CStyle=*/false,
8106                                   /*AllowObjCWritebackConversion=*/false);
8107         if (ICS.isFailure())
8108           return Incompatible;
8109         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8110                                         ICS, AA_Assigning);
8111       }
8112       if (RHS.isInvalid())
8113         return Incompatible;
8114       Sema::AssignConvertType result = Compatible;
8115       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8116           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8117         result = IncompatibleObjCWeakRef;
8118       return result;
8119     }
8120 
8121     // FIXME: Currently, we fall through and treat C++ classes like C
8122     // structures.
8123     // FIXME: We also fall through for atomics; not sure what should
8124     // happen there, though.
8125   } else if (RHS.get()->getType() == Context.OverloadTy) {
8126     // As a set of extensions to C, we support overloading on functions. These
8127     // functions need to be resolved here.
8128     DeclAccessPair DAP;
8129     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8130             RHS.get(), LHSType, /*Complain=*/false, DAP))
8131       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8132     else
8133       return Incompatible;
8134   }
8135 
8136   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8137   // a null pointer constant.
8138   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8139        LHSType->isBlockPointerType()) &&
8140       RHS.get()->isNullPointerConstant(Context,
8141                                        Expr::NPC_ValueDependentIsNull)) {
8142     if (Diagnose || ConvertRHS) {
8143       CastKind Kind;
8144       CXXCastPath Path;
8145       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8146                              /*IgnoreBaseAccess=*/false, Diagnose);
8147       if (ConvertRHS)
8148         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8149     }
8150     return Compatible;
8151   }
8152 
8153   // OpenCL queue_t type assignment.
8154   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8155                                  Context, Expr::NPC_ValueDependentIsNull)) {
8156     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8157     return Compatible;
8158   }
8159 
8160   // This check seems unnatural, however it is necessary to ensure the proper
8161   // conversion of functions/arrays. If the conversion were done for all
8162   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8163   // expressions that suppress this implicit conversion (&, sizeof).
8164   //
8165   // Suppress this for references: C++ 8.5.3p5.
8166   if (!LHSType->isReferenceType()) {
8167     // FIXME: We potentially allocate here even if ConvertRHS is false.
8168     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8169     if (RHS.isInvalid())
8170       return Incompatible;
8171   }
8172   CastKind Kind;
8173   Sema::AssignConvertType result =
8174     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8175 
8176   // C99 6.5.16.1p2: The value of the right operand is converted to the
8177   // type of the assignment expression.
8178   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8179   // so that we can use references in built-in functions even in C.
8180   // The getNonReferenceType() call makes sure that the resulting expression
8181   // does not have reference type.
8182   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8183     QualType Ty = LHSType.getNonLValueExprType(Context);
8184     Expr *E = RHS.get();
8185 
8186     // Check for various Objective-C errors. If we are not reporting
8187     // diagnostics and just checking for errors, e.g., during overload
8188     // resolution, return Incompatible to indicate the failure.
8189     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8190         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8191                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8192       if (!Diagnose)
8193         return Incompatible;
8194     }
8195     if (getLangOpts().ObjC1 &&
8196         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8197                                            E->getType(), E, Diagnose) ||
8198          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8199       if (!Diagnose)
8200         return Incompatible;
8201       // Replace the expression with a corrected version and continue so we
8202       // can find further errors.
8203       RHS = E;
8204       return Compatible;
8205     }
8206 
8207     if (ConvertRHS)
8208       RHS = ImpCastExprToType(E, Ty, Kind);
8209   }
8210   return result;
8211 }
8212 
8213 namespace {
8214 /// The original operand to an operator, prior to the application of the usual
8215 /// arithmetic conversions and converting the arguments of a builtin operator
8216 /// candidate.
8217 struct OriginalOperand {
8218   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8219     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8220       Op = MTE->GetTemporaryExpr();
8221     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8222       Op = BTE->getSubExpr();
8223     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8224       Orig = ICE->getSubExprAsWritten();
8225       Conversion = ICE->getConversionFunction();
8226     }
8227   }
8228 
8229   QualType getType() const { return Orig->getType(); }
8230 
8231   Expr *Orig;
8232   NamedDecl *Conversion;
8233 };
8234 }
8235 
8236 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8237                                ExprResult &RHS) {
8238   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8239 
8240   Diag(Loc, diag::err_typecheck_invalid_operands)
8241     << OrigLHS.getType() << OrigRHS.getType()
8242     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8243 
8244   // If a user-defined conversion was applied to either of the operands prior
8245   // to applying the built-in operator rules, tell the user about it.
8246   if (OrigLHS.Conversion) {
8247     Diag(OrigLHS.Conversion->getLocation(),
8248          diag::note_typecheck_invalid_operands_converted)
8249       << 0 << LHS.get()->getType();
8250   }
8251   if (OrigRHS.Conversion) {
8252     Diag(OrigRHS.Conversion->getLocation(),
8253          diag::note_typecheck_invalid_operands_converted)
8254       << 1 << RHS.get()->getType();
8255   }
8256 
8257   return QualType();
8258 }
8259 
8260 // Diagnose cases where a scalar was implicitly converted to a vector and
8261 // diagnose the underlying types. Otherwise, diagnose the error
8262 // as invalid vector logical operands for non-C++ cases.
8263 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8264                                             ExprResult &RHS) {
8265   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8266   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8267 
8268   bool LHSNatVec = LHSType->isVectorType();
8269   bool RHSNatVec = RHSType->isVectorType();
8270 
8271   if (!(LHSNatVec && RHSNatVec)) {
8272     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8273     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8274     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8275         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8276         << Vector->getSourceRange();
8277     return QualType();
8278   }
8279 
8280   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8281       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8282       << RHS.get()->getSourceRange();
8283 
8284   return QualType();
8285 }
8286 
8287 /// Try to convert a value of non-vector type to a vector type by converting
8288 /// the type to the element type of the vector and then performing a splat.
8289 /// If the language is OpenCL, we only use conversions that promote scalar
8290 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8291 /// for float->int.
8292 ///
8293 /// OpenCL V2.0 6.2.6.p2:
8294 /// An error shall occur if any scalar operand type has greater rank
8295 /// than the type of the vector element.
8296 ///
8297 /// \param scalar - if non-null, actually perform the conversions
8298 /// \return true if the operation fails (but without diagnosing the failure)
8299 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8300                                      QualType scalarTy,
8301                                      QualType vectorEltTy,
8302                                      QualType vectorTy,
8303                                      unsigned &DiagID) {
8304   // The conversion to apply to the scalar before splatting it,
8305   // if necessary.
8306   CastKind scalarCast = CK_NoOp;
8307 
8308   if (vectorEltTy->isIntegralType(S.Context)) {
8309     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8310         (scalarTy->isIntegerType() &&
8311          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8312       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8313       return true;
8314     }
8315     if (!scalarTy->isIntegralType(S.Context))
8316       return true;
8317     scalarCast = CK_IntegralCast;
8318   } else if (vectorEltTy->isRealFloatingType()) {
8319     if (scalarTy->isRealFloatingType()) {
8320       if (S.getLangOpts().OpenCL &&
8321           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8322         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8323         return true;
8324       }
8325       scalarCast = CK_FloatingCast;
8326     }
8327     else if (scalarTy->isIntegralType(S.Context))
8328       scalarCast = CK_IntegralToFloating;
8329     else
8330       return true;
8331   } else {
8332     return true;
8333   }
8334 
8335   // Adjust scalar if desired.
8336   if (scalar) {
8337     if (scalarCast != CK_NoOp)
8338       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8339     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8340   }
8341   return false;
8342 }
8343 
8344 /// Convert vector E to a vector with the same number of elements but different
8345 /// element type.
8346 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8347   const auto *VecTy = E->getType()->getAs<VectorType>();
8348   assert(VecTy && "Expression E must be a vector");
8349   QualType NewVecTy = S.Context.getVectorType(ElementType,
8350                                               VecTy->getNumElements(),
8351                                               VecTy->getVectorKind());
8352 
8353   // Look through the implicit cast. Return the subexpression if its type is
8354   // NewVecTy.
8355   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8356     if (ICE->getSubExpr()->getType() == NewVecTy)
8357       return ICE->getSubExpr();
8358 
8359   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8360   return S.ImpCastExprToType(E, NewVecTy, Cast);
8361 }
8362 
8363 /// Test if a (constant) integer Int can be casted to another integer type
8364 /// IntTy without losing precision.
8365 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8366                                       QualType OtherIntTy) {
8367   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8368 
8369   // Reject cases where the value of the Int is unknown as that would
8370   // possibly cause truncation, but accept cases where the scalar can be
8371   // demoted without loss of precision.
8372   llvm::APSInt Result;
8373   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8374   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8375   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8376   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8377 
8378   if (CstInt) {
8379     // If the scalar is constant and is of a higher order and has more active
8380     // bits that the vector element type, reject it.
8381     unsigned NumBits = IntSigned
8382                            ? (Result.isNegative() ? Result.getMinSignedBits()
8383                                                   : Result.getActiveBits())
8384                            : Result.getActiveBits();
8385     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8386       return true;
8387 
8388     // If the signedness of the scalar type and the vector element type
8389     // differs and the number of bits is greater than that of the vector
8390     // element reject it.
8391     return (IntSigned != OtherIntSigned &&
8392             NumBits > S.Context.getIntWidth(OtherIntTy));
8393   }
8394 
8395   // Reject cases where the value of the scalar is not constant and it's
8396   // order is greater than that of the vector element type.
8397   return (Order < 0);
8398 }
8399 
8400 /// Test if a (constant) integer Int can be casted to floating point type
8401 /// FloatTy without losing precision.
8402 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8403                                      QualType FloatTy) {
8404   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8405 
8406   // Determine if the integer constant can be expressed as a floating point
8407   // number of the appropriate type.
8408   llvm::APSInt Result;
8409   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8410   uint64_t Bits = 0;
8411   if (CstInt) {
8412     // Reject constants that would be truncated if they were converted to
8413     // the floating point type. Test by simple to/from conversion.
8414     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8415     //        could be avoided if there was a convertFromAPInt method
8416     //        which could signal back if implicit truncation occurred.
8417     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8418     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8419                            llvm::APFloat::rmTowardZero);
8420     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8421                              !IntTy->hasSignedIntegerRepresentation());
8422     bool Ignored = false;
8423     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8424                            &Ignored);
8425     if (Result != ConvertBack)
8426       return true;
8427   } else {
8428     // Reject types that cannot be fully encoded into the mantissa of
8429     // the float.
8430     Bits = S.Context.getTypeSize(IntTy);
8431     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8432         S.Context.getFloatTypeSemantics(FloatTy));
8433     if (Bits > FloatPrec)
8434       return true;
8435   }
8436 
8437   return false;
8438 }
8439 
8440 /// Attempt to convert and splat Scalar into a vector whose types matches
8441 /// Vector following GCC conversion rules. The rule is that implicit
8442 /// conversion can occur when Scalar can be casted to match Vector's element
8443 /// type without causing truncation of Scalar.
8444 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8445                                         ExprResult *Vector) {
8446   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8447   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8448   const VectorType *VT = VectorTy->getAs<VectorType>();
8449 
8450   assert(!isa<ExtVectorType>(VT) &&
8451          "ExtVectorTypes should not be handled here!");
8452 
8453   QualType VectorEltTy = VT->getElementType();
8454 
8455   // Reject cases where the vector element type or the scalar element type are
8456   // not integral or floating point types.
8457   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8458     return true;
8459 
8460   // The conversion to apply to the scalar before splatting it,
8461   // if necessary.
8462   CastKind ScalarCast = CK_NoOp;
8463 
8464   // Accept cases where the vector elements are integers and the scalar is
8465   // an integer.
8466   // FIXME: Notionally if the scalar was a floating point value with a precise
8467   //        integral representation, we could cast it to an appropriate integer
8468   //        type and then perform the rest of the checks here. GCC will perform
8469   //        this conversion in some cases as determined by the input language.
8470   //        We should accept it on a language independent basis.
8471   if (VectorEltTy->isIntegralType(S.Context) &&
8472       ScalarTy->isIntegralType(S.Context) &&
8473       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8474 
8475     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8476       return true;
8477 
8478     ScalarCast = CK_IntegralCast;
8479   } else if (VectorEltTy->isRealFloatingType()) {
8480     if (ScalarTy->isRealFloatingType()) {
8481 
8482       // Reject cases where the scalar type is not a constant and has a higher
8483       // Order than the vector element type.
8484       llvm::APFloat Result(0.0);
8485       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8486       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8487       if (!CstScalar && Order < 0)
8488         return true;
8489 
8490       // If the scalar cannot be safely casted to the vector element type,
8491       // reject it.
8492       if (CstScalar) {
8493         bool Truncated = false;
8494         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8495                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8496         if (Truncated)
8497           return true;
8498       }
8499 
8500       ScalarCast = CK_FloatingCast;
8501     } else if (ScalarTy->isIntegralType(S.Context)) {
8502       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8503         return true;
8504 
8505       ScalarCast = CK_IntegralToFloating;
8506     } else
8507       return true;
8508   }
8509 
8510   // Adjust scalar if desired.
8511   if (Scalar) {
8512     if (ScalarCast != CK_NoOp)
8513       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8514     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8515   }
8516   return false;
8517 }
8518 
8519 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8520                                    SourceLocation Loc, bool IsCompAssign,
8521                                    bool AllowBothBool,
8522                                    bool AllowBoolConversions) {
8523   if (!IsCompAssign) {
8524     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8525     if (LHS.isInvalid())
8526       return QualType();
8527   }
8528   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8529   if (RHS.isInvalid())
8530     return QualType();
8531 
8532   // For conversion purposes, we ignore any qualifiers.
8533   // For example, "const float" and "float" are equivalent.
8534   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8535   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8536 
8537   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8538   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8539   assert(LHSVecType || RHSVecType);
8540 
8541   // AltiVec-style "vector bool op vector bool" combinations are allowed
8542   // for some operators but not others.
8543   if (!AllowBothBool &&
8544       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8545       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8546     return InvalidOperands(Loc, LHS, RHS);
8547 
8548   // If the vector types are identical, return.
8549   if (Context.hasSameType(LHSType, RHSType))
8550     return LHSType;
8551 
8552   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8553   if (LHSVecType && RHSVecType &&
8554       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8555     if (isa<ExtVectorType>(LHSVecType)) {
8556       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8557       return LHSType;
8558     }
8559 
8560     if (!IsCompAssign)
8561       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8562     return RHSType;
8563   }
8564 
8565   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8566   // can be mixed, with the result being the non-bool type.  The non-bool
8567   // operand must have integer element type.
8568   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8569       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8570       (Context.getTypeSize(LHSVecType->getElementType()) ==
8571        Context.getTypeSize(RHSVecType->getElementType()))) {
8572     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8573         LHSVecType->getElementType()->isIntegerType() &&
8574         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8575       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8576       return LHSType;
8577     }
8578     if (!IsCompAssign &&
8579         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8580         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8581         RHSVecType->getElementType()->isIntegerType()) {
8582       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8583       return RHSType;
8584     }
8585   }
8586 
8587   // If there's a vector type and a scalar, try to convert the scalar to
8588   // the vector element type and splat.
8589   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8590   if (!RHSVecType) {
8591     if (isa<ExtVectorType>(LHSVecType)) {
8592       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8593                                     LHSVecType->getElementType(), LHSType,
8594                                     DiagID))
8595         return LHSType;
8596     } else {
8597       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8598         return LHSType;
8599     }
8600   }
8601   if (!LHSVecType) {
8602     if (isa<ExtVectorType>(RHSVecType)) {
8603       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8604                                     LHSType, RHSVecType->getElementType(),
8605                                     RHSType, DiagID))
8606         return RHSType;
8607     } else {
8608       if (LHS.get()->getValueKind() == VK_LValue ||
8609           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8610         return RHSType;
8611     }
8612   }
8613 
8614   // FIXME: The code below also handles conversion between vectors and
8615   // non-scalars, we should break this down into fine grained specific checks
8616   // and emit proper diagnostics.
8617   QualType VecType = LHSVecType ? LHSType : RHSType;
8618   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8619   QualType OtherType = LHSVecType ? RHSType : LHSType;
8620   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8621   if (isLaxVectorConversion(OtherType, VecType)) {
8622     // If we're allowing lax vector conversions, only the total (data) size
8623     // needs to be the same. For non compound assignment, if one of the types is
8624     // scalar, the result is always the vector type.
8625     if (!IsCompAssign) {
8626       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8627       return VecType;
8628     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8629     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8630     // type. Note that this is already done by non-compound assignments in
8631     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8632     // <1 x T> -> T. The result is also a vector type.
8633     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8634                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8635       ExprResult *RHSExpr = &RHS;
8636       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8637       return VecType;
8638     }
8639   }
8640 
8641   // Okay, the expression is invalid.
8642 
8643   // If there's a non-vector, non-real operand, diagnose that.
8644   if ((!RHSVecType && !RHSType->isRealType()) ||
8645       (!LHSVecType && !LHSType->isRealType())) {
8646     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8647       << LHSType << RHSType
8648       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8649     return QualType();
8650   }
8651 
8652   // OpenCL V1.1 6.2.6.p1:
8653   // If the operands are of more than one vector type, then an error shall
8654   // occur. Implicit conversions between vector types are not permitted, per
8655   // section 6.2.1.
8656   if (getLangOpts().OpenCL &&
8657       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8658       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8659     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8660                                                            << RHSType;
8661     return QualType();
8662   }
8663 
8664 
8665   // If there is a vector type that is not a ExtVector and a scalar, we reach
8666   // this point if scalar could not be converted to the vector's element type
8667   // without truncation.
8668   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8669       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8670     QualType Scalar = LHSVecType ? RHSType : LHSType;
8671     QualType Vector = LHSVecType ? LHSType : RHSType;
8672     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8673     Diag(Loc,
8674          diag::err_typecheck_vector_not_convertable_implict_truncation)
8675         << ScalarOrVector << Scalar << Vector;
8676 
8677     return QualType();
8678   }
8679 
8680   // Otherwise, use the generic diagnostic.
8681   Diag(Loc, DiagID)
8682     << LHSType << RHSType
8683     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8684   return QualType();
8685 }
8686 
8687 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8688 // expression.  These are mainly cases where the null pointer is used as an
8689 // integer instead of a pointer.
8690 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8691                                 SourceLocation Loc, bool IsCompare) {
8692   // The canonical way to check for a GNU null is with isNullPointerConstant,
8693   // but we use a bit of a hack here for speed; this is a relatively
8694   // hot path, and isNullPointerConstant is slow.
8695   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8696   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8697 
8698   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8699 
8700   // Avoid analyzing cases where the result will either be invalid (and
8701   // diagnosed as such) or entirely valid and not something to warn about.
8702   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8703       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8704     return;
8705 
8706   // Comparison operations would not make sense with a null pointer no matter
8707   // what the other expression is.
8708   if (!IsCompare) {
8709     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8710         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8711         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8712     return;
8713   }
8714 
8715   // The rest of the operations only make sense with a null pointer
8716   // if the other expression is a pointer.
8717   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8718       NonNullType->canDecayToPointerType())
8719     return;
8720 
8721   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8722       << LHSNull /* LHS is NULL */ << NonNullType
8723       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8724 }
8725 
8726 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8727                                                ExprResult &RHS,
8728                                                SourceLocation Loc, bool IsDiv) {
8729   // Check for division/remainder by zero.
8730   llvm::APSInt RHSValue;
8731   if (!RHS.get()->isValueDependent() &&
8732       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8733     S.DiagRuntimeBehavior(Loc, RHS.get(),
8734                           S.PDiag(diag::warn_remainder_division_by_zero)
8735                             << IsDiv << RHS.get()->getSourceRange());
8736 }
8737 
8738 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8739                                            SourceLocation Loc,
8740                                            bool IsCompAssign, bool IsDiv) {
8741   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8742 
8743   if (LHS.get()->getType()->isVectorType() ||
8744       RHS.get()->getType()->isVectorType())
8745     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8746                                /*AllowBothBool*/getLangOpts().AltiVec,
8747                                /*AllowBoolConversions*/false);
8748 
8749   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8750   if (LHS.isInvalid() || RHS.isInvalid())
8751     return QualType();
8752 
8753 
8754   if (compType.isNull() || !compType->isArithmeticType())
8755     return InvalidOperands(Loc, LHS, RHS);
8756   if (IsDiv)
8757     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8758   return compType;
8759 }
8760 
8761 QualType Sema::CheckRemainderOperands(
8762   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8763   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8764 
8765   if (LHS.get()->getType()->isVectorType() ||
8766       RHS.get()->getType()->isVectorType()) {
8767     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8768         RHS.get()->getType()->hasIntegerRepresentation())
8769       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8770                                  /*AllowBothBool*/getLangOpts().AltiVec,
8771                                  /*AllowBoolConversions*/false);
8772     return InvalidOperands(Loc, LHS, RHS);
8773   }
8774 
8775   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8776   if (LHS.isInvalid() || RHS.isInvalid())
8777     return QualType();
8778 
8779   if (compType.isNull() || !compType->isIntegerType())
8780     return InvalidOperands(Loc, LHS, RHS);
8781   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8782   return compType;
8783 }
8784 
8785 /// Diagnose invalid arithmetic on two void pointers.
8786 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8787                                                 Expr *LHSExpr, Expr *RHSExpr) {
8788   S.Diag(Loc, S.getLangOpts().CPlusPlus
8789                 ? diag::err_typecheck_pointer_arith_void_type
8790                 : diag::ext_gnu_void_ptr)
8791     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8792                             << RHSExpr->getSourceRange();
8793 }
8794 
8795 /// Diagnose invalid arithmetic on a void pointer.
8796 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8797                                             Expr *Pointer) {
8798   S.Diag(Loc, S.getLangOpts().CPlusPlus
8799                 ? diag::err_typecheck_pointer_arith_void_type
8800                 : diag::ext_gnu_void_ptr)
8801     << 0 /* one pointer */ << Pointer->getSourceRange();
8802 }
8803 
8804 /// Diagnose invalid arithmetic on a null pointer.
8805 ///
8806 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8807 /// idiom, which we recognize as a GNU extension.
8808 ///
8809 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8810                                             Expr *Pointer, bool IsGNUIdiom) {
8811   if (IsGNUIdiom)
8812     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8813       << Pointer->getSourceRange();
8814   else
8815     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8816       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8817 }
8818 
8819 /// Diagnose invalid arithmetic on two function pointers.
8820 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8821                                                     Expr *LHS, Expr *RHS) {
8822   assert(LHS->getType()->isAnyPointerType());
8823   assert(RHS->getType()->isAnyPointerType());
8824   S.Diag(Loc, S.getLangOpts().CPlusPlus
8825                 ? diag::err_typecheck_pointer_arith_function_type
8826                 : diag::ext_gnu_ptr_func_arith)
8827     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8828     // We only show the second type if it differs from the first.
8829     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8830                                                    RHS->getType())
8831     << RHS->getType()->getPointeeType()
8832     << LHS->getSourceRange() << RHS->getSourceRange();
8833 }
8834 
8835 /// Diagnose invalid arithmetic on a function pointer.
8836 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8837                                                 Expr *Pointer) {
8838   assert(Pointer->getType()->isAnyPointerType());
8839   S.Diag(Loc, S.getLangOpts().CPlusPlus
8840                 ? diag::err_typecheck_pointer_arith_function_type
8841                 : diag::ext_gnu_ptr_func_arith)
8842     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8843     << 0 /* one pointer, so only one type */
8844     << Pointer->getSourceRange();
8845 }
8846 
8847 /// Emit error if Operand is incomplete pointer type
8848 ///
8849 /// \returns True if pointer has incomplete type
8850 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8851                                                  Expr *Operand) {
8852   QualType ResType = Operand->getType();
8853   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8854     ResType = ResAtomicType->getValueType();
8855 
8856   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8857   QualType PointeeTy = ResType->getPointeeType();
8858   return S.RequireCompleteType(Loc, PointeeTy,
8859                                diag::err_typecheck_arithmetic_incomplete_type,
8860                                PointeeTy, Operand->getSourceRange());
8861 }
8862 
8863 /// Check the validity of an arithmetic pointer operand.
8864 ///
8865 /// If the operand has pointer type, this code will check for pointer types
8866 /// which are invalid in arithmetic operations. These will be diagnosed
8867 /// appropriately, including whether or not the use is supported as an
8868 /// extension.
8869 ///
8870 /// \returns True when the operand is valid to use (even if as an extension).
8871 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8872                                             Expr *Operand) {
8873   QualType ResType = Operand->getType();
8874   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8875     ResType = ResAtomicType->getValueType();
8876 
8877   if (!ResType->isAnyPointerType()) return true;
8878 
8879   QualType PointeeTy = ResType->getPointeeType();
8880   if (PointeeTy->isVoidType()) {
8881     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8882     return !S.getLangOpts().CPlusPlus;
8883   }
8884   if (PointeeTy->isFunctionType()) {
8885     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8886     return !S.getLangOpts().CPlusPlus;
8887   }
8888 
8889   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8890 
8891   return true;
8892 }
8893 
8894 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8895 /// operands.
8896 ///
8897 /// This routine will diagnose any invalid arithmetic on pointer operands much
8898 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8899 /// for emitting a single diagnostic even for operations where both LHS and RHS
8900 /// are (potentially problematic) pointers.
8901 ///
8902 /// \returns True when the operand is valid to use (even if as an extension).
8903 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8904                                                 Expr *LHSExpr, Expr *RHSExpr) {
8905   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8906   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8907   if (!isLHSPointer && !isRHSPointer) return true;
8908 
8909   QualType LHSPointeeTy, RHSPointeeTy;
8910   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8911   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8912 
8913   // if both are pointers check if operation is valid wrt address spaces
8914   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8915     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8916     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8917     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8918       S.Diag(Loc,
8919              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8920           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8921           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8922       return false;
8923     }
8924   }
8925 
8926   // Check for arithmetic on pointers to incomplete types.
8927   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8928   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8929   if (isLHSVoidPtr || isRHSVoidPtr) {
8930     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8931     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8932     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8933 
8934     return !S.getLangOpts().CPlusPlus;
8935   }
8936 
8937   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8938   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8939   if (isLHSFuncPtr || isRHSFuncPtr) {
8940     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8941     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8942                                                                 RHSExpr);
8943     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8944 
8945     return !S.getLangOpts().CPlusPlus;
8946   }
8947 
8948   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8949     return false;
8950   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8951     return false;
8952 
8953   return true;
8954 }
8955 
8956 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8957 /// literal.
8958 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8959                                   Expr *LHSExpr, Expr *RHSExpr) {
8960   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8961   Expr* IndexExpr = RHSExpr;
8962   if (!StrExpr) {
8963     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8964     IndexExpr = LHSExpr;
8965   }
8966 
8967   bool IsStringPlusInt = StrExpr &&
8968       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8969   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8970     return;
8971 
8972   llvm::APSInt index;
8973   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8974     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8975     if (index.isNonNegative() &&
8976         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8977                               index.isUnsigned()))
8978       return;
8979   }
8980 
8981   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
8982   Self.Diag(OpLoc, diag::warn_string_plus_int)
8983       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8984 
8985   // Only print a fixit for "str" + int, not for int + "str".
8986   if (IndexExpr == RHSExpr) {
8987     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
8988     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8989         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
8990         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8991         << FixItHint::CreateInsertion(EndLoc, "]");
8992   } else
8993     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8994 }
8995 
8996 /// Emit a warning when adding a char literal to a string.
8997 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8998                                    Expr *LHSExpr, Expr *RHSExpr) {
8999   const Expr *StringRefExpr = LHSExpr;
9000   const CharacterLiteral *CharExpr =
9001       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9002 
9003   if (!CharExpr) {
9004     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9005     StringRefExpr = RHSExpr;
9006   }
9007 
9008   if (!CharExpr || !StringRefExpr)
9009     return;
9010 
9011   const QualType StringType = StringRefExpr->getType();
9012 
9013   // Return if not a PointerType.
9014   if (!StringType->isAnyPointerType())
9015     return;
9016 
9017   // Return if not a CharacterType.
9018   if (!StringType->getPointeeType()->isAnyCharacterType())
9019     return;
9020 
9021   ASTContext &Ctx = Self.getASTContext();
9022   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9023 
9024   const QualType CharType = CharExpr->getType();
9025   if (!CharType->isAnyCharacterType() &&
9026       CharType->isIntegerType() &&
9027       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9028     Self.Diag(OpLoc, diag::warn_string_plus_char)
9029         << DiagRange << Ctx.CharTy;
9030   } else {
9031     Self.Diag(OpLoc, diag::warn_string_plus_char)
9032         << DiagRange << CharExpr->getType();
9033   }
9034 
9035   // Only print a fixit for str + char, not for char + str.
9036   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9037     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9038     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9039         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9040         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9041         << FixItHint::CreateInsertion(EndLoc, "]");
9042   } else {
9043     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9044   }
9045 }
9046 
9047 /// Emit error when two pointers are incompatible.
9048 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9049                                            Expr *LHSExpr, Expr *RHSExpr) {
9050   assert(LHSExpr->getType()->isAnyPointerType());
9051   assert(RHSExpr->getType()->isAnyPointerType());
9052   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9053     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9054     << RHSExpr->getSourceRange();
9055 }
9056 
9057 // C99 6.5.6
9058 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9059                                      SourceLocation Loc, BinaryOperatorKind Opc,
9060                                      QualType* CompLHSTy) {
9061   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9062 
9063   if (LHS.get()->getType()->isVectorType() ||
9064       RHS.get()->getType()->isVectorType()) {
9065     QualType compType = CheckVectorOperands(
9066         LHS, RHS, Loc, CompLHSTy,
9067         /*AllowBothBool*/getLangOpts().AltiVec,
9068         /*AllowBoolConversions*/getLangOpts().ZVector);
9069     if (CompLHSTy) *CompLHSTy = compType;
9070     return compType;
9071   }
9072 
9073   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9074   if (LHS.isInvalid() || RHS.isInvalid())
9075     return QualType();
9076 
9077   // Diagnose "string literal" '+' int and string '+' "char literal".
9078   if (Opc == BO_Add) {
9079     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9080     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9081   }
9082 
9083   // handle the common case first (both operands are arithmetic).
9084   if (!compType.isNull() && compType->isArithmeticType()) {
9085     if (CompLHSTy) *CompLHSTy = compType;
9086     return compType;
9087   }
9088 
9089   // Type-checking.  Ultimately the pointer's going to be in PExp;
9090   // note that we bias towards the LHS being the pointer.
9091   Expr *PExp = LHS.get(), *IExp = RHS.get();
9092 
9093   bool isObjCPointer;
9094   if (PExp->getType()->isPointerType()) {
9095     isObjCPointer = false;
9096   } else if (PExp->getType()->isObjCObjectPointerType()) {
9097     isObjCPointer = true;
9098   } else {
9099     std::swap(PExp, IExp);
9100     if (PExp->getType()->isPointerType()) {
9101       isObjCPointer = false;
9102     } else if (PExp->getType()->isObjCObjectPointerType()) {
9103       isObjCPointer = true;
9104     } else {
9105       return InvalidOperands(Loc, LHS, RHS);
9106     }
9107   }
9108   assert(PExp->getType()->isAnyPointerType());
9109 
9110   if (!IExp->getType()->isIntegerType())
9111     return InvalidOperands(Loc, LHS, RHS);
9112 
9113   // Adding to a null pointer results in undefined behavior.
9114   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9115           Context, Expr::NPC_ValueDependentIsNotNull)) {
9116     // In C++ adding zero to a null pointer is defined.
9117     llvm::APSInt KnownVal;
9118     if (!getLangOpts().CPlusPlus ||
9119         (!IExp->isValueDependent() &&
9120          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9121       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9122       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9123           Context, BO_Add, PExp, IExp);
9124       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9125     }
9126   }
9127 
9128   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9129     return QualType();
9130 
9131   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9132     return QualType();
9133 
9134   // Check array bounds for pointer arithemtic
9135   CheckArrayAccess(PExp, IExp);
9136 
9137   if (CompLHSTy) {
9138     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9139     if (LHSTy.isNull()) {
9140       LHSTy = LHS.get()->getType();
9141       if (LHSTy->isPromotableIntegerType())
9142         LHSTy = Context.getPromotedIntegerType(LHSTy);
9143     }
9144     *CompLHSTy = LHSTy;
9145   }
9146 
9147   return PExp->getType();
9148 }
9149 
9150 // C99 6.5.6
9151 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9152                                         SourceLocation Loc,
9153                                         QualType* CompLHSTy) {
9154   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9155 
9156   if (LHS.get()->getType()->isVectorType() ||
9157       RHS.get()->getType()->isVectorType()) {
9158     QualType compType = CheckVectorOperands(
9159         LHS, RHS, Loc, CompLHSTy,
9160         /*AllowBothBool*/getLangOpts().AltiVec,
9161         /*AllowBoolConversions*/getLangOpts().ZVector);
9162     if (CompLHSTy) *CompLHSTy = compType;
9163     return compType;
9164   }
9165 
9166   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9167   if (LHS.isInvalid() || RHS.isInvalid())
9168     return QualType();
9169 
9170   // Enforce type constraints: C99 6.5.6p3.
9171 
9172   // Handle the common case first (both operands are arithmetic).
9173   if (!compType.isNull() && compType->isArithmeticType()) {
9174     if (CompLHSTy) *CompLHSTy = compType;
9175     return compType;
9176   }
9177 
9178   // Either ptr - int   or   ptr - ptr.
9179   if (LHS.get()->getType()->isAnyPointerType()) {
9180     QualType lpointee = LHS.get()->getType()->getPointeeType();
9181 
9182     // Diagnose bad cases where we step over interface counts.
9183     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9184         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9185       return QualType();
9186 
9187     // The result type of a pointer-int computation is the pointer type.
9188     if (RHS.get()->getType()->isIntegerType()) {
9189       // Subtracting from a null pointer should produce a warning.
9190       // The last argument to the diagnose call says this doesn't match the
9191       // GNU int-to-pointer idiom.
9192       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9193                                            Expr::NPC_ValueDependentIsNotNull)) {
9194         // In C++ adding zero to a null pointer is defined.
9195         llvm::APSInt KnownVal;
9196         if (!getLangOpts().CPlusPlus ||
9197             (!RHS.get()->isValueDependent() &&
9198              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9199           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9200         }
9201       }
9202 
9203       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9204         return QualType();
9205 
9206       // Check array bounds for pointer arithemtic
9207       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9208                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9209 
9210       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9211       return LHS.get()->getType();
9212     }
9213 
9214     // Handle pointer-pointer subtractions.
9215     if (const PointerType *RHSPTy
9216           = RHS.get()->getType()->getAs<PointerType>()) {
9217       QualType rpointee = RHSPTy->getPointeeType();
9218 
9219       if (getLangOpts().CPlusPlus) {
9220         // Pointee types must be the same: C++ [expr.add]
9221         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9222           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9223         }
9224       } else {
9225         // Pointee types must be compatible C99 6.5.6p3
9226         if (!Context.typesAreCompatible(
9227                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9228                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9229           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9230           return QualType();
9231         }
9232       }
9233 
9234       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9235                                                LHS.get(), RHS.get()))
9236         return QualType();
9237 
9238       // FIXME: Add warnings for nullptr - ptr.
9239 
9240       // The pointee type may have zero size.  As an extension, a structure or
9241       // union may have zero size or an array may have zero length.  In this
9242       // case subtraction does not make sense.
9243       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9244         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9245         if (ElementSize.isZero()) {
9246           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9247             << rpointee.getUnqualifiedType()
9248             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9249         }
9250       }
9251 
9252       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9253       return Context.getPointerDiffType();
9254     }
9255   }
9256 
9257   return InvalidOperands(Loc, LHS, RHS);
9258 }
9259 
9260 static bool isScopedEnumerationType(QualType T) {
9261   if (const EnumType *ET = T->getAs<EnumType>())
9262     return ET->getDecl()->isScoped();
9263   return false;
9264 }
9265 
9266 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9267                                    SourceLocation Loc, BinaryOperatorKind Opc,
9268                                    QualType LHSType) {
9269   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9270   // so skip remaining warnings as we don't want to modify values within Sema.
9271   if (S.getLangOpts().OpenCL)
9272     return;
9273 
9274   llvm::APSInt Right;
9275   // Check right/shifter operand
9276   if (RHS.get()->isValueDependent() ||
9277       !RHS.get()->EvaluateAsInt(Right, S.Context))
9278     return;
9279 
9280   if (Right.isNegative()) {
9281     S.DiagRuntimeBehavior(Loc, RHS.get(),
9282                           S.PDiag(diag::warn_shift_negative)
9283                             << RHS.get()->getSourceRange());
9284     return;
9285   }
9286   llvm::APInt LeftBits(Right.getBitWidth(),
9287                        S.Context.getTypeSize(LHS.get()->getType()));
9288   if (Right.uge(LeftBits)) {
9289     S.DiagRuntimeBehavior(Loc, RHS.get(),
9290                           S.PDiag(diag::warn_shift_gt_typewidth)
9291                             << RHS.get()->getSourceRange());
9292     return;
9293   }
9294   if (Opc != BO_Shl)
9295     return;
9296 
9297   // When left shifting an ICE which is signed, we can check for overflow which
9298   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9299   // integers have defined behavior modulo one more than the maximum value
9300   // representable in the result type, so never warn for those.
9301   llvm::APSInt Left;
9302   if (LHS.get()->isValueDependent() ||
9303       LHSType->hasUnsignedIntegerRepresentation() ||
9304       !LHS.get()->EvaluateAsInt(Left, S.Context))
9305     return;
9306 
9307   // If LHS does not have a signed type and non-negative value
9308   // then, the behavior is undefined. Warn about it.
9309   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9310     S.DiagRuntimeBehavior(Loc, LHS.get(),
9311                           S.PDiag(diag::warn_shift_lhs_negative)
9312                             << LHS.get()->getSourceRange());
9313     return;
9314   }
9315 
9316   llvm::APInt ResultBits =
9317       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9318   if (LeftBits.uge(ResultBits))
9319     return;
9320   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9321   Result = Result.shl(Right);
9322 
9323   // Print the bit representation of the signed integer as an unsigned
9324   // hexadecimal number.
9325   SmallString<40> HexResult;
9326   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9327 
9328   // If we are only missing a sign bit, this is less likely to result in actual
9329   // bugs -- if the result is cast back to an unsigned type, it will have the
9330   // expected value. Thus we place this behind a different warning that can be
9331   // turned off separately if needed.
9332   if (LeftBits == ResultBits - 1) {
9333     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9334         << HexResult << LHSType
9335         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9336     return;
9337   }
9338 
9339   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9340     << HexResult.str() << Result.getMinSignedBits() << LHSType
9341     << Left.getBitWidth() << LHS.get()->getSourceRange()
9342     << RHS.get()->getSourceRange();
9343 }
9344 
9345 /// Return the resulting type when a vector is shifted
9346 ///        by a scalar or vector shift amount.
9347 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9348                                  SourceLocation Loc, bool IsCompAssign) {
9349   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9350   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9351       !LHS.get()->getType()->isVectorType()) {
9352     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9353       << RHS.get()->getType() << LHS.get()->getType()
9354       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9355     return QualType();
9356   }
9357 
9358   if (!IsCompAssign) {
9359     LHS = S.UsualUnaryConversions(LHS.get());
9360     if (LHS.isInvalid()) return QualType();
9361   }
9362 
9363   RHS = S.UsualUnaryConversions(RHS.get());
9364   if (RHS.isInvalid()) return QualType();
9365 
9366   QualType LHSType = LHS.get()->getType();
9367   // Note that LHS might be a scalar because the routine calls not only in
9368   // OpenCL case.
9369   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9370   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9371 
9372   // Note that RHS might not be a vector.
9373   QualType RHSType = RHS.get()->getType();
9374   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9375   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9376 
9377   // The operands need to be integers.
9378   if (!LHSEleType->isIntegerType()) {
9379     S.Diag(Loc, diag::err_typecheck_expect_int)
9380       << LHS.get()->getType() << LHS.get()->getSourceRange();
9381     return QualType();
9382   }
9383 
9384   if (!RHSEleType->isIntegerType()) {
9385     S.Diag(Loc, diag::err_typecheck_expect_int)
9386       << RHS.get()->getType() << RHS.get()->getSourceRange();
9387     return QualType();
9388   }
9389 
9390   if (!LHSVecTy) {
9391     assert(RHSVecTy);
9392     if (IsCompAssign)
9393       return RHSType;
9394     if (LHSEleType != RHSEleType) {
9395       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9396       LHSEleType = RHSEleType;
9397     }
9398     QualType VecTy =
9399         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9400     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9401     LHSType = VecTy;
9402   } else if (RHSVecTy) {
9403     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9404     // are applied component-wise. So if RHS is a vector, then ensure
9405     // that the number of elements is the same as LHS...
9406     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9407       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9408         << LHS.get()->getType() << RHS.get()->getType()
9409         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9410       return QualType();
9411     }
9412     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9413       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9414       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9415       if (LHSBT != RHSBT &&
9416           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9417         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9418             << LHS.get()->getType() << RHS.get()->getType()
9419             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9420       }
9421     }
9422   } else {
9423     // ...else expand RHS to match the number of elements in LHS.
9424     QualType VecTy =
9425       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9426     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9427   }
9428 
9429   return LHSType;
9430 }
9431 
9432 // C99 6.5.7
9433 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9434                                   SourceLocation Loc, BinaryOperatorKind Opc,
9435                                   bool IsCompAssign) {
9436   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9437 
9438   // Vector shifts promote their scalar inputs to vector type.
9439   if (LHS.get()->getType()->isVectorType() ||
9440       RHS.get()->getType()->isVectorType()) {
9441     if (LangOpts.ZVector) {
9442       // The shift operators for the z vector extensions work basically
9443       // like general shifts, except that neither the LHS nor the RHS is
9444       // allowed to be a "vector bool".
9445       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9446         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9447           return InvalidOperands(Loc, LHS, RHS);
9448       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9449         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9450           return InvalidOperands(Loc, LHS, RHS);
9451     }
9452     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9453   }
9454 
9455   // Shifts don't perform usual arithmetic conversions, they just do integer
9456   // promotions on each operand. C99 6.5.7p3
9457 
9458   // For the LHS, do usual unary conversions, but then reset them away
9459   // if this is a compound assignment.
9460   ExprResult OldLHS = LHS;
9461   LHS = UsualUnaryConversions(LHS.get());
9462   if (LHS.isInvalid())
9463     return QualType();
9464   QualType LHSType = LHS.get()->getType();
9465   if (IsCompAssign) LHS = OldLHS;
9466 
9467   // The RHS is simpler.
9468   RHS = UsualUnaryConversions(RHS.get());
9469   if (RHS.isInvalid())
9470     return QualType();
9471   QualType RHSType = RHS.get()->getType();
9472 
9473   // C99 6.5.7p2: Each of the operands shall have integer type.
9474   if (!LHSType->hasIntegerRepresentation() ||
9475       !RHSType->hasIntegerRepresentation())
9476     return InvalidOperands(Loc, LHS, RHS);
9477 
9478   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9479   // hasIntegerRepresentation() above instead of this.
9480   if (isScopedEnumerationType(LHSType) ||
9481       isScopedEnumerationType(RHSType)) {
9482     return InvalidOperands(Loc, LHS, RHS);
9483   }
9484   // Sanity-check shift operands
9485   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9486 
9487   // "The type of the result is that of the promoted left operand."
9488   return LHSType;
9489 }
9490 
9491 /// If two different enums are compared, raise a warning.
9492 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9493                                 Expr *RHS) {
9494   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9495   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9496 
9497   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9498   if (!LHSEnumType)
9499     return;
9500   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9501   if (!RHSEnumType)
9502     return;
9503 
9504   // Ignore anonymous enums.
9505   if (!LHSEnumType->getDecl()->getIdentifier() &&
9506       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9507     return;
9508   if (!RHSEnumType->getDecl()->getIdentifier() &&
9509       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9510     return;
9511 
9512   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9513     return;
9514 
9515   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9516       << LHSStrippedType << RHSStrippedType
9517       << LHS->getSourceRange() << RHS->getSourceRange();
9518 }
9519 
9520 /// Diagnose bad pointer comparisons.
9521 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9522                                               ExprResult &LHS, ExprResult &RHS,
9523                                               bool IsError) {
9524   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9525                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9526     << LHS.get()->getType() << RHS.get()->getType()
9527     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9528 }
9529 
9530 /// Returns false if the pointers are converted to a composite type,
9531 /// true otherwise.
9532 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9533                                            ExprResult &LHS, ExprResult &RHS) {
9534   // C++ [expr.rel]p2:
9535   //   [...] Pointer conversions (4.10) and qualification
9536   //   conversions (4.4) are performed on pointer operands (or on
9537   //   a pointer operand and a null pointer constant) to bring
9538   //   them to their composite pointer type. [...]
9539   //
9540   // C++ [expr.eq]p1 uses the same notion for (in)equality
9541   // comparisons of pointers.
9542 
9543   QualType LHSType = LHS.get()->getType();
9544   QualType RHSType = RHS.get()->getType();
9545   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9546          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9547 
9548   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9549   if (T.isNull()) {
9550     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9551         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9552       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9553     else
9554       S.InvalidOperands(Loc, LHS, RHS);
9555     return true;
9556   }
9557 
9558   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9559   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9560   return false;
9561 }
9562 
9563 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9564                                                     ExprResult &LHS,
9565                                                     ExprResult &RHS,
9566                                                     bool IsError) {
9567   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9568                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9569     << LHS.get()->getType() << RHS.get()->getType()
9570     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9571 }
9572 
9573 static bool isObjCObjectLiteral(ExprResult &E) {
9574   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9575   case Stmt::ObjCArrayLiteralClass:
9576   case Stmt::ObjCDictionaryLiteralClass:
9577   case Stmt::ObjCStringLiteralClass:
9578   case Stmt::ObjCBoxedExprClass:
9579     return true;
9580   default:
9581     // Note that ObjCBoolLiteral is NOT an object literal!
9582     return false;
9583   }
9584 }
9585 
9586 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9587   const ObjCObjectPointerType *Type =
9588     LHS->getType()->getAs<ObjCObjectPointerType>();
9589 
9590   // If this is not actually an Objective-C object, bail out.
9591   if (!Type)
9592     return false;
9593 
9594   // Get the LHS object's interface type.
9595   QualType InterfaceType = Type->getPointeeType();
9596 
9597   // If the RHS isn't an Objective-C object, bail out.
9598   if (!RHS->getType()->isObjCObjectPointerType())
9599     return false;
9600 
9601   // Try to find the -isEqual: method.
9602   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9603   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9604                                                       InterfaceType,
9605                                                       /*instance=*/true);
9606   if (!Method) {
9607     if (Type->isObjCIdType()) {
9608       // For 'id', just check the global pool.
9609       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9610                                                   /*receiverId=*/true);
9611     } else {
9612       // Check protocols.
9613       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9614                                              /*instance=*/true);
9615     }
9616   }
9617 
9618   if (!Method)
9619     return false;
9620 
9621   QualType T = Method->parameters()[0]->getType();
9622   if (!T->isObjCObjectPointerType())
9623     return false;
9624 
9625   QualType R = Method->getReturnType();
9626   if (!R->isScalarType())
9627     return false;
9628 
9629   return true;
9630 }
9631 
9632 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9633   FromE = FromE->IgnoreParenImpCasts();
9634   switch (FromE->getStmtClass()) {
9635     default:
9636       break;
9637     case Stmt::ObjCStringLiteralClass:
9638       // "string literal"
9639       return LK_String;
9640     case Stmt::ObjCArrayLiteralClass:
9641       // "array literal"
9642       return LK_Array;
9643     case Stmt::ObjCDictionaryLiteralClass:
9644       // "dictionary literal"
9645       return LK_Dictionary;
9646     case Stmt::BlockExprClass:
9647       return LK_Block;
9648     case Stmt::ObjCBoxedExprClass: {
9649       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9650       switch (Inner->getStmtClass()) {
9651         case Stmt::IntegerLiteralClass:
9652         case Stmt::FloatingLiteralClass:
9653         case Stmt::CharacterLiteralClass:
9654         case Stmt::ObjCBoolLiteralExprClass:
9655         case Stmt::CXXBoolLiteralExprClass:
9656           // "numeric literal"
9657           return LK_Numeric;
9658         case Stmt::ImplicitCastExprClass: {
9659           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9660           // Boolean literals can be represented by implicit casts.
9661           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9662             return LK_Numeric;
9663           break;
9664         }
9665         default:
9666           break;
9667       }
9668       return LK_Boxed;
9669     }
9670   }
9671   return LK_None;
9672 }
9673 
9674 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9675                                           ExprResult &LHS, ExprResult &RHS,
9676                                           BinaryOperator::Opcode Opc){
9677   Expr *Literal;
9678   Expr *Other;
9679   if (isObjCObjectLiteral(LHS)) {
9680     Literal = LHS.get();
9681     Other = RHS.get();
9682   } else {
9683     Literal = RHS.get();
9684     Other = LHS.get();
9685   }
9686 
9687   // Don't warn on comparisons against nil.
9688   Other = Other->IgnoreParenCasts();
9689   if (Other->isNullPointerConstant(S.getASTContext(),
9690                                    Expr::NPC_ValueDependentIsNotNull))
9691     return;
9692 
9693   // This should be kept in sync with warn_objc_literal_comparison.
9694   // LK_String should always be after the other literals, since it has its own
9695   // warning flag.
9696   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9697   assert(LiteralKind != Sema::LK_Block);
9698   if (LiteralKind == Sema::LK_None) {
9699     llvm_unreachable("Unknown Objective-C object literal kind");
9700   }
9701 
9702   if (LiteralKind == Sema::LK_String)
9703     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9704       << Literal->getSourceRange();
9705   else
9706     S.Diag(Loc, diag::warn_objc_literal_comparison)
9707       << LiteralKind << Literal->getSourceRange();
9708 
9709   if (BinaryOperator::isEqualityOp(Opc) &&
9710       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9711     SourceLocation Start = LHS.get()->getBeginLoc();
9712     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9713     CharSourceRange OpRange =
9714       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9715 
9716     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9717       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9718       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9719       << FixItHint::CreateInsertion(End, "]");
9720   }
9721 }
9722 
9723 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9724 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9725                                            ExprResult &RHS, SourceLocation Loc,
9726                                            BinaryOperatorKind Opc) {
9727   // Check that left hand side is !something.
9728   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9729   if (!UO || UO->getOpcode() != UO_LNot) return;
9730 
9731   // Only check if the right hand side is non-bool arithmetic type.
9732   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9733 
9734   // Make sure that the something in !something is not bool.
9735   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9736   if (SubExpr->isKnownToHaveBooleanValue()) return;
9737 
9738   // Emit warning.
9739   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9740   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9741       << Loc << IsBitwiseOp;
9742 
9743   // First note suggest !(x < y)
9744   SourceLocation FirstOpen = SubExpr->getBeginLoc();
9745   SourceLocation FirstClose = RHS.get()->getEndLoc();
9746   FirstClose = S.getLocForEndOfToken(FirstClose);
9747   if (FirstClose.isInvalid())
9748     FirstOpen = SourceLocation();
9749   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9750       << IsBitwiseOp
9751       << FixItHint::CreateInsertion(FirstOpen, "(")
9752       << FixItHint::CreateInsertion(FirstClose, ")");
9753 
9754   // Second note suggests (!x) < y
9755   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9756   SourceLocation SecondClose = LHS.get()->getEndLoc();
9757   SecondClose = S.getLocForEndOfToken(SecondClose);
9758   if (SecondClose.isInvalid())
9759     SecondOpen = SourceLocation();
9760   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9761       << FixItHint::CreateInsertion(SecondOpen, "(")
9762       << FixItHint::CreateInsertion(SecondClose, ")");
9763 }
9764 
9765 // Get the decl for a simple expression: a reference to a variable,
9766 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9767 static ValueDecl *getCompareDecl(Expr *E) {
9768   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9769     return DR->getDecl();
9770   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9771     if (Ivar->isFreeIvar())
9772       return Ivar->getDecl();
9773   }
9774   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9775     if (Mem->isImplicitAccess())
9776       return Mem->getMemberDecl();
9777   }
9778   return nullptr;
9779 }
9780 
9781 /// Diagnose some forms of syntactically-obvious tautological comparison.
9782 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9783                                            Expr *LHS, Expr *RHS,
9784                                            BinaryOperatorKind Opc) {
9785   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9786   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9787 
9788   QualType LHSType = LHS->getType();
9789   QualType RHSType = RHS->getType();
9790   if (LHSType->hasFloatingRepresentation() ||
9791       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9792       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9793       S.inTemplateInstantiation())
9794     return;
9795 
9796   // Comparisons between two array types are ill-formed for operator<=>, so
9797   // we shouldn't emit any additional warnings about it.
9798   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9799     return;
9800 
9801   // For non-floating point types, check for self-comparisons of the form
9802   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9803   // often indicate logic errors in the program.
9804   //
9805   // NOTE: Don't warn about comparison expressions resulting from macro
9806   // expansion. Also don't warn about comparisons which are only self
9807   // comparisons within a template instantiation. The warnings should catch
9808   // obvious cases in the definition of the template anyways. The idea is to
9809   // warn when the typed comparison operator will always evaluate to the same
9810   // result.
9811   ValueDecl *DL = getCompareDecl(LHSStripped);
9812   ValueDecl *DR = getCompareDecl(RHSStripped);
9813   if (DL && DR && declaresSameEntity(DL, DR)) {
9814     StringRef Result;
9815     switch (Opc) {
9816     case BO_EQ: case BO_LE: case BO_GE:
9817       Result = "true";
9818       break;
9819     case BO_NE: case BO_LT: case BO_GT:
9820       Result = "false";
9821       break;
9822     case BO_Cmp:
9823       Result = "'std::strong_ordering::equal'";
9824       break;
9825     default:
9826       break;
9827     }
9828     S.DiagRuntimeBehavior(Loc, nullptr,
9829                           S.PDiag(diag::warn_comparison_always)
9830                               << 0 /*self-comparison*/ << !Result.empty()
9831                               << Result);
9832   } else if (DL && DR &&
9833              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9834              !DL->isWeak() && !DR->isWeak()) {
9835     // What is it always going to evaluate to?
9836     StringRef Result;
9837     switch(Opc) {
9838     case BO_EQ: // e.g. array1 == array2
9839       Result = "false";
9840       break;
9841     case BO_NE: // e.g. array1 != array2
9842       Result = "true";
9843       break;
9844     default: // e.g. array1 <= array2
9845       // The best we can say is 'a constant'
9846       break;
9847     }
9848     S.DiagRuntimeBehavior(Loc, nullptr,
9849                           S.PDiag(diag::warn_comparison_always)
9850                               << 1 /*array comparison*/
9851                               << !Result.empty() << Result);
9852   }
9853 
9854   if (isa<CastExpr>(LHSStripped))
9855     LHSStripped = LHSStripped->IgnoreParenCasts();
9856   if (isa<CastExpr>(RHSStripped))
9857     RHSStripped = RHSStripped->IgnoreParenCasts();
9858 
9859   // Warn about comparisons against a string constant (unless the other
9860   // operand is null); the user probably wants strcmp.
9861   Expr *LiteralString = nullptr;
9862   Expr *LiteralStringStripped = nullptr;
9863   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9864       !RHSStripped->isNullPointerConstant(S.Context,
9865                                           Expr::NPC_ValueDependentIsNull)) {
9866     LiteralString = LHS;
9867     LiteralStringStripped = LHSStripped;
9868   } else if ((isa<StringLiteral>(RHSStripped) ||
9869               isa<ObjCEncodeExpr>(RHSStripped)) &&
9870              !LHSStripped->isNullPointerConstant(S.Context,
9871                                           Expr::NPC_ValueDependentIsNull)) {
9872     LiteralString = RHS;
9873     LiteralStringStripped = RHSStripped;
9874   }
9875 
9876   if (LiteralString) {
9877     S.DiagRuntimeBehavior(Loc, nullptr,
9878                           S.PDiag(diag::warn_stringcompare)
9879                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9880                               << LiteralString->getSourceRange());
9881   }
9882 }
9883 
9884 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9885   switch (CK) {
9886   default: {
9887 #ifndef NDEBUG
9888     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9889                  << "\n";
9890 #endif
9891     llvm_unreachable("unhandled cast kind");
9892   }
9893   case CK_UserDefinedConversion:
9894     return ICK_Identity;
9895   case CK_LValueToRValue:
9896     return ICK_Lvalue_To_Rvalue;
9897   case CK_ArrayToPointerDecay:
9898     return ICK_Array_To_Pointer;
9899   case CK_FunctionToPointerDecay:
9900     return ICK_Function_To_Pointer;
9901   case CK_IntegralCast:
9902     return ICK_Integral_Conversion;
9903   case CK_FloatingCast:
9904     return ICK_Floating_Conversion;
9905   case CK_IntegralToFloating:
9906   case CK_FloatingToIntegral:
9907     return ICK_Floating_Integral;
9908   case CK_IntegralComplexCast:
9909   case CK_FloatingComplexCast:
9910   case CK_FloatingComplexToIntegralComplex:
9911   case CK_IntegralComplexToFloatingComplex:
9912     return ICK_Complex_Conversion;
9913   case CK_FloatingComplexToReal:
9914   case CK_FloatingRealToComplex:
9915   case CK_IntegralComplexToReal:
9916   case CK_IntegralRealToComplex:
9917     return ICK_Complex_Real;
9918   }
9919 }
9920 
9921 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9922                                              QualType FromType,
9923                                              SourceLocation Loc) {
9924   // Check for a narrowing implicit conversion.
9925   StandardConversionSequence SCS;
9926   SCS.setAsIdentityConversion();
9927   SCS.setToType(0, FromType);
9928   SCS.setToType(1, ToType);
9929   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9930     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9931 
9932   APValue PreNarrowingValue;
9933   QualType PreNarrowingType;
9934   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9935                                PreNarrowingType,
9936                                /*IgnoreFloatToIntegralConversion*/ true)) {
9937   case NK_Dependent_Narrowing:
9938     // Implicit conversion to a narrower type, but the expression is
9939     // value-dependent so we can't tell whether it's actually narrowing.
9940   case NK_Not_Narrowing:
9941     return false;
9942 
9943   case NK_Constant_Narrowing:
9944     // Implicit conversion to a narrower type, and the value is not a constant
9945     // expression.
9946     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
9947         << /*Constant*/ 1
9948         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9949     return true;
9950 
9951   case NK_Variable_Narrowing:
9952     // Implicit conversion to a narrower type, and the value is not a constant
9953     // expression.
9954   case NK_Type_Narrowing:
9955     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
9956         << /*Constant*/ 0 << FromType << ToType;
9957     // TODO: It's not a constant expression, but what if the user intended it
9958     // to be? Can we produce notes to help them figure out why it isn't?
9959     return true;
9960   }
9961   llvm_unreachable("unhandled case in switch");
9962 }
9963 
9964 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9965                                                          ExprResult &LHS,
9966                                                          ExprResult &RHS,
9967                                                          SourceLocation Loc) {
9968   using CCT = ComparisonCategoryType;
9969 
9970   QualType LHSType = LHS.get()->getType();
9971   QualType RHSType = RHS.get()->getType();
9972   // Dig out the original argument type and expression before implicit casts
9973   // were applied. These are the types/expressions we need to check the
9974   // [expr.spaceship] requirements against.
9975   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9976   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9977   QualType LHSStrippedType = LHSStripped.get()->getType();
9978   QualType RHSStrippedType = RHSStripped.get()->getType();
9979 
9980   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9981   // other is not, the program is ill-formed.
9982   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9983     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9984     return QualType();
9985   }
9986 
9987   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9988                     RHSStrippedType->isEnumeralType();
9989   if (NumEnumArgs == 1) {
9990     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9991     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9992     if (OtherTy->hasFloatingRepresentation()) {
9993       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9994       return QualType();
9995     }
9996   }
9997   if (NumEnumArgs == 2) {
9998     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9999     // type E, the operator yields the result of converting the operands
10000     // to the underlying type of E and applying <=> to the converted operands.
10001     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10002       S.InvalidOperands(Loc, LHS, RHS);
10003       return QualType();
10004     }
10005     QualType IntType =
10006         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10007     assert(IntType->isArithmeticType());
10008 
10009     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10010     // promote the boolean type, and all other promotable integer types, to
10011     // avoid this.
10012     if (IntType->isPromotableIntegerType())
10013       IntType = S.Context.getPromotedIntegerType(IntType);
10014 
10015     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10016     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10017     LHSType = RHSType = IntType;
10018   }
10019 
10020   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10021   // usual arithmetic conversions are applied to the operands.
10022   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10023   if (LHS.isInvalid() || RHS.isInvalid())
10024     return QualType();
10025   if (Type.isNull())
10026     return S.InvalidOperands(Loc, LHS, RHS);
10027   assert(Type->isArithmeticType() || Type->isEnumeralType());
10028 
10029   bool HasNarrowing = checkThreeWayNarrowingConversion(
10030       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10031   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10032                                                    RHS.get()->getBeginLoc());
10033   if (HasNarrowing)
10034     return QualType();
10035 
10036   assert(!Type.isNull() && "composite type for <=> has not been set");
10037 
10038   auto TypeKind = [&]() {
10039     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10040       if (CT->getElementType()->hasFloatingRepresentation())
10041         return CCT::WeakEquality;
10042       return CCT::StrongEquality;
10043     }
10044     if (Type->isIntegralOrEnumerationType())
10045       return CCT::StrongOrdering;
10046     if (Type->hasFloatingRepresentation())
10047       return CCT::PartialOrdering;
10048     llvm_unreachable("other types are unimplemented");
10049   }();
10050 
10051   return S.CheckComparisonCategoryType(TypeKind, Loc);
10052 }
10053 
10054 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10055                                                  ExprResult &RHS,
10056                                                  SourceLocation Loc,
10057                                                  BinaryOperatorKind Opc) {
10058   if (Opc == BO_Cmp)
10059     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10060 
10061   // C99 6.5.8p3 / C99 6.5.9p4
10062   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10063   if (LHS.isInvalid() || RHS.isInvalid())
10064     return QualType();
10065   if (Type.isNull())
10066     return S.InvalidOperands(Loc, LHS, RHS);
10067   assert(Type->isArithmeticType() || Type->isEnumeralType());
10068 
10069   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10070 
10071   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10072     return S.InvalidOperands(Loc, LHS, RHS);
10073 
10074   // Check for comparisons of floating point operands using != and ==.
10075   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10076     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10077 
10078   // The result of comparisons is 'bool' in C++, 'int' in C.
10079   return S.Context.getLogicalOperationType();
10080 }
10081 
10082 // C99 6.5.8, C++ [expr.rel]
10083 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10084                                     SourceLocation Loc,
10085                                     BinaryOperatorKind Opc) {
10086   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10087   bool IsThreeWay = Opc == BO_Cmp;
10088   auto IsAnyPointerType = [](ExprResult E) {
10089     QualType Ty = E.get()->getType();
10090     return Ty->isPointerType() || Ty->isMemberPointerType();
10091   };
10092 
10093   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10094   // type, array-to-pointer, ..., conversions are performed on both operands to
10095   // bring them to their composite type.
10096   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10097   // any type-related checks.
10098   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10099     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10100     if (LHS.isInvalid())
10101       return QualType();
10102     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10103     if (RHS.isInvalid())
10104       return QualType();
10105   } else {
10106     LHS = DefaultLvalueConversion(LHS.get());
10107     if (LHS.isInvalid())
10108       return QualType();
10109     RHS = DefaultLvalueConversion(RHS.get());
10110     if (RHS.isInvalid())
10111       return QualType();
10112   }
10113 
10114   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10115 
10116   // Handle vector comparisons separately.
10117   if (LHS.get()->getType()->isVectorType() ||
10118       RHS.get()->getType()->isVectorType())
10119     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10120 
10121   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10122   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10123 
10124   QualType LHSType = LHS.get()->getType();
10125   QualType RHSType = RHS.get()->getType();
10126   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10127       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10128     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10129 
10130   const Expr::NullPointerConstantKind LHSNullKind =
10131       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10132   const Expr::NullPointerConstantKind RHSNullKind =
10133       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10134   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10135   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10136 
10137   auto computeResultTy = [&]() {
10138     if (Opc != BO_Cmp)
10139       return Context.getLogicalOperationType();
10140     assert(getLangOpts().CPlusPlus);
10141     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10142 
10143     QualType CompositeTy = LHS.get()->getType();
10144     assert(!CompositeTy->isReferenceType());
10145 
10146     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10147       return CheckComparisonCategoryType(Kind, Loc);
10148     };
10149 
10150     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10151     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10152     // result is of type std::strong_equality
10153     if (CompositeTy->isFunctionPointerType() ||
10154         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10155       // FIXME: consider making the function pointer case produce
10156       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10157       // and direction polls
10158       return buildResultTy(ComparisonCategoryType::StrongEquality);
10159 
10160     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10161     // pointer type, p <=> q is of type std::strong_ordering.
10162     if (CompositeTy->isPointerType()) {
10163       // P0946R0: Comparisons between a null pointer constant and an object
10164       // pointer result in std::strong_equality
10165       if (LHSIsNull != RHSIsNull)
10166         return buildResultTy(ComparisonCategoryType::StrongEquality);
10167       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10168     }
10169     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10170     // TODO: Extend support for operator<=> to ObjC types.
10171     return InvalidOperands(Loc, LHS, RHS);
10172   };
10173 
10174 
10175   if (!IsRelational && LHSIsNull != RHSIsNull) {
10176     bool IsEquality = Opc == BO_EQ;
10177     if (RHSIsNull)
10178       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10179                                    RHS.get()->getSourceRange());
10180     else
10181       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10182                                    LHS.get()->getSourceRange());
10183   }
10184 
10185   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10186       (RHSType->isIntegerType() && !RHSIsNull)) {
10187     // Skip normal pointer conversion checks in this case; we have better
10188     // diagnostics for this below.
10189   } else if (getLangOpts().CPlusPlus) {
10190     // Equality comparison of a function pointer to a void pointer is invalid,
10191     // but we allow it as an extension.
10192     // FIXME: If we really want to allow this, should it be part of composite
10193     // pointer type computation so it works in conditionals too?
10194     if (!IsRelational &&
10195         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10196          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10197       // This is a gcc extension compatibility comparison.
10198       // In a SFINAE context, we treat this as a hard error to maintain
10199       // conformance with the C++ standard.
10200       diagnoseFunctionPointerToVoidComparison(
10201           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10202 
10203       if (isSFINAEContext())
10204         return QualType();
10205 
10206       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10207       return computeResultTy();
10208     }
10209 
10210     // C++ [expr.eq]p2:
10211     //   If at least one operand is a pointer [...] bring them to their
10212     //   composite pointer type.
10213     // C++ [expr.spaceship]p6
10214     //  If at least one of the operands is of pointer type, [...] bring them
10215     //  to their composite pointer type.
10216     // C++ [expr.rel]p2:
10217     //   If both operands are pointers, [...] bring them to their composite
10218     //   pointer type.
10219     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10220             (IsRelational ? 2 : 1) &&
10221         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10222                                          RHSType->isObjCObjectPointerType()))) {
10223       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10224         return QualType();
10225       return computeResultTy();
10226     }
10227   } else if (LHSType->isPointerType() &&
10228              RHSType->isPointerType()) { // C99 6.5.8p2
10229     // All of the following pointer-related warnings are GCC extensions, except
10230     // when handling null pointer constants.
10231     QualType LCanPointeeTy =
10232       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10233     QualType RCanPointeeTy =
10234       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10235 
10236     // C99 6.5.9p2 and C99 6.5.8p2
10237     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10238                                    RCanPointeeTy.getUnqualifiedType())) {
10239       // Valid unless a relational comparison of function pointers
10240       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10241         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10242           << LHSType << RHSType << LHS.get()->getSourceRange()
10243           << RHS.get()->getSourceRange();
10244       }
10245     } else if (!IsRelational &&
10246                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10247       // Valid unless comparison between non-null pointer and function pointer
10248       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10249           && !LHSIsNull && !RHSIsNull)
10250         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10251                                                 /*isError*/false);
10252     } else {
10253       // Invalid
10254       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10255     }
10256     if (LCanPointeeTy != RCanPointeeTy) {
10257       // Treat NULL constant as a special case in OpenCL.
10258       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10259         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10260         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10261           Diag(Loc,
10262                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10263               << LHSType << RHSType << 0 /* comparison */
10264               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10265         }
10266       }
10267       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10268       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10269       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10270                                                : CK_BitCast;
10271       if (LHSIsNull && !RHSIsNull)
10272         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10273       else
10274         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10275     }
10276     return computeResultTy();
10277   }
10278 
10279   if (getLangOpts().CPlusPlus) {
10280     // C++ [expr.eq]p4:
10281     //   Two operands of type std::nullptr_t or one operand of type
10282     //   std::nullptr_t and the other a null pointer constant compare equal.
10283     if (!IsRelational && LHSIsNull && RHSIsNull) {
10284       if (LHSType->isNullPtrType()) {
10285         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10286         return computeResultTy();
10287       }
10288       if (RHSType->isNullPtrType()) {
10289         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10290         return computeResultTy();
10291       }
10292     }
10293 
10294     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10295     // These aren't covered by the composite pointer type rules.
10296     if (!IsRelational && RHSType->isNullPtrType() &&
10297         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10298       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10299       return computeResultTy();
10300     }
10301     if (!IsRelational && LHSType->isNullPtrType() &&
10302         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10303       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10304       return computeResultTy();
10305     }
10306 
10307     if (IsRelational &&
10308         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10309          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10310       // HACK: Relational comparison of nullptr_t against a pointer type is
10311       // invalid per DR583, but we allow it within std::less<> and friends,
10312       // since otherwise common uses of it break.
10313       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10314       // friends to have std::nullptr_t overload candidates.
10315       DeclContext *DC = CurContext;
10316       if (isa<FunctionDecl>(DC))
10317         DC = DC->getParent();
10318       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10319         if (CTSD->isInStdNamespace() &&
10320             llvm::StringSwitch<bool>(CTSD->getName())
10321                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10322                 .Default(false)) {
10323           if (RHSType->isNullPtrType())
10324             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10325           else
10326             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10327           return computeResultTy();
10328         }
10329       }
10330     }
10331 
10332     // C++ [expr.eq]p2:
10333     //   If at least one operand is a pointer to member, [...] bring them to
10334     //   their composite pointer type.
10335     if (!IsRelational &&
10336         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10337       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10338         return QualType();
10339       else
10340         return computeResultTy();
10341     }
10342   }
10343 
10344   // Handle block pointer types.
10345   if (!IsRelational && LHSType->isBlockPointerType() &&
10346       RHSType->isBlockPointerType()) {
10347     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10348     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10349 
10350     if (!LHSIsNull && !RHSIsNull &&
10351         !Context.typesAreCompatible(lpointee, rpointee)) {
10352       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10353         << LHSType << RHSType << LHS.get()->getSourceRange()
10354         << RHS.get()->getSourceRange();
10355     }
10356     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10357     return computeResultTy();
10358   }
10359 
10360   // Allow block pointers to be compared with null pointer constants.
10361   if (!IsRelational
10362       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10363           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10364     if (!LHSIsNull && !RHSIsNull) {
10365       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10366              ->getPointeeType()->isVoidType())
10367             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10368                 ->getPointeeType()->isVoidType())))
10369         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10370           << LHSType << RHSType << LHS.get()->getSourceRange()
10371           << RHS.get()->getSourceRange();
10372     }
10373     if (LHSIsNull && !RHSIsNull)
10374       LHS = ImpCastExprToType(LHS.get(), RHSType,
10375                               RHSType->isPointerType() ? CK_BitCast
10376                                 : CK_AnyPointerToBlockPointerCast);
10377     else
10378       RHS = ImpCastExprToType(RHS.get(), LHSType,
10379                               LHSType->isPointerType() ? CK_BitCast
10380                                 : CK_AnyPointerToBlockPointerCast);
10381     return computeResultTy();
10382   }
10383 
10384   if (LHSType->isObjCObjectPointerType() ||
10385       RHSType->isObjCObjectPointerType()) {
10386     const PointerType *LPT = LHSType->getAs<PointerType>();
10387     const PointerType *RPT = RHSType->getAs<PointerType>();
10388     if (LPT || RPT) {
10389       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10390       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10391 
10392       if (!LPtrToVoid && !RPtrToVoid &&
10393           !Context.typesAreCompatible(LHSType, RHSType)) {
10394         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10395                                           /*isError*/false);
10396       }
10397       if (LHSIsNull && !RHSIsNull) {
10398         Expr *E = LHS.get();
10399         if (getLangOpts().ObjCAutoRefCount)
10400           CheckObjCConversion(SourceRange(), RHSType, E,
10401                               CCK_ImplicitConversion);
10402         LHS = ImpCastExprToType(E, RHSType,
10403                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10404       }
10405       else {
10406         Expr *E = RHS.get();
10407         if (getLangOpts().ObjCAutoRefCount)
10408           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10409                               /*Diagnose=*/true,
10410                               /*DiagnoseCFAudited=*/false, Opc);
10411         RHS = ImpCastExprToType(E, LHSType,
10412                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10413       }
10414       return computeResultTy();
10415     }
10416     if (LHSType->isObjCObjectPointerType() &&
10417         RHSType->isObjCObjectPointerType()) {
10418       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10419         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10420                                           /*isError*/false);
10421       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10422         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10423 
10424       if (LHSIsNull && !RHSIsNull)
10425         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10426       else
10427         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10428       return computeResultTy();
10429     }
10430 
10431     if (!IsRelational && LHSType->isBlockPointerType() &&
10432         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10433       LHS = ImpCastExprToType(LHS.get(), RHSType,
10434                               CK_BlockPointerToObjCPointerCast);
10435       return computeResultTy();
10436     } else if (!IsRelational &&
10437                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10438                RHSType->isBlockPointerType()) {
10439       RHS = ImpCastExprToType(RHS.get(), LHSType,
10440                               CK_BlockPointerToObjCPointerCast);
10441       return computeResultTy();
10442     }
10443   }
10444   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10445       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10446     unsigned DiagID = 0;
10447     bool isError = false;
10448     if (LangOpts.DebuggerSupport) {
10449       // Under a debugger, allow the comparison of pointers to integers,
10450       // since users tend to want to compare addresses.
10451     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10452                (RHSIsNull && RHSType->isIntegerType())) {
10453       if (IsRelational) {
10454         isError = getLangOpts().CPlusPlus;
10455         DiagID =
10456           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10457                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10458       }
10459     } else if (getLangOpts().CPlusPlus) {
10460       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10461       isError = true;
10462     } else if (IsRelational)
10463       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10464     else
10465       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10466 
10467     if (DiagID) {
10468       Diag(Loc, DiagID)
10469         << LHSType << RHSType << LHS.get()->getSourceRange()
10470         << RHS.get()->getSourceRange();
10471       if (isError)
10472         return QualType();
10473     }
10474 
10475     if (LHSType->isIntegerType())
10476       LHS = ImpCastExprToType(LHS.get(), RHSType,
10477                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10478     else
10479       RHS = ImpCastExprToType(RHS.get(), LHSType,
10480                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10481     return computeResultTy();
10482   }
10483 
10484   // Handle block pointers.
10485   if (!IsRelational && RHSIsNull
10486       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10487     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10488     return computeResultTy();
10489   }
10490   if (!IsRelational && LHSIsNull
10491       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10492     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10493     return computeResultTy();
10494   }
10495 
10496   if (getLangOpts().OpenCLVersion >= 200) {
10497     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10498       return computeResultTy();
10499     }
10500 
10501     if (LHSIsNull && RHSType->isQueueT()) {
10502       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10503       return computeResultTy();
10504     }
10505 
10506     if (LHSType->isQueueT() && RHSIsNull) {
10507       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10508       return computeResultTy();
10509     }
10510   }
10511 
10512   return InvalidOperands(Loc, LHS, RHS);
10513 }
10514 
10515 // Return a signed ext_vector_type that is of identical size and number of
10516 // elements. For floating point vectors, return an integer type of identical
10517 // size and number of elements. In the non ext_vector_type case, search from
10518 // the largest type to the smallest type to avoid cases where long long == long,
10519 // where long gets picked over long long.
10520 QualType Sema::GetSignedVectorType(QualType V) {
10521   const VectorType *VTy = V->getAs<VectorType>();
10522   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10523 
10524   if (isa<ExtVectorType>(VTy)) {
10525     if (TypeSize == Context.getTypeSize(Context.CharTy))
10526       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10527     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10528       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10529     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10530       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10531     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10532       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10533     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10534            "Unhandled vector element size in vector compare");
10535     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10536   }
10537 
10538   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10539     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10540                                  VectorType::GenericVector);
10541   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10542     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10543                                  VectorType::GenericVector);
10544   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10545     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10546                                  VectorType::GenericVector);
10547   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10548     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10549                                  VectorType::GenericVector);
10550   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10551          "Unhandled vector element size in vector compare");
10552   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10553                                VectorType::GenericVector);
10554 }
10555 
10556 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10557 /// operates on extended vector types.  Instead of producing an IntTy result,
10558 /// like a scalar comparison, a vector comparison produces a vector of integer
10559 /// types.
10560 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10561                                           SourceLocation Loc,
10562                                           BinaryOperatorKind Opc) {
10563   // Check to make sure we're operating on vectors of the same type and width,
10564   // Allowing one side to be a scalar of element type.
10565   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10566                               /*AllowBothBool*/true,
10567                               /*AllowBoolConversions*/getLangOpts().ZVector);
10568   if (vType.isNull())
10569     return vType;
10570 
10571   QualType LHSType = LHS.get()->getType();
10572 
10573   // If AltiVec, the comparison results in a numeric type, i.e.
10574   // bool for C++, int for C
10575   if (getLangOpts().AltiVec &&
10576       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10577     return Context.getLogicalOperationType();
10578 
10579   // For non-floating point types, check for self-comparisons of the form
10580   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10581   // often indicate logic errors in the program.
10582   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10583 
10584   // Check for comparisons of floating point operands using != and ==.
10585   if (BinaryOperator::isEqualityOp(Opc) &&
10586       LHSType->hasFloatingRepresentation()) {
10587     assert(RHS.get()->getType()->hasFloatingRepresentation());
10588     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10589   }
10590 
10591   // Return a signed type for the vector.
10592   return GetSignedVectorType(vType);
10593 }
10594 
10595 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10596                                           SourceLocation Loc) {
10597   // Ensure that either both operands are of the same vector type, or
10598   // one operand is of a vector type and the other is of its element type.
10599   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10600                                        /*AllowBothBool*/true,
10601                                        /*AllowBoolConversions*/false);
10602   if (vType.isNull())
10603     return InvalidOperands(Loc, LHS, RHS);
10604   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10605       vType->hasFloatingRepresentation())
10606     return InvalidOperands(Loc, LHS, RHS);
10607   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10608   //        usage of the logical operators && and || with vectors in C. This
10609   //        check could be notionally dropped.
10610   if (!getLangOpts().CPlusPlus &&
10611       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10612     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10613 
10614   return GetSignedVectorType(LHS.get()->getType());
10615 }
10616 
10617 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10618                                            SourceLocation Loc,
10619                                            BinaryOperatorKind Opc) {
10620   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10621 
10622   bool IsCompAssign =
10623       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10624 
10625   if (LHS.get()->getType()->isVectorType() ||
10626       RHS.get()->getType()->isVectorType()) {
10627     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10628         RHS.get()->getType()->hasIntegerRepresentation())
10629       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10630                         /*AllowBothBool*/true,
10631                         /*AllowBoolConversions*/getLangOpts().ZVector);
10632     return InvalidOperands(Loc, LHS, RHS);
10633   }
10634 
10635   if (Opc == BO_And)
10636     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10637 
10638   ExprResult LHSResult = LHS, RHSResult = RHS;
10639   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10640                                                  IsCompAssign);
10641   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10642     return QualType();
10643   LHS = LHSResult.get();
10644   RHS = RHSResult.get();
10645 
10646   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10647     return compType;
10648   return InvalidOperands(Loc, LHS, RHS);
10649 }
10650 
10651 // C99 6.5.[13,14]
10652 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10653                                            SourceLocation Loc,
10654                                            BinaryOperatorKind Opc) {
10655   // Check vector operands differently.
10656   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10657     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10658 
10659   // Diagnose cases where the user write a logical and/or but probably meant a
10660   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10661   // is a constant.
10662   if (LHS.get()->getType()->isIntegerType() &&
10663       !LHS.get()->getType()->isBooleanType() &&
10664       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10665       // Don't warn in macros or template instantiations.
10666       !Loc.isMacroID() && !inTemplateInstantiation()) {
10667     // If the RHS can be constant folded, and if it constant folds to something
10668     // that isn't 0 or 1 (which indicate a potential logical operation that
10669     // happened to fold to true/false) then warn.
10670     // Parens on the RHS are ignored.
10671     llvm::APSInt Result;
10672     if (RHS.get()->EvaluateAsInt(Result, Context))
10673       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10674            !RHS.get()->getExprLoc().isMacroID()) ||
10675           (Result != 0 && Result != 1)) {
10676         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10677           << RHS.get()->getSourceRange()
10678           << (Opc == BO_LAnd ? "&&" : "||");
10679         // Suggest replacing the logical operator with the bitwise version
10680         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10681             << (Opc == BO_LAnd ? "&" : "|")
10682             << FixItHint::CreateReplacement(SourceRange(
10683                                                  Loc, getLocForEndOfToken(Loc)),
10684                                             Opc == BO_LAnd ? "&" : "|");
10685         if (Opc == BO_LAnd)
10686           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10687           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10688               << FixItHint::CreateRemoval(
10689                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10690                                  RHS.get()->getEndLoc()));
10691       }
10692   }
10693 
10694   if (!Context.getLangOpts().CPlusPlus) {
10695     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10696     // not operate on the built-in scalar and vector float types.
10697     if (Context.getLangOpts().OpenCL &&
10698         Context.getLangOpts().OpenCLVersion < 120) {
10699       if (LHS.get()->getType()->isFloatingType() ||
10700           RHS.get()->getType()->isFloatingType())
10701         return InvalidOperands(Loc, LHS, RHS);
10702     }
10703 
10704     LHS = UsualUnaryConversions(LHS.get());
10705     if (LHS.isInvalid())
10706       return QualType();
10707 
10708     RHS = UsualUnaryConversions(RHS.get());
10709     if (RHS.isInvalid())
10710       return QualType();
10711 
10712     if (!LHS.get()->getType()->isScalarType() ||
10713         !RHS.get()->getType()->isScalarType())
10714       return InvalidOperands(Loc, LHS, RHS);
10715 
10716     return Context.IntTy;
10717   }
10718 
10719   // The following is safe because we only use this method for
10720   // non-overloadable operands.
10721 
10722   // C++ [expr.log.and]p1
10723   // C++ [expr.log.or]p1
10724   // The operands are both contextually converted to type bool.
10725   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10726   if (LHSRes.isInvalid())
10727     return InvalidOperands(Loc, LHS, RHS);
10728   LHS = LHSRes;
10729 
10730   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10731   if (RHSRes.isInvalid())
10732     return InvalidOperands(Loc, LHS, RHS);
10733   RHS = RHSRes;
10734 
10735   // C++ [expr.log.and]p2
10736   // C++ [expr.log.or]p2
10737   // The result is a bool.
10738   return Context.BoolTy;
10739 }
10740 
10741 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10742   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10743   if (!ME) return false;
10744   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10745   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10746       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10747   if (!Base) return false;
10748   return Base->getMethodDecl() != nullptr;
10749 }
10750 
10751 /// Is the given expression (which must be 'const') a reference to a
10752 /// variable which was originally non-const, but which has become
10753 /// 'const' due to being captured within a block?
10754 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10755 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10756   assert(E->isLValue() && E->getType().isConstQualified());
10757   E = E->IgnoreParens();
10758 
10759   // Must be a reference to a declaration from an enclosing scope.
10760   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10761   if (!DRE) return NCCK_None;
10762   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10763 
10764   // The declaration must be a variable which is not declared 'const'.
10765   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10766   if (!var) return NCCK_None;
10767   if (var->getType().isConstQualified()) return NCCK_None;
10768   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10769 
10770   // Decide whether the first capture was for a block or a lambda.
10771   DeclContext *DC = S.CurContext, *Prev = nullptr;
10772   // Decide whether the first capture was for a block or a lambda.
10773   while (DC) {
10774     // For init-capture, it is possible that the variable belongs to the
10775     // template pattern of the current context.
10776     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10777       if (var->isInitCapture() &&
10778           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10779         break;
10780     if (DC == var->getDeclContext())
10781       break;
10782     Prev = DC;
10783     DC = DC->getParent();
10784   }
10785   // Unless we have an init-capture, we've gone one step too far.
10786   if (!var->isInitCapture())
10787     DC = Prev;
10788   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10789 }
10790 
10791 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10792   Ty = Ty.getNonReferenceType();
10793   if (IsDereference && Ty->isPointerType())
10794     Ty = Ty->getPointeeType();
10795   return !Ty.isConstQualified();
10796 }
10797 
10798 // Update err_typecheck_assign_const and note_typecheck_assign_const
10799 // when this enum is changed.
10800 enum {
10801   ConstFunction,
10802   ConstVariable,
10803   ConstMember,
10804   ConstMethod,
10805   NestedConstMember,
10806   ConstUnknown,  // Keep as last element
10807 };
10808 
10809 /// Emit the "read-only variable not assignable" error and print notes to give
10810 /// more information about why the variable is not assignable, such as pointing
10811 /// to the declaration of a const variable, showing that a method is const, or
10812 /// that the function is returning a const reference.
10813 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10814                                     SourceLocation Loc) {
10815   SourceRange ExprRange = E->getSourceRange();
10816 
10817   // Only emit one error on the first const found.  All other consts will emit
10818   // a note to the error.
10819   bool DiagnosticEmitted = false;
10820 
10821   // Track if the current expression is the result of a dereference, and if the
10822   // next checked expression is the result of a dereference.
10823   bool IsDereference = false;
10824   bool NextIsDereference = false;
10825 
10826   // Loop to process MemberExpr chains.
10827   while (true) {
10828     IsDereference = NextIsDereference;
10829 
10830     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10831     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10832       NextIsDereference = ME->isArrow();
10833       const ValueDecl *VD = ME->getMemberDecl();
10834       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10835         // Mutable fields can be modified even if the class is const.
10836         if (Field->isMutable()) {
10837           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10838           break;
10839         }
10840 
10841         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10842           if (!DiagnosticEmitted) {
10843             S.Diag(Loc, diag::err_typecheck_assign_const)
10844                 << ExprRange << ConstMember << false /*static*/ << Field
10845                 << Field->getType();
10846             DiagnosticEmitted = true;
10847           }
10848           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10849               << ConstMember << false /*static*/ << Field << Field->getType()
10850               << Field->getSourceRange();
10851         }
10852         E = ME->getBase();
10853         continue;
10854       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10855         if (VDecl->getType().isConstQualified()) {
10856           if (!DiagnosticEmitted) {
10857             S.Diag(Loc, diag::err_typecheck_assign_const)
10858                 << ExprRange << ConstMember << true /*static*/ << VDecl
10859                 << VDecl->getType();
10860             DiagnosticEmitted = true;
10861           }
10862           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10863               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10864               << VDecl->getSourceRange();
10865         }
10866         // Static fields do not inherit constness from parents.
10867         break;
10868       }
10869       break; // End MemberExpr
10870     } else if (const ArraySubscriptExpr *ASE =
10871                    dyn_cast<ArraySubscriptExpr>(E)) {
10872       E = ASE->getBase()->IgnoreParenImpCasts();
10873       continue;
10874     } else if (const ExtVectorElementExpr *EVE =
10875                    dyn_cast<ExtVectorElementExpr>(E)) {
10876       E = EVE->getBase()->IgnoreParenImpCasts();
10877       continue;
10878     }
10879     break;
10880   }
10881 
10882   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10883     // Function calls
10884     const FunctionDecl *FD = CE->getDirectCallee();
10885     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10886       if (!DiagnosticEmitted) {
10887         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10888                                                       << ConstFunction << FD;
10889         DiagnosticEmitted = true;
10890       }
10891       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10892              diag::note_typecheck_assign_const)
10893           << ConstFunction << FD << FD->getReturnType()
10894           << FD->getReturnTypeSourceRange();
10895     }
10896   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10897     // Point to variable declaration.
10898     if (const ValueDecl *VD = DRE->getDecl()) {
10899       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10900         if (!DiagnosticEmitted) {
10901           S.Diag(Loc, diag::err_typecheck_assign_const)
10902               << ExprRange << ConstVariable << VD << VD->getType();
10903           DiagnosticEmitted = true;
10904         }
10905         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10906             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10907       }
10908     }
10909   } else if (isa<CXXThisExpr>(E)) {
10910     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10911       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10912         if (MD->isConst()) {
10913           if (!DiagnosticEmitted) {
10914             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10915                                                           << ConstMethod << MD;
10916             DiagnosticEmitted = true;
10917           }
10918           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10919               << ConstMethod << MD << MD->getSourceRange();
10920         }
10921       }
10922     }
10923   }
10924 
10925   if (DiagnosticEmitted)
10926     return;
10927 
10928   // Can't determine a more specific message, so display the generic error.
10929   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10930 }
10931 
10932 enum OriginalExprKind {
10933   OEK_Variable,
10934   OEK_Member,
10935   OEK_LValue
10936 };
10937 
10938 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10939                                          const RecordType *Ty,
10940                                          SourceLocation Loc, SourceRange Range,
10941                                          OriginalExprKind OEK,
10942                                          bool &DiagnosticEmitted,
10943                                          bool IsNested = false) {
10944   // We walk the record hierarchy breadth-first to ensure that we print
10945   // diagnostics in field nesting order.
10946   // First, check every field for constness.
10947   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10948     if (Field->getType().isConstQualified()) {
10949       if (!DiagnosticEmitted) {
10950         S.Diag(Loc, diag::err_typecheck_assign_const)
10951             << Range << NestedConstMember << OEK << VD
10952             << IsNested << Field;
10953         DiagnosticEmitted = true;
10954       }
10955       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10956           << NestedConstMember << IsNested << Field
10957           << Field->getType() << Field->getSourceRange();
10958     }
10959   }
10960   // Then, recurse.
10961   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10962     QualType FTy = Field->getType();
10963     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10964       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10965                                    OEK, DiagnosticEmitted, true);
10966   }
10967 }
10968 
10969 /// Emit an error for the case where a record we are trying to assign to has a
10970 /// const-qualified field somewhere in its hierarchy.
10971 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10972                                          SourceLocation Loc) {
10973   QualType Ty = E->getType();
10974   assert(Ty->isRecordType() && "lvalue was not record?");
10975   SourceRange Range = E->getSourceRange();
10976   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10977   bool DiagEmitted = false;
10978 
10979   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10980     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10981             Range, OEK_Member, DiagEmitted);
10982   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10983     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10984             Range, OEK_Variable, DiagEmitted);
10985   else
10986     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10987             Range, OEK_LValue, DiagEmitted);
10988   if (!DiagEmitted)
10989     DiagnoseConstAssignment(S, E, Loc);
10990 }
10991 
10992 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10993 /// emit an error and return true.  If so, return false.
10994 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10995   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10996 
10997   S.CheckShadowingDeclModification(E, Loc);
10998 
10999   SourceLocation OrigLoc = Loc;
11000   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11001                                                               &Loc);
11002   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11003     IsLV = Expr::MLV_InvalidMessageExpression;
11004   if (IsLV == Expr::MLV_Valid)
11005     return false;
11006 
11007   unsigned DiagID = 0;
11008   bool NeedType = false;
11009   switch (IsLV) { // C99 6.5.16p2
11010   case Expr::MLV_ConstQualified:
11011     // Use a specialized diagnostic when we're assigning to an object
11012     // from an enclosing function or block.
11013     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11014       if (NCCK == NCCK_Block)
11015         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11016       else
11017         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11018       break;
11019     }
11020 
11021     // In ARC, use some specialized diagnostics for occasions where we
11022     // infer 'const'.  These are always pseudo-strong variables.
11023     if (S.getLangOpts().ObjCAutoRefCount) {
11024       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11025       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11026         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11027 
11028         // Use the normal diagnostic if it's pseudo-__strong but the
11029         // user actually wrote 'const'.
11030         if (var->isARCPseudoStrong() &&
11031             (!var->getTypeSourceInfo() ||
11032              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11033           // There are two pseudo-strong cases:
11034           //  - self
11035           ObjCMethodDecl *method = S.getCurMethodDecl();
11036           if (method && var == method->getSelfDecl())
11037             DiagID = method->isClassMethod()
11038               ? diag::err_typecheck_arc_assign_self_class_method
11039               : diag::err_typecheck_arc_assign_self;
11040 
11041           //  - fast enumeration variables
11042           else
11043             DiagID = diag::err_typecheck_arr_assign_enumeration;
11044 
11045           SourceRange Assign;
11046           if (Loc != OrigLoc)
11047             Assign = SourceRange(OrigLoc, OrigLoc);
11048           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11049           // We need to preserve the AST regardless, so migration tool
11050           // can do its job.
11051           return false;
11052         }
11053       }
11054     }
11055 
11056     // If none of the special cases above are triggered, then this is a
11057     // simple const assignment.
11058     if (DiagID == 0) {
11059       DiagnoseConstAssignment(S, E, Loc);
11060       return true;
11061     }
11062 
11063     break;
11064   case Expr::MLV_ConstAddrSpace:
11065     DiagnoseConstAssignment(S, E, Loc);
11066     return true;
11067   case Expr::MLV_ConstQualifiedField:
11068     DiagnoseRecursiveConstFields(S, E, Loc);
11069     return true;
11070   case Expr::MLV_ArrayType:
11071   case Expr::MLV_ArrayTemporary:
11072     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11073     NeedType = true;
11074     break;
11075   case Expr::MLV_NotObjectType:
11076     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11077     NeedType = true;
11078     break;
11079   case Expr::MLV_LValueCast:
11080     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11081     break;
11082   case Expr::MLV_Valid:
11083     llvm_unreachable("did not take early return for MLV_Valid");
11084   case Expr::MLV_InvalidExpression:
11085   case Expr::MLV_MemberFunction:
11086   case Expr::MLV_ClassTemporary:
11087     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11088     break;
11089   case Expr::MLV_IncompleteType:
11090   case Expr::MLV_IncompleteVoidType:
11091     return S.RequireCompleteType(Loc, E->getType(),
11092              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11093   case Expr::MLV_DuplicateVectorComponents:
11094     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11095     break;
11096   case Expr::MLV_NoSetterProperty:
11097     llvm_unreachable("readonly properties should be processed differently");
11098   case Expr::MLV_InvalidMessageExpression:
11099     DiagID = diag::err_readonly_message_assignment;
11100     break;
11101   case Expr::MLV_SubObjCPropertySetting:
11102     DiagID = diag::err_no_subobject_property_setting;
11103     break;
11104   }
11105 
11106   SourceRange Assign;
11107   if (Loc != OrigLoc)
11108     Assign = SourceRange(OrigLoc, OrigLoc);
11109   if (NeedType)
11110     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11111   else
11112     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11113   return true;
11114 }
11115 
11116 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11117                                          SourceLocation Loc,
11118                                          Sema &Sema) {
11119   if (Sema.inTemplateInstantiation())
11120     return;
11121   if (Sema.isUnevaluatedContext())
11122     return;
11123   if (Loc.isInvalid() || Loc.isMacroID())
11124     return;
11125   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11126     return;
11127 
11128   // C / C++ fields
11129   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11130   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11131   if (ML && MR) {
11132     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11133       return;
11134     const ValueDecl *LHSDecl =
11135         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11136     const ValueDecl *RHSDecl =
11137         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11138     if (LHSDecl != RHSDecl)
11139       return;
11140     if (LHSDecl->getType().isVolatileQualified())
11141       return;
11142     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11143       if (RefTy->getPointeeType().isVolatileQualified())
11144         return;
11145 
11146     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11147   }
11148 
11149   // Objective-C instance variables
11150   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11151   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11152   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11153     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11154     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11155     if (RL && RR && RL->getDecl() == RR->getDecl())
11156       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11157   }
11158 }
11159 
11160 // C99 6.5.16.1
11161 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11162                                        SourceLocation Loc,
11163                                        QualType CompoundType) {
11164   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11165 
11166   // Verify that LHS is a modifiable lvalue, and emit error if not.
11167   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11168     return QualType();
11169 
11170   QualType LHSType = LHSExpr->getType();
11171   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11172                                              CompoundType;
11173   // OpenCL v1.2 s6.1.1.1 p2:
11174   // The half data type can only be used to declare a pointer to a buffer that
11175   // contains half values
11176   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11177     LHSType->isHalfType()) {
11178     Diag(Loc, diag::err_opencl_half_load_store) << 1
11179         << LHSType.getUnqualifiedType();
11180     return QualType();
11181   }
11182 
11183   AssignConvertType ConvTy;
11184   if (CompoundType.isNull()) {
11185     Expr *RHSCheck = RHS.get();
11186 
11187     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11188 
11189     QualType LHSTy(LHSType);
11190     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11191     if (RHS.isInvalid())
11192       return QualType();
11193     // Special case of NSObject attributes on c-style pointer types.
11194     if (ConvTy == IncompatiblePointer &&
11195         ((Context.isObjCNSObjectType(LHSType) &&
11196           RHSType->isObjCObjectPointerType()) ||
11197          (Context.isObjCNSObjectType(RHSType) &&
11198           LHSType->isObjCObjectPointerType())))
11199       ConvTy = Compatible;
11200 
11201     if (ConvTy == Compatible &&
11202         LHSType->isObjCObjectType())
11203         Diag(Loc, diag::err_objc_object_assignment)
11204           << LHSType;
11205 
11206     // If the RHS is a unary plus or minus, check to see if they = and + are
11207     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11208     // instead of "x += 4".
11209     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11210       RHSCheck = ICE->getSubExpr();
11211     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11212       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11213           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11214           // Only if the two operators are exactly adjacent.
11215           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11216           // And there is a space or other character before the subexpr of the
11217           // unary +/-.  We don't want to warn on "x=-1".
11218           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11219           UO->getSubExpr()->getBeginLoc().isFileID()) {
11220         Diag(Loc, diag::warn_not_compound_assign)
11221           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11222           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11223       }
11224     }
11225 
11226     if (ConvTy == Compatible) {
11227       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11228         // Warn about retain cycles where a block captures the LHS, but
11229         // not if the LHS is a simple variable into which the block is
11230         // being stored...unless that variable can be captured by reference!
11231         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11232         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11233         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11234           checkRetainCycles(LHSExpr, RHS.get());
11235       }
11236 
11237       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11238           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11239         // It is safe to assign a weak reference into a strong variable.
11240         // Although this code can still have problems:
11241         //   id x = self.weakProp;
11242         //   id y = self.weakProp;
11243         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11244         // paths through the function. This should be revisited if
11245         // -Wrepeated-use-of-weak is made flow-sensitive.
11246         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11247         // variable, which will be valid for the current autorelease scope.
11248         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11249                              RHS.get()->getBeginLoc()))
11250           getCurFunction()->markSafeWeakUse(RHS.get());
11251 
11252       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11253         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11254       }
11255     }
11256   } else {
11257     // Compound assignment "x += y"
11258     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11259   }
11260 
11261   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11262                                RHS.get(), AA_Assigning))
11263     return QualType();
11264 
11265   CheckForNullPointerDereference(*this, LHSExpr);
11266 
11267   // C99 6.5.16p3: The type of an assignment expression is the type of the
11268   // left operand unless the left operand has qualified type, in which case
11269   // it is the unqualified version of the type of the left operand.
11270   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11271   // is converted to the type of the assignment expression (above).
11272   // C++ 5.17p1: the type of the assignment expression is that of its left
11273   // operand.
11274   return (getLangOpts().CPlusPlus
11275           ? LHSType : LHSType.getUnqualifiedType());
11276 }
11277 
11278 // Only ignore explicit casts to void.
11279 static bool IgnoreCommaOperand(const Expr *E) {
11280   E = E->IgnoreParens();
11281 
11282   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11283     if (CE->getCastKind() == CK_ToVoid) {
11284       return true;
11285     }
11286   }
11287 
11288   return false;
11289 }
11290 
11291 // Look for instances where it is likely the comma operator is confused with
11292 // another operator.  There is a whitelist of acceptable expressions for the
11293 // left hand side of the comma operator, otherwise emit a warning.
11294 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11295   // No warnings in macros
11296   if (Loc.isMacroID())
11297     return;
11298 
11299   // Don't warn in template instantiations.
11300   if (inTemplateInstantiation())
11301     return;
11302 
11303   // Scope isn't fine-grained enough to whitelist the specific cases, so
11304   // instead, skip more than needed, then call back into here with the
11305   // CommaVisitor in SemaStmt.cpp.
11306   // The whitelisted locations are the initialization and increment portions
11307   // of a for loop.  The additional checks are on the condition of
11308   // if statements, do/while loops, and for loops.
11309   const unsigned ForIncrementFlags =
11310       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11311   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11312   const unsigned ScopeFlags = getCurScope()->getFlags();
11313   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11314       (ScopeFlags & ForInitFlags) == ForInitFlags)
11315     return;
11316 
11317   // If there are multiple comma operators used together, get the RHS of the
11318   // of the comma operator as the LHS.
11319   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11320     if (BO->getOpcode() != BO_Comma)
11321       break;
11322     LHS = BO->getRHS();
11323   }
11324 
11325   // Only allow some expressions on LHS to not warn.
11326   if (IgnoreCommaOperand(LHS))
11327     return;
11328 
11329   Diag(Loc, diag::warn_comma_operator);
11330   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11331       << LHS->getSourceRange()
11332       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11333                                     LangOpts.CPlusPlus ? "static_cast<void>("
11334                                                        : "(void)(")
11335       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11336                                     ")");
11337 }
11338 
11339 // C99 6.5.17
11340 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11341                                    SourceLocation Loc) {
11342   LHS = S.CheckPlaceholderExpr(LHS.get());
11343   RHS = S.CheckPlaceholderExpr(RHS.get());
11344   if (LHS.isInvalid() || RHS.isInvalid())
11345     return QualType();
11346 
11347   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11348   // operands, but not unary promotions.
11349   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11350 
11351   // So we treat the LHS as a ignored value, and in C++ we allow the
11352   // containing site to determine what should be done with the RHS.
11353   LHS = S.IgnoredValueConversions(LHS.get());
11354   if (LHS.isInvalid())
11355     return QualType();
11356 
11357   S.DiagnoseUnusedExprResult(LHS.get());
11358 
11359   if (!S.getLangOpts().CPlusPlus) {
11360     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11361     if (RHS.isInvalid())
11362       return QualType();
11363     if (!RHS.get()->getType()->isVoidType())
11364       S.RequireCompleteType(Loc, RHS.get()->getType(),
11365                             diag::err_incomplete_type);
11366   }
11367 
11368   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11369     S.DiagnoseCommaOperator(LHS.get(), Loc);
11370 
11371   return RHS.get()->getType();
11372 }
11373 
11374 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11375 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11376 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11377                                                ExprValueKind &VK,
11378                                                ExprObjectKind &OK,
11379                                                SourceLocation OpLoc,
11380                                                bool IsInc, bool IsPrefix) {
11381   if (Op->isTypeDependent())
11382     return S.Context.DependentTy;
11383 
11384   QualType ResType = Op->getType();
11385   // Atomic types can be used for increment / decrement where the non-atomic
11386   // versions can, so ignore the _Atomic() specifier for the purpose of
11387   // checking.
11388   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11389     ResType = ResAtomicType->getValueType();
11390 
11391   assert(!ResType.isNull() && "no type for increment/decrement expression");
11392 
11393   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11394     // Decrement of bool is not allowed.
11395     if (!IsInc) {
11396       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11397       return QualType();
11398     }
11399     // Increment of bool sets it to true, but is deprecated.
11400     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11401                                               : diag::warn_increment_bool)
11402       << Op->getSourceRange();
11403   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11404     // Error on enum increments and decrements in C++ mode
11405     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11406     return QualType();
11407   } else if (ResType->isRealType()) {
11408     // OK!
11409   } else if (ResType->isPointerType()) {
11410     // C99 6.5.2.4p2, 6.5.6p2
11411     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11412       return QualType();
11413   } else if (ResType->isObjCObjectPointerType()) {
11414     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11415     // Otherwise, we just need a complete type.
11416     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11417         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11418       return QualType();
11419   } else if (ResType->isAnyComplexType()) {
11420     // C99 does not support ++/-- on complex types, we allow as an extension.
11421     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11422       << ResType << Op->getSourceRange();
11423   } else if (ResType->isPlaceholderType()) {
11424     ExprResult PR = S.CheckPlaceholderExpr(Op);
11425     if (PR.isInvalid()) return QualType();
11426     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11427                                           IsInc, IsPrefix);
11428   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11429     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11430   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11431              (ResType->getAs<VectorType>()->getVectorKind() !=
11432               VectorType::AltiVecBool)) {
11433     // The z vector extensions allow ++ and -- for non-bool vectors.
11434   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11435             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11436     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11437   } else {
11438     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11439       << ResType << int(IsInc) << Op->getSourceRange();
11440     return QualType();
11441   }
11442   // At this point, we know we have a real, complex or pointer type.
11443   // Now make sure the operand is a modifiable lvalue.
11444   if (CheckForModifiableLvalue(Op, OpLoc, S))
11445     return QualType();
11446   // In C++, a prefix increment is the same type as the operand. Otherwise
11447   // (in C or with postfix), the increment is the unqualified type of the
11448   // operand.
11449   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11450     VK = VK_LValue;
11451     OK = Op->getObjectKind();
11452     return ResType;
11453   } else {
11454     VK = VK_RValue;
11455     return ResType.getUnqualifiedType();
11456   }
11457 }
11458 
11459 
11460 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11461 /// This routine allows us to typecheck complex/recursive expressions
11462 /// where the declaration is needed for type checking. We only need to
11463 /// handle cases when the expression references a function designator
11464 /// or is an lvalue. Here are some examples:
11465 ///  - &(x) => x
11466 ///  - &*****f => f for f a function designator.
11467 ///  - &s.xx => s
11468 ///  - &s.zz[1].yy -> s, if zz is an array
11469 ///  - *(x + 1) -> x, if x is an array
11470 ///  - &"123"[2] -> 0
11471 ///  - & __real__ x -> x
11472 static ValueDecl *getPrimaryDecl(Expr *E) {
11473   switch (E->getStmtClass()) {
11474   case Stmt::DeclRefExprClass:
11475     return cast<DeclRefExpr>(E)->getDecl();
11476   case Stmt::MemberExprClass:
11477     // If this is an arrow operator, the address is an offset from
11478     // the base's value, so the object the base refers to is
11479     // irrelevant.
11480     if (cast<MemberExpr>(E)->isArrow())
11481       return nullptr;
11482     // Otherwise, the expression refers to a part of the base
11483     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11484   case Stmt::ArraySubscriptExprClass: {
11485     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11486     // promotion of register arrays earlier.
11487     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11488     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11489       if (ICE->getSubExpr()->getType()->isArrayType())
11490         return getPrimaryDecl(ICE->getSubExpr());
11491     }
11492     return nullptr;
11493   }
11494   case Stmt::UnaryOperatorClass: {
11495     UnaryOperator *UO = cast<UnaryOperator>(E);
11496 
11497     switch(UO->getOpcode()) {
11498     case UO_Real:
11499     case UO_Imag:
11500     case UO_Extension:
11501       return getPrimaryDecl(UO->getSubExpr());
11502     default:
11503       return nullptr;
11504     }
11505   }
11506   case Stmt::ParenExprClass:
11507     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11508   case Stmt::ImplicitCastExprClass:
11509     // If the result of an implicit cast is an l-value, we care about
11510     // the sub-expression; otherwise, the result here doesn't matter.
11511     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11512   default:
11513     return nullptr;
11514   }
11515 }
11516 
11517 namespace {
11518   enum {
11519     AO_Bit_Field = 0,
11520     AO_Vector_Element = 1,
11521     AO_Property_Expansion = 2,
11522     AO_Register_Variable = 3,
11523     AO_No_Error = 4
11524   };
11525 }
11526 /// Diagnose invalid operand for address of operations.
11527 ///
11528 /// \param Type The type of operand which cannot have its address taken.
11529 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11530                                          Expr *E, unsigned Type) {
11531   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11532 }
11533 
11534 /// CheckAddressOfOperand - The operand of & must be either a function
11535 /// designator or an lvalue designating an object. If it is an lvalue, the
11536 /// object cannot be declared with storage class register or be a bit field.
11537 /// Note: The usual conversions are *not* applied to the operand of the &
11538 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11539 /// In C++, the operand might be an overloaded function name, in which case
11540 /// we allow the '&' but retain the overloaded-function type.
11541 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11542   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11543     if (PTy->getKind() == BuiltinType::Overload) {
11544       Expr *E = OrigOp.get()->IgnoreParens();
11545       if (!isa<OverloadExpr>(E)) {
11546         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11547         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11548           << OrigOp.get()->getSourceRange();
11549         return QualType();
11550       }
11551 
11552       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11553       if (isa<UnresolvedMemberExpr>(Ovl))
11554         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11555           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11556             << OrigOp.get()->getSourceRange();
11557           return QualType();
11558         }
11559 
11560       return Context.OverloadTy;
11561     }
11562 
11563     if (PTy->getKind() == BuiltinType::UnknownAny)
11564       return Context.UnknownAnyTy;
11565 
11566     if (PTy->getKind() == BuiltinType::BoundMember) {
11567       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11568         << OrigOp.get()->getSourceRange();
11569       return QualType();
11570     }
11571 
11572     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11573     if (OrigOp.isInvalid()) return QualType();
11574   }
11575 
11576   if (OrigOp.get()->isTypeDependent())
11577     return Context.DependentTy;
11578 
11579   assert(!OrigOp.get()->getType()->isPlaceholderType());
11580 
11581   // Make sure to ignore parentheses in subsequent checks
11582   Expr *op = OrigOp.get()->IgnoreParens();
11583 
11584   // In OpenCL captures for blocks called as lambda functions
11585   // are located in the private address space. Blocks used in
11586   // enqueue_kernel can be located in a different address space
11587   // depending on a vendor implementation. Thus preventing
11588   // taking an address of the capture to avoid invalid AS casts.
11589   if (LangOpts.OpenCL) {
11590     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11591     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11592       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11593       return QualType();
11594     }
11595   }
11596 
11597   if (getLangOpts().C99) {
11598     // Implement C99-only parts of addressof rules.
11599     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11600       if (uOp->getOpcode() == UO_Deref)
11601         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11602         // (assuming the deref expression is valid).
11603         return uOp->getSubExpr()->getType();
11604     }
11605     // Technically, there should be a check for array subscript
11606     // expressions here, but the result of one is always an lvalue anyway.
11607   }
11608   ValueDecl *dcl = getPrimaryDecl(op);
11609 
11610   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11611     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11612                                            op->getBeginLoc()))
11613       return QualType();
11614 
11615   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11616   unsigned AddressOfError = AO_No_Error;
11617 
11618   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11619     bool sfinae = (bool)isSFINAEContext();
11620     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11621                                   : diag::ext_typecheck_addrof_temporary)
11622       << op->getType() << op->getSourceRange();
11623     if (sfinae)
11624       return QualType();
11625     // Materialize the temporary as an lvalue so that we can take its address.
11626     OrigOp = op =
11627         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11628   } else if (isa<ObjCSelectorExpr>(op)) {
11629     return Context.getPointerType(op->getType());
11630   } else if (lval == Expr::LV_MemberFunction) {
11631     // If it's an instance method, make a member pointer.
11632     // The expression must have exactly the form &A::foo.
11633 
11634     // If the underlying expression isn't a decl ref, give up.
11635     if (!isa<DeclRefExpr>(op)) {
11636       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11637         << OrigOp.get()->getSourceRange();
11638       return QualType();
11639     }
11640     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11641     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11642 
11643     // The id-expression was parenthesized.
11644     if (OrigOp.get() != DRE) {
11645       Diag(OpLoc, diag::err_parens_pointer_member_function)
11646         << OrigOp.get()->getSourceRange();
11647 
11648     // The method was named without a qualifier.
11649     } else if (!DRE->getQualifier()) {
11650       if (MD->getParent()->getName().empty())
11651         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11652           << op->getSourceRange();
11653       else {
11654         SmallString<32> Str;
11655         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11656         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11657           << op->getSourceRange()
11658           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11659       }
11660     }
11661 
11662     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11663     if (isa<CXXDestructorDecl>(MD))
11664       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11665 
11666     QualType MPTy = Context.getMemberPointerType(
11667         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11668     // Under the MS ABI, lock down the inheritance model now.
11669     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11670       (void)isCompleteType(OpLoc, MPTy);
11671     return MPTy;
11672   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11673     // C99 6.5.3.2p1
11674     // The operand must be either an l-value or a function designator
11675     if (!op->getType()->isFunctionType()) {
11676       // Use a special diagnostic for loads from property references.
11677       if (isa<PseudoObjectExpr>(op)) {
11678         AddressOfError = AO_Property_Expansion;
11679       } else {
11680         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11681           << op->getType() << op->getSourceRange();
11682         return QualType();
11683       }
11684     }
11685   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11686     // The operand cannot be a bit-field
11687     AddressOfError = AO_Bit_Field;
11688   } else if (op->getObjectKind() == OK_VectorComponent) {
11689     // The operand cannot be an element of a vector
11690     AddressOfError = AO_Vector_Element;
11691   } else if (dcl) { // C99 6.5.3.2p1
11692     // We have an lvalue with a decl. Make sure the decl is not declared
11693     // with the register storage-class specifier.
11694     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11695       // in C++ it is not error to take address of a register
11696       // variable (c++03 7.1.1P3)
11697       if (vd->getStorageClass() == SC_Register &&
11698           !getLangOpts().CPlusPlus) {
11699         AddressOfError = AO_Register_Variable;
11700       }
11701     } else if (isa<MSPropertyDecl>(dcl)) {
11702       AddressOfError = AO_Property_Expansion;
11703     } else if (isa<FunctionTemplateDecl>(dcl)) {
11704       return Context.OverloadTy;
11705     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11706       // Okay: we can take the address of a field.
11707       // Could be a pointer to member, though, if there is an explicit
11708       // scope qualifier for the class.
11709       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11710         DeclContext *Ctx = dcl->getDeclContext();
11711         if (Ctx && Ctx->isRecord()) {
11712           if (dcl->getType()->isReferenceType()) {
11713             Diag(OpLoc,
11714                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11715               << dcl->getDeclName() << dcl->getType();
11716             return QualType();
11717           }
11718 
11719           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11720             Ctx = Ctx->getParent();
11721 
11722           QualType MPTy = Context.getMemberPointerType(
11723               op->getType(),
11724               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11725           // Under the MS ABI, lock down the inheritance model now.
11726           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11727             (void)isCompleteType(OpLoc, MPTy);
11728           return MPTy;
11729         }
11730       }
11731     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11732                !isa<BindingDecl>(dcl))
11733       llvm_unreachable("Unknown/unexpected decl type");
11734   }
11735 
11736   if (AddressOfError != AO_No_Error) {
11737     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11738     return QualType();
11739   }
11740 
11741   if (lval == Expr::LV_IncompleteVoidType) {
11742     // Taking the address of a void variable is technically illegal, but we
11743     // allow it in cases which are otherwise valid.
11744     // Example: "extern void x; void* y = &x;".
11745     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11746   }
11747 
11748   // If the operand has type "type", the result has type "pointer to type".
11749   if (op->getType()->isObjCObjectType())
11750     return Context.getObjCObjectPointerType(op->getType());
11751 
11752   CheckAddressOfPackedMember(op);
11753 
11754   return Context.getPointerType(op->getType());
11755 }
11756 
11757 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11758   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11759   if (!DRE)
11760     return;
11761   const Decl *D = DRE->getDecl();
11762   if (!D)
11763     return;
11764   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11765   if (!Param)
11766     return;
11767   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11768     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11769       return;
11770   if (FunctionScopeInfo *FD = S.getCurFunction())
11771     if (!FD->ModifiedNonNullParams.count(Param))
11772       FD->ModifiedNonNullParams.insert(Param);
11773 }
11774 
11775 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11776 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11777                                         SourceLocation OpLoc) {
11778   if (Op->isTypeDependent())
11779     return S.Context.DependentTy;
11780 
11781   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11782   if (ConvResult.isInvalid())
11783     return QualType();
11784   Op = ConvResult.get();
11785   QualType OpTy = Op->getType();
11786   QualType Result;
11787 
11788   if (isa<CXXReinterpretCastExpr>(Op)) {
11789     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11790     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11791                                      Op->getSourceRange());
11792   }
11793 
11794   if (const PointerType *PT = OpTy->getAs<PointerType>())
11795   {
11796     Result = PT->getPointeeType();
11797   }
11798   else if (const ObjCObjectPointerType *OPT =
11799              OpTy->getAs<ObjCObjectPointerType>())
11800     Result = OPT->getPointeeType();
11801   else {
11802     ExprResult PR = S.CheckPlaceholderExpr(Op);
11803     if (PR.isInvalid()) return QualType();
11804     if (PR.get() != Op)
11805       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11806   }
11807 
11808   if (Result.isNull()) {
11809     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11810       << OpTy << Op->getSourceRange();
11811     return QualType();
11812   }
11813 
11814   // Note that per both C89 and C99, indirection is always legal, even if Result
11815   // is an incomplete type or void.  It would be possible to warn about
11816   // dereferencing a void pointer, but it's completely well-defined, and such a
11817   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11818   // for pointers to 'void' but is fine for any other pointer type:
11819   //
11820   // C++ [expr.unary.op]p1:
11821   //   [...] the expression to which [the unary * operator] is applied shall
11822   //   be a pointer to an object type, or a pointer to a function type
11823   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11824     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11825       << OpTy << Op->getSourceRange();
11826 
11827   // Dereferences are usually l-values...
11828   VK = VK_LValue;
11829 
11830   // ...except that certain expressions are never l-values in C.
11831   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11832     VK = VK_RValue;
11833 
11834   return Result;
11835 }
11836 
11837 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11838   BinaryOperatorKind Opc;
11839   switch (Kind) {
11840   default: llvm_unreachable("Unknown binop!");
11841   case tok::periodstar:           Opc = BO_PtrMemD; break;
11842   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11843   case tok::star:                 Opc = BO_Mul; break;
11844   case tok::slash:                Opc = BO_Div; break;
11845   case tok::percent:              Opc = BO_Rem; break;
11846   case tok::plus:                 Opc = BO_Add; break;
11847   case tok::minus:                Opc = BO_Sub; break;
11848   case tok::lessless:             Opc = BO_Shl; break;
11849   case tok::greatergreater:       Opc = BO_Shr; break;
11850   case tok::lessequal:            Opc = BO_LE; break;
11851   case tok::less:                 Opc = BO_LT; break;
11852   case tok::greaterequal:         Opc = BO_GE; break;
11853   case tok::greater:              Opc = BO_GT; break;
11854   case tok::exclaimequal:         Opc = BO_NE; break;
11855   case tok::equalequal:           Opc = BO_EQ; break;
11856   case tok::spaceship:            Opc = BO_Cmp; break;
11857   case tok::amp:                  Opc = BO_And; break;
11858   case tok::caret:                Opc = BO_Xor; break;
11859   case tok::pipe:                 Opc = BO_Or; break;
11860   case tok::ampamp:               Opc = BO_LAnd; break;
11861   case tok::pipepipe:             Opc = BO_LOr; break;
11862   case tok::equal:                Opc = BO_Assign; break;
11863   case tok::starequal:            Opc = BO_MulAssign; break;
11864   case tok::slashequal:           Opc = BO_DivAssign; break;
11865   case tok::percentequal:         Opc = BO_RemAssign; break;
11866   case tok::plusequal:            Opc = BO_AddAssign; break;
11867   case tok::minusequal:           Opc = BO_SubAssign; break;
11868   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11869   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11870   case tok::ampequal:             Opc = BO_AndAssign; break;
11871   case tok::caretequal:           Opc = BO_XorAssign; break;
11872   case tok::pipeequal:            Opc = BO_OrAssign; break;
11873   case tok::comma:                Opc = BO_Comma; break;
11874   }
11875   return Opc;
11876 }
11877 
11878 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11879   tok::TokenKind Kind) {
11880   UnaryOperatorKind Opc;
11881   switch (Kind) {
11882   default: llvm_unreachable("Unknown unary op!");
11883   case tok::plusplus:     Opc = UO_PreInc; break;
11884   case tok::minusminus:   Opc = UO_PreDec; break;
11885   case tok::amp:          Opc = UO_AddrOf; break;
11886   case tok::star:         Opc = UO_Deref; break;
11887   case tok::plus:         Opc = UO_Plus; break;
11888   case tok::minus:        Opc = UO_Minus; break;
11889   case tok::tilde:        Opc = UO_Not; break;
11890   case tok::exclaim:      Opc = UO_LNot; break;
11891   case tok::kw___real:    Opc = UO_Real; break;
11892   case tok::kw___imag:    Opc = UO_Imag; break;
11893   case tok::kw___extension__: Opc = UO_Extension; break;
11894   }
11895   return Opc;
11896 }
11897 
11898 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11899 /// This warning suppressed in the event of macro expansions.
11900 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11901                                    SourceLocation OpLoc, bool IsBuiltin) {
11902   if (S.inTemplateInstantiation())
11903     return;
11904   if (S.isUnevaluatedContext())
11905     return;
11906   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11907     return;
11908   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11909   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11910   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11911   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11912   if (!LHSDeclRef || !RHSDeclRef ||
11913       LHSDeclRef->getLocation().isMacroID() ||
11914       RHSDeclRef->getLocation().isMacroID())
11915     return;
11916   const ValueDecl *LHSDecl =
11917     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11918   const ValueDecl *RHSDecl =
11919     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11920   if (LHSDecl != RHSDecl)
11921     return;
11922   if (LHSDecl->getType().isVolatileQualified())
11923     return;
11924   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11925     if (RefTy->getPointeeType().isVolatileQualified())
11926       return;
11927 
11928   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11929                           : diag::warn_self_assignment_overloaded)
11930       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11931       << RHSExpr->getSourceRange();
11932 }
11933 
11934 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11935 /// is usually indicative of introspection within the Objective-C pointer.
11936 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11937                                           SourceLocation OpLoc) {
11938   if (!S.getLangOpts().ObjC1)
11939     return;
11940 
11941   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11942   const Expr *LHS = L.get();
11943   const Expr *RHS = R.get();
11944 
11945   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11946     ObjCPointerExpr = LHS;
11947     OtherExpr = RHS;
11948   }
11949   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11950     ObjCPointerExpr = RHS;
11951     OtherExpr = LHS;
11952   }
11953 
11954   // This warning is deliberately made very specific to reduce false
11955   // positives with logic that uses '&' for hashing.  This logic mainly
11956   // looks for code trying to introspect into tagged pointers, which
11957   // code should generally never do.
11958   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11959     unsigned Diag = diag::warn_objc_pointer_masking;
11960     // Determine if we are introspecting the result of performSelectorXXX.
11961     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11962     // Special case messages to -performSelector and friends, which
11963     // can return non-pointer values boxed in a pointer value.
11964     // Some clients may wish to silence warnings in this subcase.
11965     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11966       Selector S = ME->getSelector();
11967       StringRef SelArg0 = S.getNameForSlot(0);
11968       if (SelArg0.startswith("performSelector"))
11969         Diag = diag::warn_objc_pointer_masking_performSelector;
11970     }
11971 
11972     S.Diag(OpLoc, Diag)
11973       << ObjCPointerExpr->getSourceRange();
11974   }
11975 }
11976 
11977 static NamedDecl *getDeclFromExpr(Expr *E) {
11978   if (!E)
11979     return nullptr;
11980   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11981     return DRE->getDecl();
11982   if (auto *ME = dyn_cast<MemberExpr>(E))
11983     return ME->getMemberDecl();
11984   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11985     return IRE->getDecl();
11986   return nullptr;
11987 }
11988 
11989 // This helper function promotes a binary operator's operands (which are of a
11990 // half vector type) to a vector of floats and then truncates the result to
11991 // a vector of either half or short.
11992 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11993                                       BinaryOperatorKind Opc, QualType ResultTy,
11994                                       ExprValueKind VK, ExprObjectKind OK,
11995                                       bool IsCompAssign, SourceLocation OpLoc,
11996                                       FPOptions FPFeatures) {
11997   auto &Context = S.getASTContext();
11998   assert((isVector(ResultTy, Context.HalfTy) ||
11999           isVector(ResultTy, Context.ShortTy)) &&
12000          "Result must be a vector of half or short");
12001   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12002          isVector(RHS.get()->getType(), Context.HalfTy) &&
12003          "both operands expected to be a half vector");
12004 
12005   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12006   QualType BinOpResTy = RHS.get()->getType();
12007 
12008   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12009   // change BinOpResTy to a vector of ints.
12010   if (isVector(ResultTy, Context.ShortTy))
12011     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12012 
12013   if (IsCompAssign)
12014     return new (Context) CompoundAssignOperator(
12015         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12016         OpLoc, FPFeatures);
12017 
12018   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12019   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12020                                           VK, OK, OpLoc, FPFeatures);
12021   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12022 }
12023 
12024 static std::pair<ExprResult, ExprResult>
12025 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12026                            Expr *RHSExpr) {
12027   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12028   if (!S.getLangOpts().CPlusPlus) {
12029     // C cannot handle TypoExpr nodes on either side of a binop because it
12030     // doesn't handle dependent types properly, so make sure any TypoExprs have
12031     // been dealt with before checking the operands.
12032     LHS = S.CorrectDelayedTyposInExpr(LHS);
12033     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12034       if (Opc != BO_Assign)
12035         return ExprResult(E);
12036       // Avoid correcting the RHS to the same Expr as the LHS.
12037       Decl *D = getDeclFromExpr(E);
12038       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12039     });
12040   }
12041   return std::make_pair(LHS, RHS);
12042 }
12043 
12044 /// Returns true if conversion between vectors of halfs and vectors of floats
12045 /// is needed.
12046 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12047                                      QualType SrcType) {
12048   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12049          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12050          isVector(SrcType, Ctx.HalfTy);
12051 }
12052 
12053 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12054 /// operator @p Opc at location @c TokLoc. This routine only supports
12055 /// built-in operations; ActOnBinOp handles overloaded operators.
12056 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12057                                     BinaryOperatorKind Opc,
12058                                     Expr *LHSExpr, Expr *RHSExpr) {
12059   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12060     // The syntax only allows initializer lists on the RHS of assignment,
12061     // so we don't need to worry about accepting invalid code for
12062     // non-assignment operators.
12063     // C++11 5.17p9:
12064     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12065     //   of x = {} is x = T().
12066     InitializationKind Kind = InitializationKind::CreateDirectList(
12067         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12068     InitializedEntity Entity =
12069         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12070     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12071     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12072     if (Init.isInvalid())
12073       return Init;
12074     RHSExpr = Init.get();
12075   }
12076 
12077   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12078   QualType ResultTy;     // Result type of the binary operator.
12079   // The following two variables are used for compound assignment operators
12080   QualType CompLHSTy;    // Type of LHS after promotions for computation
12081   QualType CompResultTy; // Type of computation result
12082   ExprValueKind VK = VK_RValue;
12083   ExprObjectKind OK = OK_Ordinary;
12084   bool ConvertHalfVec = false;
12085 
12086   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12087   if (!LHS.isUsable() || !RHS.isUsable())
12088     return ExprError();
12089 
12090   if (getLangOpts().OpenCL) {
12091     QualType LHSTy = LHSExpr->getType();
12092     QualType RHSTy = RHSExpr->getType();
12093     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12094     // the ATOMIC_VAR_INIT macro.
12095     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12096       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12097       if (BO_Assign == Opc)
12098         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12099       else
12100         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12101       return ExprError();
12102     }
12103 
12104     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12105     // only with a builtin functions and therefore should be disallowed here.
12106     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12107         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12108         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12109         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12110       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12111       return ExprError();
12112     }
12113   }
12114 
12115   switch (Opc) {
12116   case BO_Assign:
12117     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12118     if (getLangOpts().CPlusPlus &&
12119         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12120       VK = LHS.get()->getValueKind();
12121       OK = LHS.get()->getObjectKind();
12122     }
12123     if (!ResultTy.isNull()) {
12124       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12125       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12126     }
12127     RecordModifiableNonNullParam(*this, LHS.get());
12128     break;
12129   case BO_PtrMemD:
12130   case BO_PtrMemI:
12131     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12132                                             Opc == BO_PtrMemI);
12133     break;
12134   case BO_Mul:
12135   case BO_Div:
12136     ConvertHalfVec = true;
12137     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12138                                            Opc == BO_Div);
12139     break;
12140   case BO_Rem:
12141     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12142     break;
12143   case BO_Add:
12144     ConvertHalfVec = true;
12145     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12146     break;
12147   case BO_Sub:
12148     ConvertHalfVec = true;
12149     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12150     break;
12151   case BO_Shl:
12152   case BO_Shr:
12153     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12154     break;
12155   case BO_LE:
12156   case BO_LT:
12157   case BO_GE:
12158   case BO_GT:
12159     ConvertHalfVec = true;
12160     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12161     break;
12162   case BO_EQ:
12163   case BO_NE:
12164     ConvertHalfVec = true;
12165     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12166     break;
12167   case BO_Cmp:
12168     ConvertHalfVec = true;
12169     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12170     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12171     break;
12172   case BO_And:
12173     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12174     LLVM_FALLTHROUGH;
12175   case BO_Xor:
12176   case BO_Or:
12177     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12178     break;
12179   case BO_LAnd:
12180   case BO_LOr:
12181     ConvertHalfVec = true;
12182     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12183     break;
12184   case BO_MulAssign:
12185   case BO_DivAssign:
12186     ConvertHalfVec = true;
12187     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12188                                                Opc == BO_DivAssign);
12189     CompLHSTy = CompResultTy;
12190     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12191       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12192     break;
12193   case BO_RemAssign:
12194     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12195     CompLHSTy = CompResultTy;
12196     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12197       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12198     break;
12199   case BO_AddAssign:
12200     ConvertHalfVec = true;
12201     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12202     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12203       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12204     break;
12205   case BO_SubAssign:
12206     ConvertHalfVec = true;
12207     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12208     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12209       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12210     break;
12211   case BO_ShlAssign:
12212   case BO_ShrAssign:
12213     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12214     CompLHSTy = CompResultTy;
12215     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12216       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12217     break;
12218   case BO_AndAssign:
12219   case BO_OrAssign: // fallthrough
12220     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12221     LLVM_FALLTHROUGH;
12222   case BO_XorAssign:
12223     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12224     CompLHSTy = CompResultTy;
12225     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12226       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12227     break;
12228   case BO_Comma:
12229     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12230     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12231       VK = RHS.get()->getValueKind();
12232       OK = RHS.get()->getObjectKind();
12233     }
12234     break;
12235   }
12236   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12237     return ExprError();
12238 
12239   // Some of the binary operations require promoting operands of half vector to
12240   // float vectors and truncating the result back to half vector. For now, we do
12241   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12242   // arm64).
12243   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12244          isVector(LHS.get()->getType(), Context.HalfTy) &&
12245          "both sides are half vectors or neither sides are");
12246   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12247                                             LHS.get()->getType());
12248 
12249   // Check for array bounds violations for both sides of the BinaryOperator
12250   CheckArrayAccess(LHS.get());
12251   CheckArrayAccess(RHS.get());
12252 
12253   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12254     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12255                                                  &Context.Idents.get("object_setClass"),
12256                                                  SourceLocation(), LookupOrdinaryName);
12257     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12258       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12259       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12260           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12261                                         "object_setClass(")
12262           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12263                                           ",")
12264           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12265     }
12266     else
12267       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12268   }
12269   else if (const ObjCIvarRefExpr *OIRE =
12270            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12271     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12272 
12273   // Opc is not a compound assignment if CompResultTy is null.
12274   if (CompResultTy.isNull()) {
12275     if (ConvertHalfVec)
12276       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12277                                  OpLoc, FPFeatures);
12278     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12279                                         OK, OpLoc, FPFeatures);
12280   }
12281 
12282   // Handle compound assignments.
12283   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12284       OK_ObjCProperty) {
12285     VK = VK_LValue;
12286     OK = LHS.get()->getObjectKind();
12287   }
12288 
12289   if (ConvertHalfVec)
12290     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12291                                OpLoc, FPFeatures);
12292 
12293   return new (Context) CompoundAssignOperator(
12294       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12295       OpLoc, FPFeatures);
12296 }
12297 
12298 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12299 /// operators are mixed in a way that suggests that the programmer forgot that
12300 /// comparison operators have higher precedence. The most typical example of
12301 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12302 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12303                                       SourceLocation OpLoc, Expr *LHSExpr,
12304                                       Expr *RHSExpr) {
12305   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12306   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12307 
12308   // Check that one of the sides is a comparison operator and the other isn't.
12309   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12310   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12311   if (isLeftComp == isRightComp)
12312     return;
12313 
12314   // Bitwise operations are sometimes used as eager logical ops.
12315   // Don't diagnose this.
12316   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12317   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12318   if (isLeftBitwise || isRightBitwise)
12319     return;
12320 
12321   SourceRange DiagRange = isLeftComp
12322                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12323                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12324   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12325   SourceRange ParensRange =
12326       isLeftComp
12327           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12328           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12329 
12330   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12331     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12332   SuggestParentheses(Self, OpLoc,
12333     Self.PDiag(diag::note_precedence_silence) << OpStr,
12334     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12335   SuggestParentheses(Self, OpLoc,
12336     Self.PDiag(diag::note_precedence_bitwise_first)
12337       << BinaryOperator::getOpcodeStr(Opc),
12338     ParensRange);
12339 }
12340 
12341 /// It accepts a '&&' expr that is inside a '||' one.
12342 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12343 /// in parentheses.
12344 static void
12345 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12346                                        BinaryOperator *Bop) {
12347   assert(Bop->getOpcode() == BO_LAnd);
12348   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12349       << Bop->getSourceRange() << OpLoc;
12350   SuggestParentheses(Self, Bop->getOperatorLoc(),
12351     Self.PDiag(diag::note_precedence_silence)
12352       << Bop->getOpcodeStr(),
12353     Bop->getSourceRange());
12354 }
12355 
12356 /// Returns true if the given expression can be evaluated as a constant
12357 /// 'true'.
12358 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12359   bool Res;
12360   return !E->isValueDependent() &&
12361          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12362 }
12363 
12364 /// Returns true if the given expression can be evaluated as a constant
12365 /// 'false'.
12366 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12367   bool Res;
12368   return !E->isValueDependent() &&
12369          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12370 }
12371 
12372 /// Look for '&&' in the left hand of a '||' expr.
12373 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12374                                              Expr *LHSExpr, Expr *RHSExpr) {
12375   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12376     if (Bop->getOpcode() == BO_LAnd) {
12377       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12378       if (EvaluatesAsFalse(S, RHSExpr))
12379         return;
12380       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12381       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12382         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12383     } else if (Bop->getOpcode() == BO_LOr) {
12384       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12385         // If it's "a || b && 1 || c" we didn't warn earlier for
12386         // "a || b && 1", but warn now.
12387         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12388           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12389       }
12390     }
12391   }
12392 }
12393 
12394 /// Look for '&&' in the right hand of a '||' expr.
12395 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12396                                              Expr *LHSExpr, Expr *RHSExpr) {
12397   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12398     if (Bop->getOpcode() == BO_LAnd) {
12399       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12400       if (EvaluatesAsFalse(S, LHSExpr))
12401         return;
12402       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12403       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12404         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12405     }
12406   }
12407 }
12408 
12409 /// Look for bitwise op in the left or right hand of a bitwise op with
12410 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12411 /// the '&' expression in parentheses.
12412 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12413                                          SourceLocation OpLoc, Expr *SubExpr) {
12414   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12415     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12416       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12417         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12418         << Bop->getSourceRange() << OpLoc;
12419       SuggestParentheses(S, Bop->getOperatorLoc(),
12420         S.PDiag(diag::note_precedence_silence)
12421           << Bop->getOpcodeStr(),
12422         Bop->getSourceRange());
12423     }
12424   }
12425 }
12426 
12427 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12428                                     Expr *SubExpr, StringRef Shift) {
12429   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12430     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12431       StringRef Op = Bop->getOpcodeStr();
12432       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12433           << Bop->getSourceRange() << OpLoc << Shift << Op;
12434       SuggestParentheses(S, Bop->getOperatorLoc(),
12435           S.PDiag(diag::note_precedence_silence) << Op,
12436           Bop->getSourceRange());
12437     }
12438   }
12439 }
12440 
12441 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12442                                  Expr *LHSExpr, Expr *RHSExpr) {
12443   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12444   if (!OCE)
12445     return;
12446 
12447   FunctionDecl *FD = OCE->getDirectCallee();
12448   if (!FD || !FD->isOverloadedOperator())
12449     return;
12450 
12451   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12452   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12453     return;
12454 
12455   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12456       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12457       << (Kind == OO_LessLess);
12458   SuggestParentheses(S, OCE->getOperatorLoc(),
12459                      S.PDiag(diag::note_precedence_silence)
12460                          << (Kind == OO_LessLess ? "<<" : ">>"),
12461                      OCE->getSourceRange());
12462   SuggestParentheses(
12463       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12464       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12465 }
12466 
12467 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12468 /// precedence.
12469 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12470                                     SourceLocation OpLoc, Expr *LHSExpr,
12471                                     Expr *RHSExpr){
12472   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12473   if (BinaryOperator::isBitwiseOp(Opc))
12474     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12475 
12476   // Diagnose "arg1 & arg2 | arg3"
12477   if ((Opc == BO_Or || Opc == BO_Xor) &&
12478       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12479     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12480     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12481   }
12482 
12483   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12484   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12485   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12486     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12487     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12488   }
12489 
12490   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12491       || Opc == BO_Shr) {
12492     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12493     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12494     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12495   }
12496 
12497   // Warn on overloaded shift operators and comparisons, such as:
12498   // cout << 5 == 4;
12499   if (BinaryOperator::isComparisonOp(Opc))
12500     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12501 }
12502 
12503 // Binary Operators.  'Tok' is the token for the operator.
12504 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12505                             tok::TokenKind Kind,
12506                             Expr *LHSExpr, Expr *RHSExpr) {
12507   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12508   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12509   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12510 
12511   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12512   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12513 
12514   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12515 }
12516 
12517 /// Build an overloaded binary operator expression in the given scope.
12518 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12519                                        BinaryOperatorKind Opc,
12520                                        Expr *LHS, Expr *RHS) {
12521   switch (Opc) {
12522   case BO_Assign:
12523   case BO_DivAssign:
12524   case BO_RemAssign:
12525   case BO_SubAssign:
12526   case BO_AndAssign:
12527   case BO_OrAssign:
12528   case BO_XorAssign:
12529     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12530     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12531     break;
12532   default:
12533     break;
12534   }
12535 
12536   // Find all of the overloaded operators visible from this
12537   // point. We perform both an operator-name lookup from the local
12538   // scope and an argument-dependent lookup based on the types of
12539   // the arguments.
12540   UnresolvedSet<16> Functions;
12541   OverloadedOperatorKind OverOp
12542     = BinaryOperator::getOverloadedOperator(Opc);
12543   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12544     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12545                                    RHS->getType(), Functions);
12546 
12547   // Build the (potentially-overloaded, potentially-dependent)
12548   // binary operation.
12549   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12550 }
12551 
12552 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12553                             BinaryOperatorKind Opc,
12554                             Expr *LHSExpr, Expr *RHSExpr) {
12555   ExprResult LHS, RHS;
12556   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12557   if (!LHS.isUsable() || !RHS.isUsable())
12558     return ExprError();
12559   LHSExpr = LHS.get();
12560   RHSExpr = RHS.get();
12561 
12562   // We want to end up calling one of checkPseudoObjectAssignment
12563   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12564   // both expressions are overloadable or either is type-dependent),
12565   // or CreateBuiltinBinOp (in any other case).  We also want to get
12566   // any placeholder types out of the way.
12567 
12568   // Handle pseudo-objects in the LHS.
12569   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12570     // Assignments with a pseudo-object l-value need special analysis.
12571     if (pty->getKind() == BuiltinType::PseudoObject &&
12572         BinaryOperator::isAssignmentOp(Opc))
12573       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12574 
12575     // Don't resolve overloads if the other type is overloadable.
12576     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12577       // We can't actually test that if we still have a placeholder,
12578       // though.  Fortunately, none of the exceptions we see in that
12579       // code below are valid when the LHS is an overload set.  Note
12580       // that an overload set can be dependently-typed, but it never
12581       // instantiates to having an overloadable type.
12582       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12583       if (resolvedRHS.isInvalid()) return ExprError();
12584       RHSExpr = resolvedRHS.get();
12585 
12586       if (RHSExpr->isTypeDependent() ||
12587           RHSExpr->getType()->isOverloadableType())
12588         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12589     }
12590 
12591     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12592     // template, diagnose the missing 'template' keyword instead of diagnosing
12593     // an invalid use of a bound member function.
12594     //
12595     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12596     // to C++1z [over.over]/1.4, but we already checked for that case above.
12597     if (Opc == BO_LT && inTemplateInstantiation() &&
12598         (pty->getKind() == BuiltinType::BoundMember ||
12599          pty->getKind() == BuiltinType::Overload)) {
12600       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12601       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12602           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12603             return isa<FunctionTemplateDecl>(ND);
12604           })) {
12605         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12606                                 : OE->getNameLoc(),
12607              diag::err_template_kw_missing)
12608           << OE->getName().getAsString() << "";
12609         return ExprError();
12610       }
12611     }
12612 
12613     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12614     if (LHS.isInvalid()) return ExprError();
12615     LHSExpr = LHS.get();
12616   }
12617 
12618   // Handle pseudo-objects in the RHS.
12619   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12620     // An overload in the RHS can potentially be resolved by the type
12621     // being assigned to.
12622     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12623       if (getLangOpts().CPlusPlus &&
12624           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12625            LHSExpr->getType()->isOverloadableType()))
12626         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12627 
12628       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12629     }
12630 
12631     // Don't resolve overloads if the other type is overloadable.
12632     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12633         LHSExpr->getType()->isOverloadableType())
12634       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12635 
12636     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12637     if (!resolvedRHS.isUsable()) return ExprError();
12638     RHSExpr = resolvedRHS.get();
12639   }
12640 
12641   if (getLangOpts().CPlusPlus) {
12642     // If either expression is type-dependent, always build an
12643     // overloaded op.
12644     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12645       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12646 
12647     // Otherwise, build an overloaded op if either expression has an
12648     // overloadable type.
12649     if (LHSExpr->getType()->isOverloadableType() ||
12650         RHSExpr->getType()->isOverloadableType())
12651       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12652   }
12653 
12654   // Build a built-in binary operation.
12655   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12656 }
12657 
12658 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12659   if (T.isNull() || T->isDependentType())
12660     return false;
12661 
12662   if (!T->isPromotableIntegerType())
12663     return true;
12664 
12665   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12666 }
12667 
12668 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12669                                       UnaryOperatorKind Opc,
12670                                       Expr *InputExpr) {
12671   ExprResult Input = InputExpr;
12672   ExprValueKind VK = VK_RValue;
12673   ExprObjectKind OK = OK_Ordinary;
12674   QualType resultType;
12675   bool CanOverflow = false;
12676 
12677   bool ConvertHalfVec = false;
12678   if (getLangOpts().OpenCL) {
12679     QualType Ty = InputExpr->getType();
12680     // The only legal unary operation for atomics is '&'.
12681     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12682     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12683     // only with a builtin functions and therefore should be disallowed here.
12684         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12685         || Ty->isBlockPointerType())) {
12686       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12687                        << InputExpr->getType()
12688                        << Input.get()->getSourceRange());
12689     }
12690   }
12691   switch (Opc) {
12692   case UO_PreInc:
12693   case UO_PreDec:
12694   case UO_PostInc:
12695   case UO_PostDec:
12696     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12697                                                 OpLoc,
12698                                                 Opc == UO_PreInc ||
12699                                                 Opc == UO_PostInc,
12700                                                 Opc == UO_PreInc ||
12701                                                 Opc == UO_PreDec);
12702     CanOverflow = isOverflowingIntegerType(Context, resultType);
12703     break;
12704   case UO_AddrOf:
12705     resultType = CheckAddressOfOperand(Input, OpLoc);
12706     RecordModifiableNonNullParam(*this, InputExpr);
12707     break;
12708   case UO_Deref: {
12709     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12710     if (Input.isInvalid()) return ExprError();
12711     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12712     break;
12713   }
12714   case UO_Plus:
12715   case UO_Minus:
12716     CanOverflow = Opc == UO_Minus &&
12717                   isOverflowingIntegerType(Context, Input.get()->getType());
12718     Input = UsualUnaryConversions(Input.get());
12719     if (Input.isInvalid()) return ExprError();
12720     // Unary plus and minus require promoting an operand of half vector to a
12721     // float vector and truncating the result back to a half vector. For now, we
12722     // do this only when HalfArgsAndReturns is set (that is, when the target is
12723     // arm or arm64).
12724     ConvertHalfVec =
12725         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12726 
12727     // If the operand is a half vector, promote it to a float vector.
12728     if (ConvertHalfVec)
12729       Input = convertVector(Input.get(), Context.FloatTy, *this);
12730     resultType = Input.get()->getType();
12731     if (resultType->isDependentType())
12732       break;
12733     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12734       break;
12735     else if (resultType->isVectorType() &&
12736              // The z vector extensions don't allow + or - with bool vectors.
12737              (!Context.getLangOpts().ZVector ||
12738               resultType->getAs<VectorType>()->getVectorKind() !=
12739               VectorType::AltiVecBool))
12740       break;
12741     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12742              Opc == UO_Plus &&
12743              resultType->isPointerType())
12744       break;
12745 
12746     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12747       << resultType << Input.get()->getSourceRange());
12748 
12749   case UO_Not: // bitwise complement
12750     Input = UsualUnaryConversions(Input.get());
12751     if (Input.isInvalid())
12752       return ExprError();
12753     resultType = Input.get()->getType();
12754 
12755     if (resultType->isDependentType())
12756       break;
12757     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12758     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12759       // C99 does not support '~' for complex conjugation.
12760       Diag(OpLoc, diag::ext_integer_complement_complex)
12761           << resultType << Input.get()->getSourceRange();
12762     else if (resultType->hasIntegerRepresentation())
12763       break;
12764     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12765       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12766       // on vector float types.
12767       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12768       if (!T->isIntegerType())
12769         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12770                           << resultType << Input.get()->getSourceRange());
12771     } else {
12772       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12773                        << resultType << Input.get()->getSourceRange());
12774     }
12775     break;
12776 
12777   case UO_LNot: // logical negation
12778     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12779     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12780     if (Input.isInvalid()) return ExprError();
12781     resultType = Input.get()->getType();
12782 
12783     // Though we still have to promote half FP to float...
12784     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12785       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12786       resultType = Context.FloatTy;
12787     }
12788 
12789     if (resultType->isDependentType())
12790       break;
12791     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12792       // C99 6.5.3.3p1: ok, fallthrough;
12793       if (Context.getLangOpts().CPlusPlus) {
12794         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12795         // operand contextually converted to bool.
12796         if (resultType->getScalarTypeKind() == Type::STK_FixedPoint) {
12797           return ExprError(
12798               Diag(Input.get()->getExprLoc(),
12799                    diag::err_unimplemented_conversion_with_fixed_point_type)
12800               << resultType);
12801         }
12802         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12803                                   ScalarTypeToBooleanCastKind(resultType));
12804       } else if (Context.getLangOpts().OpenCL &&
12805                  Context.getLangOpts().OpenCLVersion < 120) {
12806         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12807         // operate on scalar float types.
12808         if (!resultType->isIntegerType() && !resultType->isPointerType())
12809           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12810                            << resultType << Input.get()->getSourceRange());
12811       }
12812     } else if (resultType->isExtVectorType()) {
12813       if (Context.getLangOpts().OpenCL &&
12814           Context.getLangOpts().OpenCLVersion < 120) {
12815         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12816         // operate on vector float types.
12817         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12818         if (!T->isIntegerType())
12819           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12820                            << resultType << Input.get()->getSourceRange());
12821       }
12822       // Vector logical not returns the signed variant of the operand type.
12823       resultType = GetSignedVectorType(resultType);
12824       break;
12825     } else {
12826       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12827       //        type in C++. We should allow that here too.
12828       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12829         << resultType << Input.get()->getSourceRange());
12830     }
12831 
12832     // LNot always has type int. C99 6.5.3.3p5.
12833     // In C++, it's bool. C++ 5.3.1p8
12834     resultType = Context.getLogicalOperationType();
12835     break;
12836   case UO_Real:
12837   case UO_Imag:
12838     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12839     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12840     // complex l-values to ordinary l-values and all other values to r-values.
12841     if (Input.isInvalid()) return ExprError();
12842     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12843       if (Input.get()->getValueKind() != VK_RValue &&
12844           Input.get()->getObjectKind() == OK_Ordinary)
12845         VK = Input.get()->getValueKind();
12846     } else if (!getLangOpts().CPlusPlus) {
12847       // In C, a volatile scalar is read by __imag. In C++, it is not.
12848       Input = DefaultLvalueConversion(Input.get());
12849     }
12850     break;
12851   case UO_Extension:
12852     resultType = Input.get()->getType();
12853     VK = Input.get()->getValueKind();
12854     OK = Input.get()->getObjectKind();
12855     break;
12856   case UO_Coawait:
12857     // It's unnecessary to represent the pass-through operator co_await in the
12858     // AST; just return the input expression instead.
12859     assert(!Input.get()->getType()->isDependentType() &&
12860                    "the co_await expression must be non-dependant before "
12861                    "building operator co_await");
12862     return Input;
12863   }
12864   if (resultType.isNull() || Input.isInvalid())
12865     return ExprError();
12866 
12867   // Check for array bounds violations in the operand of the UnaryOperator,
12868   // except for the '*' and '&' operators that have to be handled specially
12869   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12870   // that are explicitly defined as valid by the standard).
12871   if (Opc != UO_AddrOf && Opc != UO_Deref)
12872     CheckArrayAccess(Input.get());
12873 
12874   auto *UO = new (Context)
12875       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12876   // Convert the result back to a half vector.
12877   if (ConvertHalfVec)
12878     return convertVector(UO, Context.HalfTy, *this);
12879   return UO;
12880 }
12881 
12882 /// Determine whether the given expression is a qualified member
12883 /// access expression, of a form that could be turned into a pointer to member
12884 /// with the address-of operator.
12885 bool Sema::isQualifiedMemberAccess(Expr *E) {
12886   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12887     if (!DRE->getQualifier())
12888       return false;
12889 
12890     ValueDecl *VD = DRE->getDecl();
12891     if (!VD->isCXXClassMember())
12892       return false;
12893 
12894     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12895       return true;
12896     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12897       return Method->isInstance();
12898 
12899     return false;
12900   }
12901 
12902   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12903     if (!ULE->getQualifier())
12904       return false;
12905 
12906     for (NamedDecl *D : ULE->decls()) {
12907       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12908         if (Method->isInstance())
12909           return true;
12910       } else {
12911         // Overload set does not contain methods.
12912         break;
12913       }
12914     }
12915 
12916     return false;
12917   }
12918 
12919   return false;
12920 }
12921 
12922 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12923                               UnaryOperatorKind Opc, Expr *Input) {
12924   // First things first: handle placeholders so that the
12925   // overloaded-operator check considers the right type.
12926   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12927     // Increment and decrement of pseudo-object references.
12928     if (pty->getKind() == BuiltinType::PseudoObject &&
12929         UnaryOperator::isIncrementDecrementOp(Opc))
12930       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12931 
12932     // extension is always a builtin operator.
12933     if (Opc == UO_Extension)
12934       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12935 
12936     // & gets special logic for several kinds of placeholder.
12937     // The builtin code knows what to do.
12938     if (Opc == UO_AddrOf &&
12939         (pty->getKind() == BuiltinType::Overload ||
12940          pty->getKind() == BuiltinType::UnknownAny ||
12941          pty->getKind() == BuiltinType::BoundMember))
12942       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12943 
12944     // Anything else needs to be handled now.
12945     ExprResult Result = CheckPlaceholderExpr(Input);
12946     if (Result.isInvalid()) return ExprError();
12947     Input = Result.get();
12948   }
12949 
12950   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12951       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12952       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12953     // Find all of the overloaded operators visible from this
12954     // point. We perform both an operator-name lookup from the local
12955     // scope and an argument-dependent lookup based on the types of
12956     // the arguments.
12957     UnresolvedSet<16> Functions;
12958     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12959     if (S && OverOp != OO_None)
12960       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12961                                    Functions);
12962 
12963     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12964   }
12965 
12966   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12967 }
12968 
12969 // Unary Operators.  'Tok' is the token for the operator.
12970 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12971                               tok::TokenKind Op, Expr *Input) {
12972   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12973 }
12974 
12975 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12976 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12977                                 LabelDecl *TheDecl) {
12978   TheDecl->markUsed(Context);
12979   // Create the AST node.  The address of a label always has type 'void*'.
12980   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12981                                      Context.getPointerType(Context.VoidTy));
12982 }
12983 
12984 /// Given the last statement in a statement-expression, check whether
12985 /// the result is a producing expression (like a call to an
12986 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12987 /// release out of the full-expression.  Otherwise, return null.
12988 /// Cannot fail.
12989 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12990   // Should always be wrapped with one of these.
12991   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12992   if (!cleanups) return nullptr;
12993 
12994   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12995   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12996     return nullptr;
12997 
12998   // Splice out the cast.  This shouldn't modify any interesting
12999   // features of the statement.
13000   Expr *producer = cast->getSubExpr();
13001   assert(producer->getType() == cast->getType());
13002   assert(producer->getValueKind() == cast->getValueKind());
13003   cleanups->setSubExpr(producer);
13004   return cleanups;
13005 }
13006 
13007 void Sema::ActOnStartStmtExpr() {
13008   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13009 }
13010 
13011 void Sema::ActOnStmtExprError() {
13012   // Note that function is also called by TreeTransform when leaving a
13013   // StmtExpr scope without rebuilding anything.
13014 
13015   DiscardCleanupsInEvaluationContext();
13016   PopExpressionEvaluationContext();
13017 }
13018 
13019 ExprResult
13020 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13021                     SourceLocation RPLoc) { // "({..})"
13022   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13023   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13024 
13025   if (hasAnyUnrecoverableErrorsInThisFunction())
13026     DiscardCleanupsInEvaluationContext();
13027   assert(!Cleanup.exprNeedsCleanups() &&
13028          "cleanups within StmtExpr not correctly bound!");
13029   PopExpressionEvaluationContext();
13030 
13031   // FIXME: there are a variety of strange constraints to enforce here, for
13032   // example, it is not possible to goto into a stmt expression apparently.
13033   // More semantic analysis is needed.
13034 
13035   // If there are sub-stmts in the compound stmt, take the type of the last one
13036   // as the type of the stmtexpr.
13037   QualType Ty = Context.VoidTy;
13038   bool StmtExprMayBindToTemp = false;
13039   if (!Compound->body_empty()) {
13040     Stmt *LastStmt = Compound->body_back();
13041     LabelStmt *LastLabelStmt = nullptr;
13042     // If LastStmt is a label, skip down through into the body.
13043     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13044       LastLabelStmt = Label;
13045       LastStmt = Label->getSubStmt();
13046     }
13047 
13048     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13049       // Do function/array conversion on the last expression, but not
13050       // lvalue-to-rvalue.  However, initialize an unqualified type.
13051       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13052       if (LastExpr.isInvalid())
13053         return ExprError();
13054       Ty = LastExpr.get()->getType().getUnqualifiedType();
13055 
13056       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13057         // In ARC, if the final expression ends in a consume, splice
13058         // the consume out and bind it later.  In the alternate case
13059         // (when dealing with a retainable type), the result
13060         // initialization will create a produce.  In both cases the
13061         // result will be +1, and we'll need to balance that out with
13062         // a bind.
13063         if (Expr *rebuiltLastStmt
13064               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13065           LastExpr = rebuiltLastStmt;
13066         } else {
13067           LastExpr = PerformCopyInitialization(
13068               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13069               SourceLocation(), LastExpr);
13070         }
13071 
13072         if (LastExpr.isInvalid())
13073           return ExprError();
13074         if (LastExpr.get() != nullptr) {
13075           if (!LastLabelStmt)
13076             Compound->setLastStmt(LastExpr.get());
13077           else
13078             LastLabelStmt->setSubStmt(LastExpr.get());
13079           StmtExprMayBindToTemp = true;
13080         }
13081       }
13082     }
13083   }
13084 
13085   // FIXME: Check that expression type is complete/non-abstract; statement
13086   // expressions are not lvalues.
13087   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13088   if (StmtExprMayBindToTemp)
13089     return MaybeBindToTemporary(ResStmtExpr);
13090   return ResStmtExpr;
13091 }
13092 
13093 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13094                                       TypeSourceInfo *TInfo,
13095                                       ArrayRef<OffsetOfComponent> Components,
13096                                       SourceLocation RParenLoc) {
13097   QualType ArgTy = TInfo->getType();
13098   bool Dependent = ArgTy->isDependentType();
13099   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13100 
13101   // We must have at least one component that refers to the type, and the first
13102   // one is known to be a field designator.  Verify that the ArgTy represents
13103   // a struct/union/class.
13104   if (!Dependent && !ArgTy->isRecordType())
13105     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13106                        << ArgTy << TypeRange);
13107 
13108   // Type must be complete per C99 7.17p3 because a declaring a variable
13109   // with an incomplete type would be ill-formed.
13110   if (!Dependent
13111       && RequireCompleteType(BuiltinLoc, ArgTy,
13112                              diag::err_offsetof_incomplete_type, TypeRange))
13113     return ExprError();
13114 
13115   bool DidWarnAboutNonPOD = false;
13116   QualType CurrentType = ArgTy;
13117   SmallVector<OffsetOfNode, 4> Comps;
13118   SmallVector<Expr*, 4> Exprs;
13119   for (const OffsetOfComponent &OC : Components) {
13120     if (OC.isBrackets) {
13121       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13122       if (!CurrentType->isDependentType()) {
13123         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13124         if(!AT)
13125           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13126                            << CurrentType);
13127         CurrentType = AT->getElementType();
13128       } else
13129         CurrentType = Context.DependentTy;
13130 
13131       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13132       if (IdxRval.isInvalid())
13133         return ExprError();
13134       Expr *Idx = IdxRval.get();
13135 
13136       // The expression must be an integral expression.
13137       // FIXME: An integral constant expression?
13138       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13139           !Idx->getType()->isIntegerType())
13140         return ExprError(
13141             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13142             << Idx->getSourceRange());
13143 
13144       // Record this array index.
13145       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13146       Exprs.push_back(Idx);
13147       continue;
13148     }
13149 
13150     // Offset of a field.
13151     if (CurrentType->isDependentType()) {
13152       // We have the offset of a field, but we can't look into the dependent
13153       // type. Just record the identifier of the field.
13154       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13155       CurrentType = Context.DependentTy;
13156       continue;
13157     }
13158 
13159     // We need to have a complete type to look into.
13160     if (RequireCompleteType(OC.LocStart, CurrentType,
13161                             diag::err_offsetof_incomplete_type))
13162       return ExprError();
13163 
13164     // Look for the designated field.
13165     const RecordType *RC = CurrentType->getAs<RecordType>();
13166     if (!RC)
13167       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13168                        << CurrentType);
13169     RecordDecl *RD = RC->getDecl();
13170 
13171     // C++ [lib.support.types]p5:
13172     //   The macro offsetof accepts a restricted set of type arguments in this
13173     //   International Standard. type shall be a POD structure or a POD union
13174     //   (clause 9).
13175     // C++11 [support.types]p4:
13176     //   If type is not a standard-layout class (Clause 9), the results are
13177     //   undefined.
13178     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13179       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13180       unsigned DiagID =
13181         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13182                             : diag::ext_offsetof_non_pod_type;
13183 
13184       if (!IsSafe && !DidWarnAboutNonPOD &&
13185           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13186                               PDiag(DiagID)
13187                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13188                               << CurrentType))
13189         DidWarnAboutNonPOD = true;
13190     }
13191 
13192     // Look for the field.
13193     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13194     LookupQualifiedName(R, RD);
13195     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13196     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13197     if (!MemberDecl) {
13198       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13199         MemberDecl = IndirectMemberDecl->getAnonField();
13200     }
13201 
13202     if (!MemberDecl)
13203       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13204                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13205                                                               OC.LocEnd));
13206 
13207     // C99 7.17p3:
13208     //   (If the specified member is a bit-field, the behavior is undefined.)
13209     //
13210     // We diagnose this as an error.
13211     if (MemberDecl->isBitField()) {
13212       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13213         << MemberDecl->getDeclName()
13214         << SourceRange(BuiltinLoc, RParenLoc);
13215       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13216       return ExprError();
13217     }
13218 
13219     RecordDecl *Parent = MemberDecl->getParent();
13220     if (IndirectMemberDecl)
13221       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13222 
13223     // If the member was found in a base class, introduce OffsetOfNodes for
13224     // the base class indirections.
13225     CXXBasePaths Paths;
13226     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13227                       Paths)) {
13228       if (Paths.getDetectedVirtual()) {
13229         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13230           << MemberDecl->getDeclName()
13231           << SourceRange(BuiltinLoc, RParenLoc);
13232         return ExprError();
13233       }
13234 
13235       CXXBasePath &Path = Paths.front();
13236       for (const CXXBasePathElement &B : Path)
13237         Comps.push_back(OffsetOfNode(B.Base));
13238     }
13239 
13240     if (IndirectMemberDecl) {
13241       for (auto *FI : IndirectMemberDecl->chain()) {
13242         assert(isa<FieldDecl>(FI));
13243         Comps.push_back(OffsetOfNode(OC.LocStart,
13244                                      cast<FieldDecl>(FI), OC.LocEnd));
13245       }
13246     } else
13247       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13248 
13249     CurrentType = MemberDecl->getType().getNonReferenceType();
13250   }
13251 
13252   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13253                               Comps, Exprs, RParenLoc);
13254 }
13255 
13256 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13257                                       SourceLocation BuiltinLoc,
13258                                       SourceLocation TypeLoc,
13259                                       ParsedType ParsedArgTy,
13260                                       ArrayRef<OffsetOfComponent> Components,
13261                                       SourceLocation RParenLoc) {
13262 
13263   TypeSourceInfo *ArgTInfo;
13264   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13265   if (ArgTy.isNull())
13266     return ExprError();
13267 
13268   if (!ArgTInfo)
13269     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13270 
13271   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13272 }
13273 
13274 
13275 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13276                                  Expr *CondExpr,
13277                                  Expr *LHSExpr, Expr *RHSExpr,
13278                                  SourceLocation RPLoc) {
13279   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13280 
13281   ExprValueKind VK = VK_RValue;
13282   ExprObjectKind OK = OK_Ordinary;
13283   QualType resType;
13284   bool ValueDependent = false;
13285   bool CondIsTrue = false;
13286   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13287     resType = Context.DependentTy;
13288     ValueDependent = true;
13289   } else {
13290     // The conditional expression is required to be a constant expression.
13291     llvm::APSInt condEval(32);
13292     ExprResult CondICE
13293       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13294           diag::err_typecheck_choose_expr_requires_constant, false);
13295     if (CondICE.isInvalid())
13296       return ExprError();
13297     CondExpr = CondICE.get();
13298     CondIsTrue = condEval.getZExtValue();
13299 
13300     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13301     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13302 
13303     resType = ActiveExpr->getType();
13304     ValueDependent = ActiveExpr->isValueDependent();
13305     VK = ActiveExpr->getValueKind();
13306     OK = ActiveExpr->getObjectKind();
13307   }
13308 
13309   return new (Context)
13310       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13311                  CondIsTrue, resType->isDependentType(), ValueDependent);
13312 }
13313 
13314 //===----------------------------------------------------------------------===//
13315 // Clang Extensions.
13316 //===----------------------------------------------------------------------===//
13317 
13318 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13319 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13320   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13321 
13322   if (LangOpts.CPlusPlus) {
13323     Decl *ManglingContextDecl;
13324     if (MangleNumberingContext *MCtx =
13325             getCurrentMangleNumberContext(Block->getDeclContext(),
13326                                           ManglingContextDecl)) {
13327       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13328       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13329     }
13330   }
13331 
13332   PushBlockScope(CurScope, Block);
13333   CurContext->addDecl(Block);
13334   if (CurScope)
13335     PushDeclContext(CurScope, Block);
13336   else
13337     CurContext = Block;
13338 
13339   getCurBlock()->HasImplicitReturnType = true;
13340 
13341   // Enter a new evaluation context to insulate the block from any
13342   // cleanups from the enclosing full-expression.
13343   PushExpressionEvaluationContext(
13344       ExpressionEvaluationContext::PotentiallyEvaluated);
13345 }
13346 
13347 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13348                                Scope *CurScope) {
13349   assert(ParamInfo.getIdentifier() == nullptr &&
13350          "block-id should have no identifier!");
13351   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13352   BlockScopeInfo *CurBlock = getCurBlock();
13353 
13354   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13355   QualType T = Sig->getType();
13356 
13357   // FIXME: We should allow unexpanded parameter packs here, but that would,
13358   // in turn, make the block expression contain unexpanded parameter packs.
13359   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13360     // Drop the parameters.
13361     FunctionProtoType::ExtProtoInfo EPI;
13362     EPI.HasTrailingReturn = false;
13363     EPI.TypeQuals |= DeclSpec::TQ_const;
13364     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13365     Sig = Context.getTrivialTypeSourceInfo(T);
13366   }
13367 
13368   // GetTypeForDeclarator always produces a function type for a block
13369   // literal signature.  Furthermore, it is always a FunctionProtoType
13370   // unless the function was written with a typedef.
13371   assert(T->isFunctionType() &&
13372          "GetTypeForDeclarator made a non-function block signature");
13373 
13374   // Look for an explicit signature in that function type.
13375   FunctionProtoTypeLoc ExplicitSignature;
13376 
13377   if ((ExplicitSignature =
13378            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13379 
13380     // Check whether that explicit signature was synthesized by
13381     // GetTypeForDeclarator.  If so, don't save that as part of the
13382     // written signature.
13383     if (ExplicitSignature.getLocalRangeBegin() ==
13384         ExplicitSignature.getLocalRangeEnd()) {
13385       // This would be much cheaper if we stored TypeLocs instead of
13386       // TypeSourceInfos.
13387       TypeLoc Result = ExplicitSignature.getReturnLoc();
13388       unsigned Size = Result.getFullDataSize();
13389       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13390       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13391 
13392       ExplicitSignature = FunctionProtoTypeLoc();
13393     }
13394   }
13395 
13396   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13397   CurBlock->FunctionType = T;
13398 
13399   const FunctionType *Fn = T->getAs<FunctionType>();
13400   QualType RetTy = Fn->getReturnType();
13401   bool isVariadic =
13402     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13403 
13404   CurBlock->TheDecl->setIsVariadic(isVariadic);
13405 
13406   // Context.DependentTy is used as a placeholder for a missing block
13407   // return type.  TODO:  what should we do with declarators like:
13408   //   ^ * { ... }
13409   // If the answer is "apply template argument deduction"....
13410   if (RetTy != Context.DependentTy) {
13411     CurBlock->ReturnType = RetTy;
13412     CurBlock->TheDecl->setBlockMissingReturnType(false);
13413     CurBlock->HasImplicitReturnType = false;
13414   }
13415 
13416   // Push block parameters from the declarator if we had them.
13417   SmallVector<ParmVarDecl*, 8> Params;
13418   if (ExplicitSignature) {
13419     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13420       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13421       if (Param->getIdentifier() == nullptr &&
13422           !Param->isImplicit() &&
13423           !Param->isInvalidDecl() &&
13424           !getLangOpts().CPlusPlus)
13425         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13426       Params.push_back(Param);
13427     }
13428 
13429   // Fake up parameter variables if we have a typedef, like
13430   //   ^ fntype { ... }
13431   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13432     for (const auto &I : Fn->param_types()) {
13433       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13434           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13435       Params.push_back(Param);
13436     }
13437   }
13438 
13439   // Set the parameters on the block decl.
13440   if (!Params.empty()) {
13441     CurBlock->TheDecl->setParams(Params);
13442     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13443                              /*CheckParameterNames=*/false);
13444   }
13445 
13446   // Finally we can process decl attributes.
13447   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13448 
13449   // Put the parameter variables in scope.
13450   for (auto AI : CurBlock->TheDecl->parameters()) {
13451     AI->setOwningFunction(CurBlock->TheDecl);
13452 
13453     // If this has an identifier, add it to the scope stack.
13454     if (AI->getIdentifier()) {
13455       CheckShadow(CurBlock->TheScope, AI);
13456 
13457       PushOnScopeChains(AI, CurBlock->TheScope);
13458     }
13459   }
13460 }
13461 
13462 /// ActOnBlockError - If there is an error parsing a block, this callback
13463 /// is invoked to pop the information about the block from the action impl.
13464 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13465   // Leave the expression-evaluation context.
13466   DiscardCleanupsInEvaluationContext();
13467   PopExpressionEvaluationContext();
13468 
13469   // Pop off CurBlock, handle nested blocks.
13470   PopDeclContext();
13471   PopFunctionScopeInfo();
13472 }
13473 
13474 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13475 /// literal was successfully completed.  ^(int x){...}
13476 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13477                                     Stmt *Body, Scope *CurScope) {
13478   // If blocks are disabled, emit an error.
13479   if (!LangOpts.Blocks)
13480     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13481 
13482   // Leave the expression-evaluation context.
13483   if (hasAnyUnrecoverableErrorsInThisFunction())
13484     DiscardCleanupsInEvaluationContext();
13485   assert(!Cleanup.exprNeedsCleanups() &&
13486          "cleanups within block not correctly bound!");
13487   PopExpressionEvaluationContext();
13488 
13489   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13490   BlockDecl *BD = BSI->TheDecl;
13491 
13492   if (BSI->HasImplicitReturnType)
13493     deduceClosureReturnType(*BSI);
13494 
13495   PopDeclContext();
13496 
13497   QualType RetTy = Context.VoidTy;
13498   if (!BSI->ReturnType.isNull())
13499     RetTy = BSI->ReturnType;
13500 
13501   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13502   QualType BlockTy;
13503 
13504   // Set the captured variables on the block.
13505   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13506   SmallVector<BlockDecl::Capture, 4> Captures;
13507   for (Capture &Cap : BSI->Captures) {
13508     if (Cap.isThisCapture())
13509       continue;
13510     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13511                               Cap.isNested(), Cap.getInitExpr());
13512     Captures.push_back(NewCap);
13513   }
13514   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13515 
13516   // If the user wrote a function type in some form, try to use that.
13517   if (!BSI->FunctionType.isNull()) {
13518     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13519 
13520     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13521     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13522 
13523     // Turn protoless block types into nullary block types.
13524     if (isa<FunctionNoProtoType>(FTy)) {
13525       FunctionProtoType::ExtProtoInfo EPI;
13526       EPI.ExtInfo = Ext;
13527       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13528 
13529     // Otherwise, if we don't need to change anything about the function type,
13530     // preserve its sugar structure.
13531     } else if (FTy->getReturnType() == RetTy &&
13532                (!NoReturn || FTy->getNoReturnAttr())) {
13533       BlockTy = BSI->FunctionType;
13534 
13535     // Otherwise, make the minimal modifications to the function type.
13536     } else {
13537       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13538       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13539       EPI.TypeQuals = 0; // FIXME: silently?
13540       EPI.ExtInfo = Ext;
13541       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13542     }
13543 
13544   // If we don't have a function type, just build one from nothing.
13545   } else {
13546     FunctionProtoType::ExtProtoInfo EPI;
13547     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13548     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13549   }
13550 
13551   DiagnoseUnusedParameters(BD->parameters());
13552   BlockTy = Context.getBlockPointerType(BlockTy);
13553 
13554   // If needed, diagnose invalid gotos and switches in the block.
13555   if (getCurFunction()->NeedsScopeChecking() &&
13556       !PP.isCodeCompletionEnabled())
13557     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13558 
13559   BD->setBody(cast<CompoundStmt>(Body));
13560 
13561   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13562     DiagnoseUnguardedAvailabilityViolations(BD);
13563 
13564   // Try to apply the named return value optimization. We have to check again
13565   // if we can do this, though, because blocks keep return statements around
13566   // to deduce an implicit return type.
13567   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13568       !BD->isDependentContext())
13569     computeNRVO(Body, BSI);
13570 
13571   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13572   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13573   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13574 
13575   // If the block isn't obviously global, i.e. it captures anything at
13576   // all, then we need to do a few things in the surrounding context:
13577   if (Result->getBlockDecl()->hasCaptures()) {
13578     // First, this expression has a new cleanup object.
13579     ExprCleanupObjects.push_back(Result->getBlockDecl());
13580     Cleanup.setExprNeedsCleanups(true);
13581 
13582     // It also gets a branch-protected scope if any of the captured
13583     // variables needs destruction.
13584     for (const auto &CI : Result->getBlockDecl()->captures()) {
13585       const VarDecl *var = CI.getVariable();
13586       if (var->getType().isDestructedType() != QualType::DK_none) {
13587         setFunctionHasBranchProtectedScope();
13588         break;
13589       }
13590     }
13591   }
13592 
13593   if (getCurFunction())
13594     getCurFunction()->addBlock(BD);
13595 
13596   return Result;
13597 }
13598 
13599 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13600                             SourceLocation RPLoc) {
13601   TypeSourceInfo *TInfo;
13602   GetTypeFromParser(Ty, &TInfo);
13603   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13604 }
13605 
13606 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13607                                 Expr *E, TypeSourceInfo *TInfo,
13608                                 SourceLocation RPLoc) {
13609   Expr *OrigExpr = E;
13610   bool IsMS = false;
13611 
13612   // CUDA device code does not support varargs.
13613   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13614     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13615       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13616       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13617         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13618     }
13619   }
13620 
13621   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13622   // as Microsoft ABI on an actual Microsoft platform, where
13623   // __builtin_ms_va_list and __builtin_va_list are the same.)
13624   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13625       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13626     QualType MSVaListType = Context.getBuiltinMSVaListType();
13627     if (Context.hasSameType(MSVaListType, E->getType())) {
13628       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13629         return ExprError();
13630       IsMS = true;
13631     }
13632   }
13633 
13634   // Get the va_list type
13635   QualType VaListType = Context.getBuiltinVaListType();
13636   if (!IsMS) {
13637     if (VaListType->isArrayType()) {
13638       // Deal with implicit array decay; for example, on x86-64,
13639       // va_list is an array, but it's supposed to decay to
13640       // a pointer for va_arg.
13641       VaListType = Context.getArrayDecayedType(VaListType);
13642       // Make sure the input expression also decays appropriately.
13643       ExprResult Result = UsualUnaryConversions(E);
13644       if (Result.isInvalid())
13645         return ExprError();
13646       E = Result.get();
13647     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13648       // If va_list is a record type and we are compiling in C++ mode,
13649       // check the argument using reference binding.
13650       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13651           Context, Context.getLValueReferenceType(VaListType), false);
13652       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13653       if (Init.isInvalid())
13654         return ExprError();
13655       E = Init.getAs<Expr>();
13656     } else {
13657       // Otherwise, the va_list argument must be an l-value because
13658       // it is modified by va_arg.
13659       if (!E->isTypeDependent() &&
13660           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13661         return ExprError();
13662     }
13663   }
13664 
13665   if (!IsMS && !E->isTypeDependent() &&
13666       !Context.hasSameType(VaListType, E->getType()))
13667     return ExprError(
13668         Diag(E->getBeginLoc(),
13669              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13670         << OrigExpr->getType() << E->getSourceRange());
13671 
13672   if (!TInfo->getType()->isDependentType()) {
13673     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13674                             diag::err_second_parameter_to_va_arg_incomplete,
13675                             TInfo->getTypeLoc()))
13676       return ExprError();
13677 
13678     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13679                                TInfo->getType(),
13680                                diag::err_second_parameter_to_va_arg_abstract,
13681                                TInfo->getTypeLoc()))
13682       return ExprError();
13683 
13684     if (!TInfo->getType().isPODType(Context)) {
13685       Diag(TInfo->getTypeLoc().getBeginLoc(),
13686            TInfo->getType()->isObjCLifetimeType()
13687              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13688              : diag::warn_second_parameter_to_va_arg_not_pod)
13689         << TInfo->getType()
13690         << TInfo->getTypeLoc().getSourceRange();
13691     }
13692 
13693     // Check for va_arg where arguments of the given type will be promoted
13694     // (i.e. this va_arg is guaranteed to have undefined behavior).
13695     QualType PromoteType;
13696     if (TInfo->getType()->isPromotableIntegerType()) {
13697       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13698       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13699         PromoteType = QualType();
13700     }
13701     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13702       PromoteType = Context.DoubleTy;
13703     if (!PromoteType.isNull())
13704       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13705                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13706                           << TInfo->getType()
13707                           << PromoteType
13708                           << TInfo->getTypeLoc().getSourceRange());
13709   }
13710 
13711   QualType T = TInfo->getType().getNonLValueExprType(Context);
13712   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13713 }
13714 
13715 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13716   // The type of __null will be int or long, depending on the size of
13717   // pointers on the target.
13718   QualType Ty;
13719   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13720   if (pw == Context.getTargetInfo().getIntWidth())
13721     Ty = Context.IntTy;
13722   else if (pw == Context.getTargetInfo().getLongWidth())
13723     Ty = Context.LongTy;
13724   else if (pw == Context.getTargetInfo().getLongLongWidth())
13725     Ty = Context.LongLongTy;
13726   else {
13727     llvm_unreachable("I don't know size of pointer!");
13728   }
13729 
13730   return new (Context) GNUNullExpr(Ty, TokenLoc);
13731 }
13732 
13733 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13734                                               bool Diagnose) {
13735   if (!getLangOpts().ObjC1)
13736     return false;
13737 
13738   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13739   if (!PT)
13740     return false;
13741 
13742   if (!PT->isObjCIdType()) {
13743     // Check if the destination is the 'NSString' interface.
13744     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13745     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13746       return false;
13747   }
13748 
13749   // Ignore any parens, implicit casts (should only be
13750   // array-to-pointer decays), and not-so-opaque values.  The last is
13751   // important for making this trigger for property assignments.
13752   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13753   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13754     if (OV->getSourceExpr())
13755       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13756 
13757   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13758   if (!SL || !SL->isAscii())
13759     return false;
13760   if (Diagnose) {
13761     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13762         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13763     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13764   }
13765   return true;
13766 }
13767 
13768 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13769                                               const Expr *SrcExpr) {
13770   if (!DstType->isFunctionPointerType() ||
13771       !SrcExpr->getType()->isFunctionType())
13772     return false;
13773 
13774   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13775   if (!DRE)
13776     return false;
13777 
13778   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13779   if (!FD)
13780     return false;
13781 
13782   return !S.checkAddressOfFunctionIsAvailable(FD,
13783                                               /*Complain=*/true,
13784                                               SrcExpr->getBeginLoc());
13785 }
13786 
13787 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13788                                     SourceLocation Loc,
13789                                     QualType DstType, QualType SrcType,
13790                                     Expr *SrcExpr, AssignmentAction Action,
13791                                     bool *Complained) {
13792   if (Complained)
13793     *Complained = false;
13794 
13795   // Decode the result (notice that AST's are still created for extensions).
13796   bool CheckInferredResultType = false;
13797   bool isInvalid = false;
13798   unsigned DiagKind = 0;
13799   FixItHint Hint;
13800   ConversionFixItGenerator ConvHints;
13801   bool MayHaveConvFixit = false;
13802   bool MayHaveFunctionDiff = false;
13803   const ObjCInterfaceDecl *IFace = nullptr;
13804   const ObjCProtocolDecl *PDecl = nullptr;
13805 
13806   switch (ConvTy) {
13807   case Compatible:
13808       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13809       return false;
13810 
13811   case PointerToInt:
13812     DiagKind = diag::ext_typecheck_convert_pointer_int;
13813     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13814     MayHaveConvFixit = true;
13815     break;
13816   case IntToPointer:
13817     DiagKind = diag::ext_typecheck_convert_int_pointer;
13818     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13819     MayHaveConvFixit = true;
13820     break;
13821   case IncompatiblePointer:
13822     if (Action == AA_Passing_CFAudited)
13823       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13824     else if (SrcType->isFunctionPointerType() &&
13825              DstType->isFunctionPointerType())
13826       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13827     else
13828       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13829 
13830     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13831       SrcType->isObjCObjectPointerType();
13832     if (Hint.isNull() && !CheckInferredResultType) {
13833       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13834     }
13835     else if (CheckInferredResultType) {
13836       SrcType = SrcType.getUnqualifiedType();
13837       DstType = DstType.getUnqualifiedType();
13838     }
13839     MayHaveConvFixit = true;
13840     break;
13841   case IncompatiblePointerSign:
13842     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13843     break;
13844   case FunctionVoidPointer:
13845     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13846     break;
13847   case IncompatiblePointerDiscardsQualifiers: {
13848     // Perform array-to-pointer decay if necessary.
13849     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13850 
13851     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13852     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13853     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13854       DiagKind = diag::err_typecheck_incompatible_address_space;
13855       break;
13856 
13857     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13858       DiagKind = diag::err_typecheck_incompatible_ownership;
13859       break;
13860     }
13861 
13862     llvm_unreachable("unknown error case for discarding qualifiers!");
13863     // fallthrough
13864   }
13865   case CompatiblePointerDiscardsQualifiers:
13866     // If the qualifiers lost were because we were applying the
13867     // (deprecated) C++ conversion from a string literal to a char*
13868     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13869     // Ideally, this check would be performed in
13870     // checkPointerTypesForAssignment. However, that would require a
13871     // bit of refactoring (so that the second argument is an
13872     // expression, rather than a type), which should be done as part
13873     // of a larger effort to fix checkPointerTypesForAssignment for
13874     // C++ semantics.
13875     if (getLangOpts().CPlusPlus &&
13876         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13877       return false;
13878     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13879     break;
13880   case IncompatibleNestedPointerQualifiers:
13881     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13882     break;
13883   case IntToBlockPointer:
13884     DiagKind = diag::err_int_to_block_pointer;
13885     break;
13886   case IncompatibleBlockPointer:
13887     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13888     break;
13889   case IncompatibleObjCQualifiedId: {
13890     if (SrcType->isObjCQualifiedIdType()) {
13891       const ObjCObjectPointerType *srcOPT =
13892                 SrcType->getAs<ObjCObjectPointerType>();
13893       for (auto *srcProto : srcOPT->quals()) {
13894         PDecl = srcProto;
13895         break;
13896       }
13897       if (const ObjCInterfaceType *IFaceT =
13898             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13899         IFace = IFaceT->getDecl();
13900     }
13901     else if (DstType->isObjCQualifiedIdType()) {
13902       const ObjCObjectPointerType *dstOPT =
13903         DstType->getAs<ObjCObjectPointerType>();
13904       for (auto *dstProto : dstOPT->quals()) {
13905         PDecl = dstProto;
13906         break;
13907       }
13908       if (const ObjCInterfaceType *IFaceT =
13909             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13910         IFace = IFaceT->getDecl();
13911     }
13912     DiagKind = diag::warn_incompatible_qualified_id;
13913     break;
13914   }
13915   case IncompatibleVectors:
13916     DiagKind = diag::warn_incompatible_vectors;
13917     break;
13918   case IncompatibleObjCWeakRef:
13919     DiagKind = diag::err_arc_weak_unavailable_assign;
13920     break;
13921   case Incompatible:
13922     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13923       if (Complained)
13924         *Complained = true;
13925       return true;
13926     }
13927 
13928     DiagKind = diag::err_typecheck_convert_incompatible;
13929     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13930     MayHaveConvFixit = true;
13931     isInvalid = true;
13932     MayHaveFunctionDiff = true;
13933     break;
13934   }
13935 
13936   QualType FirstType, SecondType;
13937   switch (Action) {
13938   case AA_Assigning:
13939   case AA_Initializing:
13940     // The destination type comes first.
13941     FirstType = DstType;
13942     SecondType = SrcType;
13943     break;
13944 
13945   case AA_Returning:
13946   case AA_Passing:
13947   case AA_Passing_CFAudited:
13948   case AA_Converting:
13949   case AA_Sending:
13950   case AA_Casting:
13951     // The source type comes first.
13952     FirstType = SrcType;
13953     SecondType = DstType;
13954     break;
13955   }
13956 
13957   PartialDiagnostic FDiag = PDiag(DiagKind);
13958   if (Action == AA_Passing_CFAudited)
13959     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13960   else
13961     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13962 
13963   // If we can fix the conversion, suggest the FixIts.
13964   assert(ConvHints.isNull() || Hint.isNull());
13965   if (!ConvHints.isNull()) {
13966     for (FixItHint &H : ConvHints.Hints)
13967       FDiag << H;
13968   } else {
13969     FDiag << Hint;
13970   }
13971   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13972 
13973   if (MayHaveFunctionDiff)
13974     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13975 
13976   Diag(Loc, FDiag);
13977   if (DiagKind == diag::warn_incompatible_qualified_id &&
13978       PDecl && IFace && !IFace->hasDefinition())
13979       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13980         << IFace << PDecl;
13981 
13982   if (SecondType == Context.OverloadTy)
13983     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13984                               FirstType, /*TakingAddress=*/true);
13985 
13986   if (CheckInferredResultType)
13987     EmitRelatedResultTypeNote(SrcExpr);
13988 
13989   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13990     EmitRelatedResultTypeNoteForReturn(DstType);
13991 
13992   if (Complained)
13993     *Complained = true;
13994   return isInvalid;
13995 }
13996 
13997 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13998                                                  llvm::APSInt *Result) {
13999   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14000   public:
14001     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14002       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14003     }
14004   } Diagnoser;
14005 
14006   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14007 }
14008 
14009 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14010                                                  llvm::APSInt *Result,
14011                                                  unsigned DiagID,
14012                                                  bool AllowFold) {
14013   class IDDiagnoser : public VerifyICEDiagnoser {
14014     unsigned DiagID;
14015 
14016   public:
14017     IDDiagnoser(unsigned DiagID)
14018       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14019 
14020     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14021       S.Diag(Loc, DiagID) << SR;
14022     }
14023   } Diagnoser(DiagID);
14024 
14025   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14026 }
14027 
14028 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14029                                             SourceRange SR) {
14030   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14031 }
14032 
14033 ExprResult
14034 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14035                                       VerifyICEDiagnoser &Diagnoser,
14036                                       bool AllowFold) {
14037   SourceLocation DiagLoc = E->getBeginLoc();
14038 
14039   if (getLangOpts().CPlusPlus11) {
14040     // C++11 [expr.const]p5:
14041     //   If an expression of literal class type is used in a context where an
14042     //   integral constant expression is required, then that class type shall
14043     //   have a single non-explicit conversion function to an integral or
14044     //   unscoped enumeration type
14045     ExprResult Converted;
14046     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14047     public:
14048       CXX11ConvertDiagnoser(bool Silent)
14049           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14050                                 Silent, true) {}
14051 
14052       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14053                                            QualType T) override {
14054         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14055       }
14056 
14057       SemaDiagnosticBuilder diagnoseIncomplete(
14058           Sema &S, SourceLocation Loc, QualType T) override {
14059         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14060       }
14061 
14062       SemaDiagnosticBuilder diagnoseExplicitConv(
14063           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14064         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14065       }
14066 
14067       SemaDiagnosticBuilder noteExplicitConv(
14068           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14069         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14070                  << ConvTy->isEnumeralType() << ConvTy;
14071       }
14072 
14073       SemaDiagnosticBuilder diagnoseAmbiguous(
14074           Sema &S, SourceLocation Loc, QualType T) override {
14075         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14076       }
14077 
14078       SemaDiagnosticBuilder noteAmbiguous(
14079           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14080         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14081                  << ConvTy->isEnumeralType() << ConvTy;
14082       }
14083 
14084       SemaDiagnosticBuilder diagnoseConversion(
14085           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14086         llvm_unreachable("conversion functions are permitted");
14087       }
14088     } ConvertDiagnoser(Diagnoser.Suppress);
14089 
14090     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14091                                                     ConvertDiagnoser);
14092     if (Converted.isInvalid())
14093       return Converted;
14094     E = Converted.get();
14095     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14096       return ExprError();
14097   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14098     // An ICE must be of integral or unscoped enumeration type.
14099     if (!Diagnoser.Suppress)
14100       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14101     return ExprError();
14102   }
14103 
14104   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14105   // in the non-ICE case.
14106   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14107     if (Result)
14108       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14109     return E;
14110   }
14111 
14112   Expr::EvalResult EvalResult;
14113   SmallVector<PartialDiagnosticAt, 8> Notes;
14114   EvalResult.Diag = &Notes;
14115 
14116   // Try to evaluate the expression, and produce diagnostics explaining why it's
14117   // not a constant expression as a side-effect.
14118   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14119                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14120 
14121   // In C++11, we can rely on diagnostics being produced for any expression
14122   // which is not a constant expression. If no diagnostics were produced, then
14123   // this is a constant expression.
14124   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14125     if (Result)
14126       *Result = EvalResult.Val.getInt();
14127     return E;
14128   }
14129 
14130   // If our only note is the usual "invalid subexpression" note, just point
14131   // the caret at its location rather than producing an essentially
14132   // redundant note.
14133   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14134         diag::note_invalid_subexpr_in_const_expr) {
14135     DiagLoc = Notes[0].first;
14136     Notes.clear();
14137   }
14138 
14139   if (!Folded || !AllowFold) {
14140     if (!Diagnoser.Suppress) {
14141       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14142       for (const PartialDiagnosticAt &Note : Notes)
14143         Diag(Note.first, Note.second);
14144     }
14145 
14146     return ExprError();
14147   }
14148 
14149   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14150   for (const PartialDiagnosticAt &Note : Notes)
14151     Diag(Note.first, Note.second);
14152 
14153   if (Result)
14154     *Result = EvalResult.Val.getInt();
14155   return E;
14156 }
14157 
14158 namespace {
14159   // Handle the case where we conclude a expression which we speculatively
14160   // considered to be unevaluated is actually evaluated.
14161   class TransformToPE : public TreeTransform<TransformToPE> {
14162     typedef TreeTransform<TransformToPE> BaseTransform;
14163 
14164   public:
14165     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14166 
14167     // Make sure we redo semantic analysis
14168     bool AlwaysRebuild() { return true; }
14169 
14170     // Make sure we handle LabelStmts correctly.
14171     // FIXME: This does the right thing, but maybe we need a more general
14172     // fix to TreeTransform?
14173     StmtResult TransformLabelStmt(LabelStmt *S) {
14174       S->getDecl()->setStmt(nullptr);
14175       return BaseTransform::TransformLabelStmt(S);
14176     }
14177 
14178     // We need to special-case DeclRefExprs referring to FieldDecls which
14179     // are not part of a member pointer formation; normal TreeTransforming
14180     // doesn't catch this case because of the way we represent them in the AST.
14181     // FIXME: This is a bit ugly; is it really the best way to handle this
14182     // case?
14183     //
14184     // Error on DeclRefExprs referring to FieldDecls.
14185     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14186       if (isa<FieldDecl>(E->getDecl()) &&
14187           !SemaRef.isUnevaluatedContext())
14188         return SemaRef.Diag(E->getLocation(),
14189                             diag::err_invalid_non_static_member_use)
14190             << E->getDecl() << E->getSourceRange();
14191 
14192       return BaseTransform::TransformDeclRefExpr(E);
14193     }
14194 
14195     // Exception: filter out member pointer formation
14196     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14197       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14198         return E;
14199 
14200       return BaseTransform::TransformUnaryOperator(E);
14201     }
14202 
14203     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14204       // Lambdas never need to be transformed.
14205       return E;
14206     }
14207   };
14208 }
14209 
14210 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14211   assert(isUnevaluatedContext() &&
14212          "Should only transform unevaluated expressions");
14213   ExprEvalContexts.back().Context =
14214       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14215   if (isUnevaluatedContext())
14216     return E;
14217   return TransformToPE(*this).TransformExpr(E);
14218 }
14219 
14220 void
14221 Sema::PushExpressionEvaluationContext(
14222     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14223     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14224   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14225                                 LambdaContextDecl, ExprContext);
14226   Cleanup.reset();
14227   if (!MaybeODRUseExprs.empty())
14228     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14229 }
14230 
14231 void
14232 Sema::PushExpressionEvaluationContext(
14233     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14234     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14235   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14236   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14237 }
14238 
14239 void Sema::PopExpressionEvaluationContext() {
14240   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14241   unsigned NumTypos = Rec.NumTypos;
14242 
14243   if (!Rec.Lambdas.empty()) {
14244     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14245     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14246         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14247       unsigned D;
14248       if (Rec.isUnevaluated()) {
14249         // C++11 [expr.prim.lambda]p2:
14250         //   A lambda-expression shall not appear in an unevaluated operand
14251         //   (Clause 5).
14252         D = diag::err_lambda_unevaluated_operand;
14253       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14254         // C++1y [expr.const]p2:
14255         //   A conditional-expression e is a core constant expression unless the
14256         //   evaluation of e, following the rules of the abstract machine, would
14257         //   evaluate [...] a lambda-expression.
14258         D = diag::err_lambda_in_constant_expression;
14259       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14260         // C++17 [expr.prim.lamda]p2:
14261         // A lambda-expression shall not appear [...] in a template-argument.
14262         D = diag::err_lambda_in_invalid_context;
14263       } else
14264         llvm_unreachable("Couldn't infer lambda error message.");
14265 
14266       for (const auto *L : Rec.Lambdas)
14267         Diag(L->getBeginLoc(), D);
14268     } else {
14269       // Mark the capture expressions odr-used. This was deferred
14270       // during lambda expression creation.
14271       for (auto *Lambda : Rec.Lambdas) {
14272         for (auto *C : Lambda->capture_inits())
14273           MarkDeclarationsReferencedInExpr(C);
14274       }
14275     }
14276   }
14277 
14278   // When are coming out of an unevaluated context, clear out any
14279   // temporaries that we may have created as part of the evaluation of
14280   // the expression in that context: they aren't relevant because they
14281   // will never be constructed.
14282   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14283     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14284                              ExprCleanupObjects.end());
14285     Cleanup = Rec.ParentCleanup;
14286     CleanupVarDeclMarking();
14287     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14288   // Otherwise, merge the contexts together.
14289   } else {
14290     Cleanup.mergeFrom(Rec.ParentCleanup);
14291     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14292                             Rec.SavedMaybeODRUseExprs.end());
14293   }
14294 
14295   // Pop the current expression evaluation context off the stack.
14296   ExprEvalContexts.pop_back();
14297 
14298   if (!ExprEvalContexts.empty())
14299     ExprEvalContexts.back().NumTypos += NumTypos;
14300   else
14301     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14302                             "last ExpressionEvaluationContextRecord");
14303 }
14304 
14305 void Sema::DiscardCleanupsInEvaluationContext() {
14306   ExprCleanupObjects.erase(
14307          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14308          ExprCleanupObjects.end());
14309   Cleanup.reset();
14310   MaybeODRUseExprs.clear();
14311 }
14312 
14313 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14314   if (!E->getType()->isVariablyModifiedType())
14315     return E;
14316   return TransformToPotentiallyEvaluated(E);
14317 }
14318 
14319 /// Are we within a context in which some evaluation could be performed (be it
14320 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14321 /// captured by C++'s idea of an "unevaluated context".
14322 static bool isEvaluatableContext(Sema &SemaRef) {
14323   switch (SemaRef.ExprEvalContexts.back().Context) {
14324     case Sema::ExpressionEvaluationContext::Unevaluated:
14325     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14326       // Expressions in this context are never evaluated.
14327       return false;
14328 
14329     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14330     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14331     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14332     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14333       // Expressions in this context could be evaluated.
14334       return true;
14335 
14336     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14337       // Referenced declarations will only be used if the construct in the
14338       // containing expression is used, at which point we'll be given another
14339       // turn to mark them.
14340       return false;
14341   }
14342   llvm_unreachable("Invalid context");
14343 }
14344 
14345 /// Are we within a context in which references to resolved functions or to
14346 /// variables result in odr-use?
14347 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14348   // An expression in a template is not really an expression until it's been
14349   // instantiated, so it doesn't trigger odr-use.
14350   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14351     return false;
14352 
14353   switch (SemaRef.ExprEvalContexts.back().Context) {
14354     case Sema::ExpressionEvaluationContext::Unevaluated:
14355     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14356     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14357     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14358       return false;
14359 
14360     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14361     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14362       return true;
14363 
14364     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14365       return false;
14366   }
14367   llvm_unreachable("Invalid context");
14368 }
14369 
14370 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14371   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14372   return Func->isConstexpr() &&
14373          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14374 }
14375 
14376 /// Mark a function referenced, and check whether it is odr-used
14377 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14378 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14379                                   bool MightBeOdrUse) {
14380   assert(Func && "No function?");
14381 
14382   Func->setReferenced();
14383 
14384   // C++11 [basic.def.odr]p3:
14385   //   A function whose name appears as a potentially-evaluated expression is
14386   //   odr-used if it is the unique lookup result or the selected member of a
14387   //   set of overloaded functions [...].
14388   //
14389   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14390   // can just check that here.
14391   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14392 
14393   // Determine whether we require a function definition to exist, per
14394   // C++11 [temp.inst]p3:
14395   //   Unless a function template specialization has been explicitly
14396   //   instantiated or explicitly specialized, the function template
14397   //   specialization is implicitly instantiated when the specialization is
14398   //   referenced in a context that requires a function definition to exist.
14399   //
14400   // That is either when this is an odr-use, or when a usage of a constexpr
14401   // function occurs within an evaluatable context.
14402   bool NeedDefinition =
14403       OdrUse || (isEvaluatableContext(*this) &&
14404                  isImplicitlyDefinableConstexprFunction(Func));
14405 
14406   // C++14 [temp.expl.spec]p6:
14407   //   If a template [...] is explicitly specialized then that specialization
14408   //   shall be declared before the first use of that specialization that would
14409   //   cause an implicit instantiation to take place, in every translation unit
14410   //   in which such a use occurs
14411   if (NeedDefinition &&
14412       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14413        Func->getMemberSpecializationInfo()))
14414     checkSpecializationVisibility(Loc, Func);
14415 
14416   // C++14 [except.spec]p17:
14417   //   An exception-specification is considered to be needed when:
14418   //   - the function is odr-used or, if it appears in an unevaluated operand,
14419   //     would be odr-used if the expression were potentially-evaluated;
14420   //
14421   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14422   // function is a pure virtual function we're calling, and in that case the
14423   // function was selected by overload resolution and we need to resolve its
14424   // exception specification for a different reason.
14425   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14426   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14427     ResolveExceptionSpec(Loc, FPT);
14428 
14429   // If we don't need to mark the function as used, and we don't need to
14430   // try to provide a definition, there's nothing more to do.
14431   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14432       (!NeedDefinition || Func->getBody()))
14433     return;
14434 
14435   // Note that this declaration has been used.
14436   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14437     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14438     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14439       if (Constructor->isDefaultConstructor()) {
14440         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14441           return;
14442         DefineImplicitDefaultConstructor(Loc, Constructor);
14443       } else if (Constructor->isCopyConstructor()) {
14444         DefineImplicitCopyConstructor(Loc, Constructor);
14445       } else if (Constructor->isMoveConstructor()) {
14446         DefineImplicitMoveConstructor(Loc, Constructor);
14447       }
14448     } else if (Constructor->getInheritedConstructor()) {
14449       DefineInheritingConstructor(Loc, Constructor);
14450     }
14451   } else if (CXXDestructorDecl *Destructor =
14452                  dyn_cast<CXXDestructorDecl>(Func)) {
14453     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14454     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14455       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14456         return;
14457       DefineImplicitDestructor(Loc, Destructor);
14458     }
14459     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14460       MarkVTableUsed(Loc, Destructor->getParent());
14461   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14462     if (MethodDecl->isOverloadedOperator() &&
14463         MethodDecl->getOverloadedOperator() == OO_Equal) {
14464       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14465       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14466         if (MethodDecl->isCopyAssignmentOperator())
14467           DefineImplicitCopyAssignment(Loc, MethodDecl);
14468         else if (MethodDecl->isMoveAssignmentOperator())
14469           DefineImplicitMoveAssignment(Loc, MethodDecl);
14470       }
14471     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14472                MethodDecl->getParent()->isLambda()) {
14473       CXXConversionDecl *Conversion =
14474           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14475       if (Conversion->isLambdaToBlockPointerConversion())
14476         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14477       else
14478         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14479     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14480       MarkVTableUsed(Loc, MethodDecl->getParent());
14481   }
14482 
14483   // Recursive functions should be marked when used from another function.
14484   // FIXME: Is this really right?
14485   if (CurContext == Func) return;
14486 
14487   // Implicit instantiation of function templates and member functions of
14488   // class templates.
14489   if (Func->isImplicitlyInstantiable()) {
14490     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14491     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14492     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14493     if (FirstInstantiation) {
14494       PointOfInstantiation = Loc;
14495       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14496     } else if (TSK != TSK_ImplicitInstantiation) {
14497       // Use the point of use as the point of instantiation, instead of the
14498       // point of explicit instantiation (which we track as the actual point of
14499       // instantiation). This gives better backtraces in diagnostics.
14500       PointOfInstantiation = Loc;
14501     }
14502 
14503     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14504         Func->isConstexpr()) {
14505       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14506           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14507           CodeSynthesisContexts.size())
14508         PendingLocalImplicitInstantiations.push_back(
14509             std::make_pair(Func, PointOfInstantiation));
14510       else if (Func->isConstexpr())
14511         // Do not defer instantiations of constexpr functions, to avoid the
14512         // expression evaluator needing to call back into Sema if it sees a
14513         // call to such a function.
14514         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14515       else {
14516         Func->setInstantiationIsPending(true);
14517         PendingInstantiations.push_back(std::make_pair(Func,
14518                                                        PointOfInstantiation));
14519         // Notify the consumer that a function was implicitly instantiated.
14520         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14521       }
14522     }
14523   } else {
14524     // Walk redefinitions, as some of them may be instantiable.
14525     for (auto i : Func->redecls()) {
14526       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14527         MarkFunctionReferenced(Loc, i, OdrUse);
14528     }
14529   }
14530 
14531   if (!OdrUse) return;
14532 
14533   // Keep track of used but undefined functions.
14534   if (!Func->isDefined()) {
14535     if (mightHaveNonExternalLinkage(Func))
14536       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14537     else if (Func->getMostRecentDecl()->isInlined() &&
14538              !LangOpts.GNUInline &&
14539              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14540       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14541     else if (isExternalWithNoLinkageType(Func))
14542       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14543   }
14544 
14545   Func->markUsed(Context);
14546 }
14547 
14548 static void
14549 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14550                                    ValueDecl *var, DeclContext *DC) {
14551   DeclContext *VarDC = var->getDeclContext();
14552 
14553   //  If the parameter still belongs to the translation unit, then
14554   //  we're actually just using one parameter in the declaration of
14555   //  the next.
14556   if (isa<ParmVarDecl>(var) &&
14557       isa<TranslationUnitDecl>(VarDC))
14558     return;
14559 
14560   // For C code, don't diagnose about capture if we're not actually in code
14561   // right now; it's impossible to write a non-constant expression outside of
14562   // function context, so we'll get other (more useful) diagnostics later.
14563   //
14564   // For C++, things get a bit more nasty... it would be nice to suppress this
14565   // diagnostic for certain cases like using a local variable in an array bound
14566   // for a member of a local class, but the correct predicate is not obvious.
14567   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14568     return;
14569 
14570   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14571   unsigned ContextKind = 3; // unknown
14572   if (isa<CXXMethodDecl>(VarDC) &&
14573       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14574     ContextKind = 2;
14575   } else if (isa<FunctionDecl>(VarDC)) {
14576     ContextKind = 0;
14577   } else if (isa<BlockDecl>(VarDC)) {
14578     ContextKind = 1;
14579   }
14580 
14581   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14582     << var << ValueKind << ContextKind << VarDC;
14583   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14584       << var;
14585 
14586   // FIXME: Add additional diagnostic info about class etc. which prevents
14587   // capture.
14588 }
14589 
14590 
14591 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14592                                       bool &SubCapturesAreNested,
14593                                       QualType &CaptureType,
14594                                       QualType &DeclRefType) {
14595    // Check whether we've already captured it.
14596   if (CSI->CaptureMap.count(Var)) {
14597     // If we found a capture, any subcaptures are nested.
14598     SubCapturesAreNested = true;
14599 
14600     // Retrieve the capture type for this variable.
14601     CaptureType = CSI->getCapture(Var).getCaptureType();
14602 
14603     // Compute the type of an expression that refers to this variable.
14604     DeclRefType = CaptureType.getNonReferenceType();
14605 
14606     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14607     // are mutable in the sense that user can change their value - they are
14608     // private instances of the captured declarations.
14609     const Capture &Cap = CSI->getCapture(Var);
14610     if (Cap.isCopyCapture() &&
14611         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14612         !(isa<CapturedRegionScopeInfo>(CSI) &&
14613           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14614       DeclRefType.addConst();
14615     return true;
14616   }
14617   return false;
14618 }
14619 
14620 // Only block literals, captured statements, and lambda expressions can
14621 // capture; other scopes don't work.
14622 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14623                                  SourceLocation Loc,
14624                                  const bool Diagnose, Sema &S) {
14625   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14626     return getLambdaAwareParentOfDeclContext(DC);
14627   else if (Var->hasLocalStorage()) {
14628     if (Diagnose)
14629        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14630   }
14631   return nullptr;
14632 }
14633 
14634 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14635 // certain types of variables (unnamed, variably modified types etc.)
14636 // so check for eligibility.
14637 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14638                                  SourceLocation Loc,
14639                                  const bool Diagnose, Sema &S) {
14640 
14641   bool IsBlock = isa<BlockScopeInfo>(CSI);
14642   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14643 
14644   // Lambdas are not allowed to capture unnamed variables
14645   // (e.g. anonymous unions).
14646   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14647   // assuming that's the intent.
14648   if (IsLambda && !Var->getDeclName()) {
14649     if (Diagnose) {
14650       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14651       S.Diag(Var->getLocation(), diag::note_declared_at);
14652     }
14653     return false;
14654   }
14655 
14656   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14657   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14658     if (Diagnose) {
14659       S.Diag(Loc, diag::err_ref_vm_type);
14660       S.Diag(Var->getLocation(), diag::note_previous_decl)
14661         << Var->getDeclName();
14662     }
14663     return false;
14664   }
14665   // Prohibit structs with flexible array members too.
14666   // We cannot capture what is in the tail end of the struct.
14667   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14668     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14669       if (Diagnose) {
14670         if (IsBlock)
14671           S.Diag(Loc, diag::err_ref_flexarray_type);
14672         else
14673           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14674             << Var->getDeclName();
14675         S.Diag(Var->getLocation(), diag::note_previous_decl)
14676           << Var->getDeclName();
14677       }
14678       return false;
14679     }
14680   }
14681   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14682   // Lambdas and captured statements are not allowed to capture __block
14683   // variables; they don't support the expected semantics.
14684   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14685     if (Diagnose) {
14686       S.Diag(Loc, diag::err_capture_block_variable)
14687         << Var->getDeclName() << !IsLambda;
14688       S.Diag(Var->getLocation(), diag::note_previous_decl)
14689         << Var->getDeclName();
14690     }
14691     return false;
14692   }
14693   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14694   if (S.getLangOpts().OpenCL && IsBlock &&
14695       Var->getType()->isBlockPointerType()) {
14696     if (Diagnose)
14697       S.Diag(Loc, diag::err_opencl_block_ref_block);
14698     return false;
14699   }
14700 
14701   return true;
14702 }
14703 
14704 // Returns true if the capture by block was successful.
14705 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14706                                  SourceLocation Loc,
14707                                  const bool BuildAndDiagnose,
14708                                  QualType &CaptureType,
14709                                  QualType &DeclRefType,
14710                                  const bool Nested,
14711                                  Sema &S) {
14712   Expr *CopyExpr = nullptr;
14713   bool ByRef = false;
14714 
14715   // Blocks are not allowed to capture arrays, excepting OpenCL.
14716   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14717   // (decayed to pointers).
14718   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14719     if (BuildAndDiagnose) {
14720       S.Diag(Loc, diag::err_ref_array_type);
14721       S.Diag(Var->getLocation(), diag::note_previous_decl)
14722       << Var->getDeclName();
14723     }
14724     return false;
14725   }
14726 
14727   // Forbid the block-capture of autoreleasing variables.
14728   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14729     if (BuildAndDiagnose) {
14730       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14731         << /*block*/ 0;
14732       S.Diag(Var->getLocation(), diag::note_previous_decl)
14733         << Var->getDeclName();
14734     }
14735     return false;
14736   }
14737 
14738   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14739   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14740     // This function finds out whether there is an AttributedType of kind
14741     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14742     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14743     // rather than being added implicitly by the compiler.
14744     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14745       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14746         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
14747           return true;
14748 
14749         // Peel off AttributedTypes that are not of kind ObjCOwnership.
14750         Ty = AttrTy->getModifiedType();
14751       }
14752 
14753       return false;
14754     };
14755 
14756     QualType PointeeTy = PT->getPointeeType();
14757 
14758     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14759         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14760         !IsObjCOwnershipAttributedType(PointeeTy)) {
14761       if (BuildAndDiagnose) {
14762         SourceLocation VarLoc = Var->getLocation();
14763         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14764         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14765       }
14766     }
14767   }
14768 
14769   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14770   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14771       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14772     // Block capture by reference does not change the capture or
14773     // declaration reference types.
14774     ByRef = true;
14775   } else {
14776     // Block capture by copy introduces 'const'.
14777     CaptureType = CaptureType.getNonReferenceType().withConst();
14778     DeclRefType = CaptureType;
14779 
14780     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14781       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14782         // The capture logic needs the destructor, so make sure we mark it.
14783         // Usually this is unnecessary because most local variables have
14784         // their destructors marked at declaration time, but parameters are
14785         // an exception because it's technically only the call site that
14786         // actually requires the destructor.
14787         if (isa<ParmVarDecl>(Var))
14788           S.FinalizeVarWithDestructor(Var, Record);
14789 
14790         // Enter a new evaluation context to insulate the copy
14791         // full-expression.
14792         EnterExpressionEvaluationContext scope(
14793             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14794 
14795         // According to the blocks spec, the capture of a variable from
14796         // the stack requires a const copy constructor.  This is not true
14797         // of the copy/move done to move a __block variable to the heap.
14798         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14799                                                   DeclRefType.withConst(),
14800                                                   VK_LValue, Loc);
14801 
14802         ExprResult Result
14803           = S.PerformCopyInitialization(
14804               InitializedEntity::InitializeBlock(Var->getLocation(),
14805                                                   CaptureType, false),
14806               Loc, DeclRef);
14807 
14808         // Build a full-expression copy expression if initialization
14809         // succeeded and used a non-trivial constructor.  Recover from
14810         // errors by pretending that the copy isn't necessary.
14811         if (!Result.isInvalid() &&
14812             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14813                 ->isTrivial()) {
14814           Result = S.MaybeCreateExprWithCleanups(Result);
14815           CopyExpr = Result.get();
14816         }
14817       }
14818     }
14819   }
14820 
14821   // Actually capture the variable.
14822   if (BuildAndDiagnose)
14823     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14824                     SourceLocation(), CaptureType, CopyExpr);
14825 
14826   return true;
14827 
14828 }
14829 
14830 
14831 /// Capture the given variable in the captured region.
14832 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14833                                     VarDecl *Var,
14834                                     SourceLocation Loc,
14835                                     const bool BuildAndDiagnose,
14836                                     QualType &CaptureType,
14837                                     QualType &DeclRefType,
14838                                     const bool RefersToCapturedVariable,
14839                                     Sema &S) {
14840   // By default, capture variables by reference.
14841   bool ByRef = true;
14842   // Using an LValue reference type is consistent with Lambdas (see below).
14843   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14844     if (S.isOpenMPCapturedDecl(Var)) {
14845       bool HasConst = DeclRefType.isConstQualified();
14846       DeclRefType = DeclRefType.getUnqualifiedType();
14847       // Don't lose diagnostics about assignments to const.
14848       if (HasConst)
14849         DeclRefType.addConst();
14850     }
14851     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14852   }
14853 
14854   if (ByRef)
14855     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14856   else
14857     CaptureType = DeclRefType;
14858 
14859   Expr *CopyExpr = nullptr;
14860   if (BuildAndDiagnose) {
14861     // The current implementation assumes that all variables are captured
14862     // by references. Since there is no capture by copy, no expression
14863     // evaluation will be needed.
14864     RecordDecl *RD = RSI->TheRecordDecl;
14865 
14866     FieldDecl *Field
14867       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14868                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14869                           nullptr, false, ICIS_NoInit);
14870     Field->setImplicit(true);
14871     Field->setAccess(AS_private);
14872     RD->addDecl(Field);
14873     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14874       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14875 
14876     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14877                                             DeclRefType, VK_LValue, Loc);
14878     Var->setReferenced(true);
14879     Var->markUsed(S.Context);
14880   }
14881 
14882   // Actually capture the variable.
14883   if (BuildAndDiagnose)
14884     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14885                     SourceLocation(), CaptureType, CopyExpr);
14886 
14887 
14888   return true;
14889 }
14890 
14891 /// Create a field within the lambda class for the variable
14892 /// being captured.
14893 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14894                                     QualType FieldType, QualType DeclRefType,
14895                                     SourceLocation Loc,
14896                                     bool RefersToCapturedVariable) {
14897   CXXRecordDecl *Lambda = LSI->Lambda;
14898 
14899   // Build the non-static data member.
14900   FieldDecl *Field
14901     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14902                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14903                         nullptr, false, ICIS_NoInit);
14904   Field->setImplicit(true);
14905   Field->setAccess(AS_private);
14906   Lambda->addDecl(Field);
14907 }
14908 
14909 /// Capture the given variable in the lambda.
14910 static bool captureInLambda(LambdaScopeInfo *LSI,
14911                             VarDecl *Var,
14912                             SourceLocation Loc,
14913                             const bool BuildAndDiagnose,
14914                             QualType &CaptureType,
14915                             QualType &DeclRefType,
14916                             const bool RefersToCapturedVariable,
14917                             const Sema::TryCaptureKind Kind,
14918                             SourceLocation EllipsisLoc,
14919                             const bool IsTopScope,
14920                             Sema &S) {
14921 
14922   // Determine whether we are capturing by reference or by value.
14923   bool ByRef = false;
14924   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14925     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14926   } else {
14927     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14928   }
14929 
14930   // Compute the type of the field that will capture this variable.
14931   if (ByRef) {
14932     // C++11 [expr.prim.lambda]p15:
14933     //   An entity is captured by reference if it is implicitly or
14934     //   explicitly captured but not captured by copy. It is
14935     //   unspecified whether additional unnamed non-static data
14936     //   members are declared in the closure type for entities
14937     //   captured by reference.
14938     //
14939     // FIXME: It is not clear whether we want to build an lvalue reference
14940     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14941     // to do the former, while EDG does the latter. Core issue 1249 will
14942     // clarify, but for now we follow GCC because it's a more permissive and
14943     // easily defensible position.
14944     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14945   } else {
14946     // C++11 [expr.prim.lambda]p14:
14947     //   For each entity captured by copy, an unnamed non-static
14948     //   data member is declared in the closure type. The
14949     //   declaration order of these members is unspecified. The type
14950     //   of such a data member is the type of the corresponding
14951     //   captured entity if the entity is not a reference to an
14952     //   object, or the referenced type otherwise. [Note: If the
14953     //   captured entity is a reference to a function, the
14954     //   corresponding data member is also a reference to a
14955     //   function. - end note ]
14956     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14957       if (!RefType->getPointeeType()->isFunctionType())
14958         CaptureType = RefType->getPointeeType();
14959     }
14960 
14961     // Forbid the lambda copy-capture of autoreleasing variables.
14962     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14963       if (BuildAndDiagnose) {
14964         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14965         S.Diag(Var->getLocation(), diag::note_previous_decl)
14966           << Var->getDeclName();
14967       }
14968       return false;
14969     }
14970 
14971     // Make sure that by-copy captures are of a complete and non-abstract type.
14972     if (BuildAndDiagnose) {
14973       if (!CaptureType->isDependentType() &&
14974           S.RequireCompleteType(Loc, CaptureType,
14975                                 diag::err_capture_of_incomplete_type,
14976                                 Var->getDeclName()))
14977         return false;
14978 
14979       if (S.RequireNonAbstractType(Loc, CaptureType,
14980                                    diag::err_capture_of_abstract_type))
14981         return false;
14982     }
14983   }
14984 
14985   // Capture this variable in the lambda.
14986   if (BuildAndDiagnose)
14987     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14988                             RefersToCapturedVariable);
14989 
14990   // Compute the type of a reference to this captured variable.
14991   if (ByRef)
14992     DeclRefType = CaptureType.getNonReferenceType();
14993   else {
14994     // C++ [expr.prim.lambda]p5:
14995     //   The closure type for a lambda-expression has a public inline
14996     //   function call operator [...]. This function call operator is
14997     //   declared const (9.3.1) if and only if the lambda-expression's
14998     //   parameter-declaration-clause is not followed by mutable.
14999     DeclRefType = CaptureType.getNonReferenceType();
15000     if (!LSI->Mutable && !CaptureType->isReferenceType())
15001       DeclRefType.addConst();
15002   }
15003 
15004   // Add the capture.
15005   if (BuildAndDiagnose)
15006     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15007                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15008 
15009   return true;
15010 }
15011 
15012 bool Sema::tryCaptureVariable(
15013     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15014     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15015     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15016   // An init-capture is notionally from the context surrounding its
15017   // declaration, but its parent DC is the lambda class.
15018   DeclContext *VarDC = Var->getDeclContext();
15019   if (Var->isInitCapture())
15020     VarDC = VarDC->getParent();
15021 
15022   DeclContext *DC = CurContext;
15023   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15024       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15025   // We need to sync up the Declaration Context with the
15026   // FunctionScopeIndexToStopAt
15027   if (FunctionScopeIndexToStopAt) {
15028     unsigned FSIndex = FunctionScopes.size() - 1;
15029     while (FSIndex != MaxFunctionScopesIndex) {
15030       DC = getLambdaAwareParentOfDeclContext(DC);
15031       --FSIndex;
15032     }
15033   }
15034 
15035 
15036   // If the variable is declared in the current context, there is no need to
15037   // capture it.
15038   if (VarDC == DC) return true;
15039 
15040   // Capture global variables if it is required to use private copy of this
15041   // variable.
15042   bool IsGlobal = !Var->hasLocalStorage();
15043   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15044     return true;
15045   Var = Var->getCanonicalDecl();
15046 
15047   // Walk up the stack to determine whether we can capture the variable,
15048   // performing the "simple" checks that don't depend on type. We stop when
15049   // we've either hit the declared scope of the variable or find an existing
15050   // capture of that variable.  We start from the innermost capturing-entity
15051   // (the DC) and ensure that all intervening capturing-entities
15052   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15053   // declcontext can either capture the variable or have already captured
15054   // the variable.
15055   CaptureType = Var->getType();
15056   DeclRefType = CaptureType.getNonReferenceType();
15057   bool Nested = false;
15058   bool Explicit = (Kind != TryCapture_Implicit);
15059   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15060   do {
15061     // Only block literals, captured statements, and lambda expressions can
15062     // capture; other scopes don't work.
15063     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15064                                                               ExprLoc,
15065                                                               BuildAndDiagnose,
15066                                                               *this);
15067     // We need to check for the parent *first* because, if we *have*
15068     // private-captured a global variable, we need to recursively capture it in
15069     // intermediate blocks, lambdas, etc.
15070     if (!ParentDC) {
15071       if (IsGlobal) {
15072         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15073         break;
15074       }
15075       return true;
15076     }
15077 
15078     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15079     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15080 
15081 
15082     // Check whether we've already captured it.
15083     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15084                                              DeclRefType)) {
15085       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15086       break;
15087     }
15088     // If we are instantiating a generic lambda call operator body,
15089     // we do not want to capture new variables.  What was captured
15090     // during either a lambdas transformation or initial parsing
15091     // should be used.
15092     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15093       if (BuildAndDiagnose) {
15094         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15095         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15096           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15097           Diag(Var->getLocation(), diag::note_previous_decl)
15098              << Var->getDeclName();
15099           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15100         } else
15101           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15102       }
15103       return true;
15104     }
15105     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15106     // certain types of variables (unnamed, variably modified types etc.)
15107     // so check for eligibility.
15108     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15109        return true;
15110 
15111     // Try to capture variable-length arrays types.
15112     if (Var->getType()->isVariablyModifiedType()) {
15113       // We're going to walk down into the type and look for VLA
15114       // expressions.
15115       QualType QTy = Var->getType();
15116       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15117         QTy = PVD->getOriginalType();
15118       captureVariablyModifiedType(Context, QTy, CSI);
15119     }
15120 
15121     if (getLangOpts().OpenMP) {
15122       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15123         // OpenMP private variables should not be captured in outer scope, so
15124         // just break here. Similarly, global variables that are captured in a
15125         // target region should not be captured outside the scope of the region.
15126         if (RSI->CapRegionKind == CR_OpenMP) {
15127           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15128           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15129                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15130           // When we detect target captures we are looking from inside the
15131           // target region, therefore we need to propagate the capture from the
15132           // enclosing region. Therefore, the capture is not initially nested.
15133           if (IsTargetCap)
15134             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15135 
15136           if (IsTargetCap || IsOpenMPPrivateDecl) {
15137             Nested = !IsTargetCap;
15138             DeclRefType = DeclRefType.getUnqualifiedType();
15139             CaptureType = Context.getLValueReferenceType(DeclRefType);
15140             break;
15141           }
15142         }
15143       }
15144     }
15145     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15146       // No capture-default, and this is not an explicit capture
15147       // so cannot capture this variable.
15148       if (BuildAndDiagnose) {
15149         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15150         Diag(Var->getLocation(), diag::note_previous_decl)
15151           << Var->getDeclName();
15152         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15153           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15154                diag::note_lambda_decl);
15155         // FIXME: If we error out because an outer lambda can not implicitly
15156         // capture a variable that an inner lambda explicitly captures, we
15157         // should have the inner lambda do the explicit capture - because
15158         // it makes for cleaner diagnostics later.  This would purely be done
15159         // so that the diagnostic does not misleadingly claim that a variable
15160         // can not be captured by a lambda implicitly even though it is captured
15161         // explicitly.  Suggestion:
15162         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15163         //    at the function head
15164         //  - cache the StartingDeclContext - this must be a lambda
15165         //  - captureInLambda in the innermost lambda the variable.
15166       }
15167       return true;
15168     }
15169 
15170     FunctionScopesIndex--;
15171     DC = ParentDC;
15172     Explicit = false;
15173   } while (!VarDC->Equals(DC));
15174 
15175   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15176   // computing the type of the capture at each step, checking type-specific
15177   // requirements, and adding captures if requested.
15178   // If the variable had already been captured previously, we start capturing
15179   // at the lambda nested within that one.
15180   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15181        ++I) {
15182     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15183 
15184     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15185       if (!captureInBlock(BSI, Var, ExprLoc,
15186                           BuildAndDiagnose, CaptureType,
15187                           DeclRefType, Nested, *this))
15188         return true;
15189       Nested = true;
15190     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15191       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15192                                    BuildAndDiagnose, CaptureType,
15193                                    DeclRefType, Nested, *this))
15194         return true;
15195       Nested = true;
15196     } else {
15197       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15198       if (!captureInLambda(LSI, Var, ExprLoc,
15199                            BuildAndDiagnose, CaptureType,
15200                            DeclRefType, Nested, Kind, EllipsisLoc,
15201                             /*IsTopScope*/I == N - 1, *this))
15202         return true;
15203       Nested = true;
15204     }
15205   }
15206   return false;
15207 }
15208 
15209 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15210                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15211   QualType CaptureType;
15212   QualType DeclRefType;
15213   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15214                             /*BuildAndDiagnose=*/true, CaptureType,
15215                             DeclRefType, nullptr);
15216 }
15217 
15218 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15219   QualType CaptureType;
15220   QualType DeclRefType;
15221   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15222                              /*BuildAndDiagnose=*/false, CaptureType,
15223                              DeclRefType, nullptr);
15224 }
15225 
15226 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15227   QualType CaptureType;
15228   QualType DeclRefType;
15229 
15230   // Determine whether we can capture this variable.
15231   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15232                          /*BuildAndDiagnose=*/false, CaptureType,
15233                          DeclRefType, nullptr))
15234     return QualType();
15235 
15236   return DeclRefType;
15237 }
15238 
15239 
15240 
15241 // If either the type of the variable or the initializer is dependent,
15242 // return false. Otherwise, determine whether the variable is a constant
15243 // expression. Use this if you need to know if a variable that might or
15244 // might not be dependent is truly a constant expression.
15245 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15246     ASTContext &Context) {
15247 
15248   if (Var->getType()->isDependentType())
15249     return false;
15250   const VarDecl *DefVD = nullptr;
15251   Var->getAnyInitializer(DefVD);
15252   if (!DefVD)
15253     return false;
15254   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15255   Expr *Init = cast<Expr>(Eval->Value);
15256   if (Init->isValueDependent())
15257     return false;
15258   return IsVariableAConstantExpression(Var, Context);
15259 }
15260 
15261 
15262 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15263   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15264   // an object that satisfies the requirements for appearing in a
15265   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15266   // is immediately applied."  This function handles the lvalue-to-rvalue
15267   // conversion part.
15268   MaybeODRUseExprs.erase(E->IgnoreParens());
15269 
15270   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15271   // to a variable that is a constant expression, and if so, identify it as
15272   // a reference to a variable that does not involve an odr-use of that
15273   // variable.
15274   if (LambdaScopeInfo *LSI = getCurLambda()) {
15275     Expr *SansParensExpr = E->IgnoreParens();
15276     VarDecl *Var = nullptr;
15277     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15278       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15279     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15280       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15281 
15282     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15283       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15284   }
15285 }
15286 
15287 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15288   Res = CorrectDelayedTyposInExpr(Res);
15289 
15290   if (!Res.isUsable())
15291     return Res;
15292 
15293   // If a constant-expression is a reference to a variable where we delay
15294   // deciding whether it is an odr-use, just assume we will apply the
15295   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15296   // (a non-type template argument), we have special handling anyway.
15297   UpdateMarkingForLValueToRValue(Res.get());
15298   return Res;
15299 }
15300 
15301 void Sema::CleanupVarDeclMarking() {
15302   for (Expr *E : MaybeODRUseExprs) {
15303     VarDecl *Var;
15304     SourceLocation Loc;
15305     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15306       Var = cast<VarDecl>(DRE->getDecl());
15307       Loc = DRE->getLocation();
15308     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15309       Var = cast<VarDecl>(ME->getMemberDecl());
15310       Loc = ME->getMemberLoc();
15311     } else {
15312       llvm_unreachable("Unexpected expression");
15313     }
15314 
15315     MarkVarDeclODRUsed(Var, Loc, *this,
15316                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15317   }
15318 
15319   MaybeODRUseExprs.clear();
15320 }
15321 
15322 
15323 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15324                                     VarDecl *Var, Expr *E) {
15325   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15326          "Invalid Expr argument to DoMarkVarDeclReferenced");
15327   Var->setReferenced();
15328 
15329   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15330 
15331   bool OdrUseContext = isOdrUseContext(SemaRef);
15332   bool UsableInConstantExpr =
15333       Var->isUsableInConstantExpressions(SemaRef.Context);
15334   bool NeedDefinition =
15335       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15336 
15337   VarTemplateSpecializationDecl *VarSpec =
15338       dyn_cast<VarTemplateSpecializationDecl>(Var);
15339   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15340          "Can't instantiate a partial template specialization.");
15341 
15342   // If this might be a member specialization of a static data member, check
15343   // the specialization is visible. We already did the checks for variable
15344   // template specializations when we created them.
15345   if (NeedDefinition && TSK != TSK_Undeclared &&
15346       !isa<VarTemplateSpecializationDecl>(Var))
15347     SemaRef.checkSpecializationVisibility(Loc, Var);
15348 
15349   // Perform implicit instantiation of static data members, static data member
15350   // templates of class templates, and variable template specializations. Delay
15351   // instantiations of variable templates, except for those that could be used
15352   // in a constant expression.
15353   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15354     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15355     // instantiation declaration if a variable is usable in a constant
15356     // expression (among other cases).
15357     bool TryInstantiating =
15358         TSK == TSK_ImplicitInstantiation ||
15359         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15360 
15361     if (TryInstantiating) {
15362       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15363       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15364       if (FirstInstantiation) {
15365         PointOfInstantiation = Loc;
15366         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15367       }
15368 
15369       bool InstantiationDependent = false;
15370       bool IsNonDependent =
15371           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15372                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15373                   : true;
15374 
15375       // Do not instantiate specializations that are still type-dependent.
15376       if (IsNonDependent) {
15377         if (UsableInConstantExpr) {
15378           // Do not defer instantiations of variables that could be used in a
15379           // constant expression.
15380           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15381         } else if (FirstInstantiation ||
15382                    isa<VarTemplateSpecializationDecl>(Var)) {
15383           // FIXME: For a specialization of a variable template, we don't
15384           // distinguish between "declaration and type implicitly instantiated"
15385           // and "implicit instantiation of definition requested", so we have
15386           // no direct way to avoid enqueueing the pending instantiation
15387           // multiple times.
15388           SemaRef.PendingInstantiations
15389               .push_back(std::make_pair(Var, PointOfInstantiation));
15390         }
15391       }
15392     }
15393   }
15394 
15395   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15396   // the requirements for appearing in a constant expression (5.19) and, if
15397   // it is an object, the lvalue-to-rvalue conversion (4.1)
15398   // is immediately applied."  We check the first part here, and
15399   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15400   // Note that we use the C++11 definition everywhere because nothing in
15401   // C++03 depends on whether we get the C++03 version correct. The second
15402   // part does not apply to references, since they are not objects.
15403   if (OdrUseContext && E &&
15404       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15405     // A reference initialized by a constant expression can never be
15406     // odr-used, so simply ignore it.
15407     if (!Var->getType()->isReferenceType() ||
15408         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15409       SemaRef.MaybeODRUseExprs.insert(E);
15410   } else if (OdrUseContext) {
15411     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15412                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15413   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15414     // If this is a dependent context, we don't need to mark variables as
15415     // odr-used, but we may still need to track them for lambda capture.
15416     // FIXME: Do we also need to do this inside dependent typeid expressions
15417     // (which are modeled as unevaluated at this point)?
15418     const bool RefersToEnclosingScope =
15419         (SemaRef.CurContext != Var->getDeclContext() &&
15420          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15421     if (RefersToEnclosingScope) {
15422       LambdaScopeInfo *const LSI =
15423           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15424       if (LSI && (!LSI->CallOperator ||
15425                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15426         // If a variable could potentially be odr-used, defer marking it so
15427         // until we finish analyzing the full expression for any
15428         // lvalue-to-rvalue
15429         // or discarded value conversions that would obviate odr-use.
15430         // Add it to the list of potential captures that will be analyzed
15431         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15432         // unless the variable is a reference that was initialized by a constant
15433         // expression (this will never need to be captured or odr-used).
15434         assert(E && "Capture variable should be used in an expression.");
15435         if (!Var->getType()->isReferenceType() ||
15436             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15437           LSI->addPotentialCapture(E->IgnoreParens());
15438       }
15439     }
15440   }
15441 }
15442 
15443 /// Mark a variable referenced, and check whether it is odr-used
15444 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15445 /// used directly for normal expressions referring to VarDecl.
15446 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15447   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15448 }
15449 
15450 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15451                                Decl *D, Expr *E, bool MightBeOdrUse) {
15452   if (SemaRef.isInOpenMPDeclareTargetContext())
15453     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15454 
15455   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15456     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15457     return;
15458   }
15459 
15460   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15461 
15462   // If this is a call to a method via a cast, also mark the method in the
15463   // derived class used in case codegen can devirtualize the call.
15464   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15465   if (!ME)
15466     return;
15467   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15468   if (!MD)
15469     return;
15470   // Only attempt to devirtualize if this is truly a virtual call.
15471   bool IsVirtualCall = MD->isVirtual() &&
15472                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15473   if (!IsVirtualCall)
15474     return;
15475 
15476   // If it's possible to devirtualize the call, mark the called function
15477   // referenced.
15478   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15479       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15480   if (DM)
15481     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15482 }
15483 
15484 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15485 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15486   // TODO: update this with DR# once a defect report is filed.
15487   // C++11 defect. The address of a pure member should not be an ODR use, even
15488   // if it's a qualified reference.
15489   bool OdrUse = true;
15490   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15491     if (Method->isVirtual() &&
15492         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15493       OdrUse = false;
15494   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15495 }
15496 
15497 /// Perform reference-marking and odr-use handling for a MemberExpr.
15498 void Sema::MarkMemberReferenced(MemberExpr *E) {
15499   // C++11 [basic.def.odr]p2:
15500   //   A non-overloaded function whose name appears as a potentially-evaluated
15501   //   expression or a member of a set of candidate functions, if selected by
15502   //   overload resolution when referred to from a potentially-evaluated
15503   //   expression, is odr-used, unless it is a pure virtual function and its
15504   //   name is not explicitly qualified.
15505   bool MightBeOdrUse = true;
15506   if (E->performsVirtualDispatch(getLangOpts())) {
15507     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15508       if (Method->isPure())
15509         MightBeOdrUse = false;
15510   }
15511   SourceLocation Loc =
15512       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15513   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15514 }
15515 
15516 /// Perform marking for a reference to an arbitrary declaration.  It
15517 /// marks the declaration referenced, and performs odr-use checking for
15518 /// functions and variables. This method should not be used when building a
15519 /// normal expression which refers to a variable.
15520 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15521                                  bool MightBeOdrUse) {
15522   if (MightBeOdrUse) {
15523     if (auto *VD = dyn_cast<VarDecl>(D)) {
15524       MarkVariableReferenced(Loc, VD);
15525       return;
15526     }
15527   }
15528   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15529     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15530     return;
15531   }
15532   D->setReferenced();
15533 }
15534 
15535 namespace {
15536   // Mark all of the declarations used by a type as referenced.
15537   // FIXME: Not fully implemented yet! We need to have a better understanding
15538   // of when we're entering a context we should not recurse into.
15539   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15540   // TreeTransforms rebuilding the type in a new context. Rather than
15541   // duplicating the TreeTransform logic, we should consider reusing it here.
15542   // Currently that causes problems when rebuilding LambdaExprs.
15543   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15544     Sema &S;
15545     SourceLocation Loc;
15546 
15547   public:
15548     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15549 
15550     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15551 
15552     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15553   };
15554 }
15555 
15556 bool MarkReferencedDecls::TraverseTemplateArgument(
15557     const TemplateArgument &Arg) {
15558   {
15559     // A non-type template argument is a constant-evaluated context.
15560     EnterExpressionEvaluationContext Evaluated(
15561         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15562     if (Arg.getKind() == TemplateArgument::Declaration) {
15563       if (Decl *D = Arg.getAsDecl())
15564         S.MarkAnyDeclReferenced(Loc, D, true);
15565     } else if (Arg.getKind() == TemplateArgument::Expression) {
15566       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15567     }
15568   }
15569 
15570   return Inherited::TraverseTemplateArgument(Arg);
15571 }
15572 
15573 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15574   MarkReferencedDecls Marker(*this, Loc);
15575   Marker.TraverseType(T);
15576 }
15577 
15578 namespace {
15579   /// Helper class that marks all of the declarations referenced by
15580   /// potentially-evaluated subexpressions as "referenced".
15581   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15582     Sema &S;
15583     bool SkipLocalVariables;
15584 
15585   public:
15586     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15587 
15588     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15589       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15590 
15591     void VisitDeclRefExpr(DeclRefExpr *E) {
15592       // If we were asked not to visit local variables, don't.
15593       if (SkipLocalVariables) {
15594         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15595           if (VD->hasLocalStorage())
15596             return;
15597       }
15598 
15599       S.MarkDeclRefReferenced(E);
15600     }
15601 
15602     void VisitMemberExpr(MemberExpr *E) {
15603       S.MarkMemberReferenced(E);
15604       Inherited::VisitMemberExpr(E);
15605     }
15606 
15607     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15608       S.MarkFunctionReferenced(
15609           E->getBeginLoc(),
15610           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15611       Visit(E->getSubExpr());
15612     }
15613 
15614     void VisitCXXNewExpr(CXXNewExpr *E) {
15615       if (E->getOperatorNew())
15616         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15617       if (E->getOperatorDelete())
15618         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15619       Inherited::VisitCXXNewExpr(E);
15620     }
15621 
15622     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15623       if (E->getOperatorDelete())
15624         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15625       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15626       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15627         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15628         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15629       }
15630 
15631       Inherited::VisitCXXDeleteExpr(E);
15632     }
15633 
15634     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15635       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15636       Inherited::VisitCXXConstructExpr(E);
15637     }
15638 
15639     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15640       Visit(E->getExpr());
15641     }
15642 
15643     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15644       Inherited::VisitImplicitCastExpr(E);
15645 
15646       if (E->getCastKind() == CK_LValueToRValue)
15647         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15648     }
15649   };
15650 }
15651 
15652 /// Mark any declarations that appear within this expression or any
15653 /// potentially-evaluated subexpressions as "referenced".
15654 ///
15655 /// \param SkipLocalVariables If true, don't mark local variables as
15656 /// 'referenced'.
15657 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15658                                             bool SkipLocalVariables) {
15659   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15660 }
15661 
15662 /// Emit a diagnostic that describes an effect on the run-time behavior
15663 /// of the program being compiled.
15664 ///
15665 /// This routine emits the given diagnostic when the code currently being
15666 /// type-checked is "potentially evaluated", meaning that there is a
15667 /// possibility that the code will actually be executable. Code in sizeof()
15668 /// expressions, code used only during overload resolution, etc., are not
15669 /// potentially evaluated. This routine will suppress such diagnostics or,
15670 /// in the absolutely nutty case of potentially potentially evaluated
15671 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15672 /// later.
15673 ///
15674 /// This routine should be used for all diagnostics that describe the run-time
15675 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15676 /// Failure to do so will likely result in spurious diagnostics or failures
15677 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15678 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15679                                const PartialDiagnostic &PD) {
15680   switch (ExprEvalContexts.back().Context) {
15681   case ExpressionEvaluationContext::Unevaluated:
15682   case ExpressionEvaluationContext::UnevaluatedList:
15683   case ExpressionEvaluationContext::UnevaluatedAbstract:
15684   case ExpressionEvaluationContext::DiscardedStatement:
15685     // The argument will never be evaluated, so don't complain.
15686     break;
15687 
15688   case ExpressionEvaluationContext::ConstantEvaluated:
15689     // Relevant diagnostics should be produced by constant evaluation.
15690     break;
15691 
15692   case ExpressionEvaluationContext::PotentiallyEvaluated:
15693   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15694     if (Statement && getCurFunctionOrMethodDecl()) {
15695       FunctionScopes.back()->PossiblyUnreachableDiags.
15696         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15697       return true;
15698     }
15699 
15700     // The initializer of a constexpr variable or of the first declaration of a
15701     // static data member is not syntactically a constant evaluated constant,
15702     // but nonetheless is always required to be a constant expression, so we
15703     // can skip diagnosing.
15704     // FIXME: Using the mangling context here is a hack.
15705     if (auto *VD = dyn_cast_or_null<VarDecl>(
15706             ExprEvalContexts.back().ManglingContextDecl)) {
15707       if (VD->isConstexpr() ||
15708           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15709         break;
15710       // FIXME: For any other kind of variable, we should build a CFG for its
15711       // initializer and check whether the context in question is reachable.
15712     }
15713 
15714     Diag(Loc, PD);
15715     return true;
15716   }
15717 
15718   return false;
15719 }
15720 
15721 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15722                                CallExpr *CE, FunctionDecl *FD) {
15723   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15724     return false;
15725 
15726   // If we're inside a decltype's expression, don't check for a valid return
15727   // type or construct temporaries until we know whether this is the last call.
15728   if (ExprEvalContexts.back().ExprContext ==
15729       ExpressionEvaluationContextRecord::EK_Decltype) {
15730     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15731     return false;
15732   }
15733 
15734   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15735     FunctionDecl *FD;
15736     CallExpr *CE;
15737 
15738   public:
15739     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15740       : FD(FD), CE(CE) { }
15741 
15742     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15743       if (!FD) {
15744         S.Diag(Loc, diag::err_call_incomplete_return)
15745           << T << CE->getSourceRange();
15746         return;
15747       }
15748 
15749       S.Diag(Loc, diag::err_call_function_incomplete_return)
15750         << CE->getSourceRange() << FD->getDeclName() << T;
15751       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15752           << FD->getDeclName();
15753     }
15754   } Diagnoser(FD, CE);
15755 
15756   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15757     return true;
15758 
15759   return false;
15760 }
15761 
15762 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15763 // will prevent this condition from triggering, which is what we want.
15764 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15765   SourceLocation Loc;
15766 
15767   unsigned diagnostic = diag::warn_condition_is_assignment;
15768   bool IsOrAssign = false;
15769 
15770   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15771     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15772       return;
15773 
15774     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15775 
15776     // Greylist some idioms by putting them into a warning subcategory.
15777     if (ObjCMessageExpr *ME
15778           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15779       Selector Sel = ME->getSelector();
15780 
15781       // self = [<foo> init...]
15782       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15783         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15784 
15785       // <foo> = [<bar> nextObject]
15786       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15787         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15788     }
15789 
15790     Loc = Op->getOperatorLoc();
15791   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15792     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15793       return;
15794 
15795     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15796     Loc = Op->getOperatorLoc();
15797   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15798     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15799   else {
15800     // Not an assignment.
15801     return;
15802   }
15803 
15804   Diag(Loc, diagnostic) << E->getSourceRange();
15805 
15806   SourceLocation Open = E->getBeginLoc();
15807   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15808   Diag(Loc, diag::note_condition_assign_silence)
15809         << FixItHint::CreateInsertion(Open, "(")
15810         << FixItHint::CreateInsertion(Close, ")");
15811 
15812   if (IsOrAssign)
15813     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15814       << FixItHint::CreateReplacement(Loc, "!=");
15815   else
15816     Diag(Loc, diag::note_condition_assign_to_comparison)
15817       << FixItHint::CreateReplacement(Loc, "==");
15818 }
15819 
15820 /// Redundant parentheses over an equality comparison can indicate
15821 /// that the user intended an assignment used as condition.
15822 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15823   // Don't warn if the parens came from a macro.
15824   SourceLocation parenLoc = ParenE->getBeginLoc();
15825   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15826     return;
15827   // Don't warn for dependent expressions.
15828   if (ParenE->isTypeDependent())
15829     return;
15830 
15831   Expr *E = ParenE->IgnoreParens();
15832 
15833   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15834     if (opE->getOpcode() == BO_EQ &&
15835         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15836                                                            == Expr::MLV_Valid) {
15837       SourceLocation Loc = opE->getOperatorLoc();
15838 
15839       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15840       SourceRange ParenERange = ParenE->getSourceRange();
15841       Diag(Loc, diag::note_equality_comparison_silence)
15842         << FixItHint::CreateRemoval(ParenERange.getBegin())
15843         << FixItHint::CreateRemoval(ParenERange.getEnd());
15844       Diag(Loc, diag::note_equality_comparison_to_assign)
15845         << FixItHint::CreateReplacement(Loc, "=");
15846     }
15847 }
15848 
15849 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15850                                        bool IsConstexpr) {
15851   DiagnoseAssignmentAsCondition(E);
15852   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15853     DiagnoseEqualityWithExtraParens(parenE);
15854 
15855   ExprResult result = CheckPlaceholderExpr(E);
15856   if (result.isInvalid()) return ExprError();
15857   E = result.get();
15858 
15859   if (!E->isTypeDependent()) {
15860     if (getLangOpts().CPlusPlus)
15861       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15862 
15863     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15864     if (ERes.isInvalid())
15865       return ExprError();
15866     E = ERes.get();
15867 
15868     QualType T = E->getType();
15869     if (!T->isScalarType()) { // C99 6.8.4.1p1
15870       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15871         << T << E->getSourceRange();
15872       return ExprError();
15873     }
15874     CheckBoolLikeConversion(E, Loc);
15875   }
15876 
15877   return E;
15878 }
15879 
15880 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15881                                            Expr *SubExpr, ConditionKind CK) {
15882   // Empty conditions are valid in for-statements.
15883   if (!SubExpr)
15884     return ConditionResult();
15885 
15886   ExprResult Cond;
15887   switch (CK) {
15888   case ConditionKind::Boolean:
15889     Cond = CheckBooleanCondition(Loc, SubExpr);
15890     break;
15891 
15892   case ConditionKind::ConstexprIf:
15893     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15894     break;
15895 
15896   case ConditionKind::Switch:
15897     Cond = CheckSwitchCondition(Loc, SubExpr);
15898     break;
15899   }
15900   if (Cond.isInvalid())
15901     return ConditionError();
15902 
15903   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15904   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15905   if (!FullExpr.get())
15906     return ConditionError();
15907 
15908   return ConditionResult(*this, nullptr, FullExpr,
15909                          CK == ConditionKind::ConstexprIf);
15910 }
15911 
15912 namespace {
15913   /// A visitor for rebuilding a call to an __unknown_any expression
15914   /// to have an appropriate type.
15915   struct RebuildUnknownAnyFunction
15916     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15917 
15918     Sema &S;
15919 
15920     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15921 
15922     ExprResult VisitStmt(Stmt *S) {
15923       llvm_unreachable("unexpected statement!");
15924     }
15925 
15926     ExprResult VisitExpr(Expr *E) {
15927       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15928         << E->getSourceRange();
15929       return ExprError();
15930     }
15931 
15932     /// Rebuild an expression which simply semantically wraps another
15933     /// expression which it shares the type and value kind of.
15934     template <class T> ExprResult rebuildSugarExpr(T *E) {
15935       ExprResult SubResult = Visit(E->getSubExpr());
15936       if (SubResult.isInvalid()) return ExprError();
15937 
15938       Expr *SubExpr = SubResult.get();
15939       E->setSubExpr(SubExpr);
15940       E->setType(SubExpr->getType());
15941       E->setValueKind(SubExpr->getValueKind());
15942       assert(E->getObjectKind() == OK_Ordinary);
15943       return E;
15944     }
15945 
15946     ExprResult VisitParenExpr(ParenExpr *E) {
15947       return rebuildSugarExpr(E);
15948     }
15949 
15950     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15951       return rebuildSugarExpr(E);
15952     }
15953 
15954     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15955       ExprResult SubResult = Visit(E->getSubExpr());
15956       if (SubResult.isInvalid()) return ExprError();
15957 
15958       Expr *SubExpr = SubResult.get();
15959       E->setSubExpr(SubExpr);
15960       E->setType(S.Context.getPointerType(SubExpr->getType()));
15961       assert(E->getValueKind() == VK_RValue);
15962       assert(E->getObjectKind() == OK_Ordinary);
15963       return E;
15964     }
15965 
15966     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15967       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15968 
15969       E->setType(VD->getType());
15970 
15971       assert(E->getValueKind() == VK_RValue);
15972       if (S.getLangOpts().CPlusPlus &&
15973           !(isa<CXXMethodDecl>(VD) &&
15974             cast<CXXMethodDecl>(VD)->isInstance()))
15975         E->setValueKind(VK_LValue);
15976 
15977       return E;
15978     }
15979 
15980     ExprResult VisitMemberExpr(MemberExpr *E) {
15981       return resolveDecl(E, E->getMemberDecl());
15982     }
15983 
15984     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15985       return resolveDecl(E, E->getDecl());
15986     }
15987   };
15988 }
15989 
15990 /// Given a function expression of unknown-any type, try to rebuild it
15991 /// to have a function type.
15992 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15993   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15994   if (Result.isInvalid()) return ExprError();
15995   return S.DefaultFunctionArrayConversion(Result.get());
15996 }
15997 
15998 namespace {
15999   /// A visitor for rebuilding an expression of type __unknown_anytype
16000   /// into one which resolves the type directly on the referring
16001   /// expression.  Strict preservation of the original source
16002   /// structure is not a goal.
16003   struct RebuildUnknownAnyExpr
16004     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16005 
16006     Sema &S;
16007 
16008     /// The current destination type.
16009     QualType DestType;
16010 
16011     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16012       : S(S), DestType(CastType) {}
16013 
16014     ExprResult VisitStmt(Stmt *S) {
16015       llvm_unreachable("unexpected statement!");
16016     }
16017 
16018     ExprResult VisitExpr(Expr *E) {
16019       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16020         << E->getSourceRange();
16021       return ExprError();
16022     }
16023 
16024     ExprResult VisitCallExpr(CallExpr *E);
16025     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16026 
16027     /// Rebuild an expression which simply semantically wraps another
16028     /// expression which it shares the type and value kind of.
16029     template <class T> ExprResult rebuildSugarExpr(T *E) {
16030       ExprResult SubResult = Visit(E->getSubExpr());
16031       if (SubResult.isInvalid()) return ExprError();
16032       Expr *SubExpr = SubResult.get();
16033       E->setSubExpr(SubExpr);
16034       E->setType(SubExpr->getType());
16035       E->setValueKind(SubExpr->getValueKind());
16036       assert(E->getObjectKind() == OK_Ordinary);
16037       return E;
16038     }
16039 
16040     ExprResult VisitParenExpr(ParenExpr *E) {
16041       return rebuildSugarExpr(E);
16042     }
16043 
16044     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16045       return rebuildSugarExpr(E);
16046     }
16047 
16048     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16049       const PointerType *Ptr = DestType->getAs<PointerType>();
16050       if (!Ptr) {
16051         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16052           << E->getSourceRange();
16053         return ExprError();
16054       }
16055 
16056       if (isa<CallExpr>(E->getSubExpr())) {
16057         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16058           << E->getSourceRange();
16059         return ExprError();
16060       }
16061 
16062       assert(E->getValueKind() == VK_RValue);
16063       assert(E->getObjectKind() == OK_Ordinary);
16064       E->setType(DestType);
16065 
16066       // Build the sub-expression as if it were an object of the pointee type.
16067       DestType = Ptr->getPointeeType();
16068       ExprResult SubResult = Visit(E->getSubExpr());
16069       if (SubResult.isInvalid()) return ExprError();
16070       E->setSubExpr(SubResult.get());
16071       return E;
16072     }
16073 
16074     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16075 
16076     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16077 
16078     ExprResult VisitMemberExpr(MemberExpr *E) {
16079       return resolveDecl(E, E->getMemberDecl());
16080     }
16081 
16082     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16083       return resolveDecl(E, E->getDecl());
16084     }
16085   };
16086 }
16087 
16088 /// Rebuilds a call expression which yielded __unknown_anytype.
16089 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16090   Expr *CalleeExpr = E->getCallee();
16091 
16092   enum FnKind {
16093     FK_MemberFunction,
16094     FK_FunctionPointer,
16095     FK_BlockPointer
16096   };
16097 
16098   FnKind Kind;
16099   QualType CalleeType = CalleeExpr->getType();
16100   if (CalleeType == S.Context.BoundMemberTy) {
16101     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16102     Kind = FK_MemberFunction;
16103     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16104   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16105     CalleeType = Ptr->getPointeeType();
16106     Kind = FK_FunctionPointer;
16107   } else {
16108     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16109     Kind = FK_BlockPointer;
16110   }
16111   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16112 
16113   // Verify that this is a legal result type of a function.
16114   if (DestType->isArrayType() || DestType->isFunctionType()) {
16115     unsigned diagID = diag::err_func_returning_array_function;
16116     if (Kind == FK_BlockPointer)
16117       diagID = diag::err_block_returning_array_function;
16118 
16119     S.Diag(E->getExprLoc(), diagID)
16120       << DestType->isFunctionType() << DestType;
16121     return ExprError();
16122   }
16123 
16124   // Otherwise, go ahead and set DestType as the call's result.
16125   E->setType(DestType.getNonLValueExprType(S.Context));
16126   E->setValueKind(Expr::getValueKindForType(DestType));
16127   assert(E->getObjectKind() == OK_Ordinary);
16128 
16129   // Rebuild the function type, replacing the result type with DestType.
16130   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16131   if (Proto) {
16132     // __unknown_anytype(...) is a special case used by the debugger when
16133     // it has no idea what a function's signature is.
16134     //
16135     // We want to build this call essentially under the K&R
16136     // unprototyped rules, but making a FunctionNoProtoType in C++
16137     // would foul up all sorts of assumptions.  However, we cannot
16138     // simply pass all arguments as variadic arguments, nor can we
16139     // portably just call the function under a non-variadic type; see
16140     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16141     // However, it turns out that in practice it is generally safe to
16142     // call a function declared as "A foo(B,C,D);" under the prototype
16143     // "A foo(B,C,D,...);".  The only known exception is with the
16144     // Windows ABI, where any variadic function is implicitly cdecl
16145     // regardless of its normal CC.  Therefore we change the parameter
16146     // types to match the types of the arguments.
16147     //
16148     // This is a hack, but it is far superior to moving the
16149     // corresponding target-specific code from IR-gen to Sema/AST.
16150 
16151     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16152     SmallVector<QualType, 8> ArgTypes;
16153     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16154       ArgTypes.reserve(E->getNumArgs());
16155       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16156         Expr *Arg = E->getArg(i);
16157         QualType ArgType = Arg->getType();
16158         if (E->isLValue()) {
16159           ArgType = S.Context.getLValueReferenceType(ArgType);
16160         } else if (E->isXValue()) {
16161           ArgType = S.Context.getRValueReferenceType(ArgType);
16162         }
16163         ArgTypes.push_back(ArgType);
16164       }
16165       ParamTypes = ArgTypes;
16166     }
16167     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16168                                          Proto->getExtProtoInfo());
16169   } else {
16170     DestType = S.Context.getFunctionNoProtoType(DestType,
16171                                                 FnType->getExtInfo());
16172   }
16173 
16174   // Rebuild the appropriate pointer-to-function type.
16175   switch (Kind) {
16176   case FK_MemberFunction:
16177     // Nothing to do.
16178     break;
16179 
16180   case FK_FunctionPointer:
16181     DestType = S.Context.getPointerType(DestType);
16182     break;
16183 
16184   case FK_BlockPointer:
16185     DestType = S.Context.getBlockPointerType(DestType);
16186     break;
16187   }
16188 
16189   // Finally, we can recurse.
16190   ExprResult CalleeResult = Visit(CalleeExpr);
16191   if (!CalleeResult.isUsable()) return ExprError();
16192   E->setCallee(CalleeResult.get());
16193 
16194   // Bind a temporary if necessary.
16195   return S.MaybeBindToTemporary(E);
16196 }
16197 
16198 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16199   // Verify that this is a legal result type of a call.
16200   if (DestType->isArrayType() || DestType->isFunctionType()) {
16201     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16202       << DestType->isFunctionType() << DestType;
16203     return ExprError();
16204   }
16205 
16206   // Rewrite the method result type if available.
16207   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16208     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16209     Method->setReturnType(DestType);
16210   }
16211 
16212   // Change the type of the message.
16213   E->setType(DestType.getNonReferenceType());
16214   E->setValueKind(Expr::getValueKindForType(DestType));
16215 
16216   return S.MaybeBindToTemporary(E);
16217 }
16218 
16219 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16220   // The only case we should ever see here is a function-to-pointer decay.
16221   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16222     assert(E->getValueKind() == VK_RValue);
16223     assert(E->getObjectKind() == OK_Ordinary);
16224 
16225     E->setType(DestType);
16226 
16227     // Rebuild the sub-expression as the pointee (function) type.
16228     DestType = DestType->castAs<PointerType>()->getPointeeType();
16229 
16230     ExprResult Result = Visit(E->getSubExpr());
16231     if (!Result.isUsable()) return ExprError();
16232 
16233     E->setSubExpr(Result.get());
16234     return E;
16235   } else if (E->getCastKind() == CK_LValueToRValue) {
16236     assert(E->getValueKind() == VK_RValue);
16237     assert(E->getObjectKind() == OK_Ordinary);
16238 
16239     assert(isa<BlockPointerType>(E->getType()));
16240 
16241     E->setType(DestType);
16242 
16243     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16244     DestType = S.Context.getLValueReferenceType(DestType);
16245 
16246     ExprResult Result = Visit(E->getSubExpr());
16247     if (!Result.isUsable()) return ExprError();
16248 
16249     E->setSubExpr(Result.get());
16250     return E;
16251   } else {
16252     llvm_unreachable("Unhandled cast type!");
16253   }
16254 }
16255 
16256 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16257   ExprValueKind ValueKind = VK_LValue;
16258   QualType Type = DestType;
16259 
16260   // We know how to make this work for certain kinds of decls:
16261 
16262   //  - functions
16263   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16264     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16265       DestType = Ptr->getPointeeType();
16266       ExprResult Result = resolveDecl(E, VD);
16267       if (Result.isInvalid()) return ExprError();
16268       return S.ImpCastExprToType(Result.get(), Type,
16269                                  CK_FunctionToPointerDecay, VK_RValue);
16270     }
16271 
16272     if (!Type->isFunctionType()) {
16273       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16274         << VD << E->getSourceRange();
16275       return ExprError();
16276     }
16277     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16278       // We must match the FunctionDecl's type to the hack introduced in
16279       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16280       // type. See the lengthy commentary in that routine.
16281       QualType FDT = FD->getType();
16282       const FunctionType *FnType = FDT->castAs<FunctionType>();
16283       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16284       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16285       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16286         SourceLocation Loc = FD->getLocation();
16287         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16288                                       FD->getDeclContext(),
16289                                       Loc, Loc, FD->getNameInfo().getName(),
16290                                       DestType, FD->getTypeSourceInfo(),
16291                                       SC_None, false/*isInlineSpecified*/,
16292                                       FD->hasPrototype(),
16293                                       false/*isConstexprSpecified*/);
16294 
16295         if (FD->getQualifier())
16296           NewFD->setQualifierInfo(FD->getQualifierLoc());
16297 
16298         SmallVector<ParmVarDecl*, 16> Params;
16299         for (const auto &AI : FT->param_types()) {
16300           ParmVarDecl *Param =
16301             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16302           Param->setScopeInfo(0, Params.size());
16303           Params.push_back(Param);
16304         }
16305         NewFD->setParams(Params);
16306         DRE->setDecl(NewFD);
16307         VD = DRE->getDecl();
16308       }
16309     }
16310 
16311     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16312       if (MD->isInstance()) {
16313         ValueKind = VK_RValue;
16314         Type = S.Context.BoundMemberTy;
16315       }
16316 
16317     // Function references aren't l-values in C.
16318     if (!S.getLangOpts().CPlusPlus)
16319       ValueKind = VK_RValue;
16320 
16321   //  - variables
16322   } else if (isa<VarDecl>(VD)) {
16323     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16324       Type = RefTy->getPointeeType();
16325     } else if (Type->isFunctionType()) {
16326       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16327         << VD << E->getSourceRange();
16328       return ExprError();
16329     }
16330 
16331   //  - nothing else
16332   } else {
16333     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16334       << VD << E->getSourceRange();
16335     return ExprError();
16336   }
16337 
16338   // Modifying the declaration like this is friendly to IR-gen but
16339   // also really dangerous.
16340   VD->setType(DestType);
16341   E->setType(Type);
16342   E->setValueKind(ValueKind);
16343   return E;
16344 }
16345 
16346 /// Check a cast of an unknown-any type.  We intentionally only
16347 /// trigger this for C-style casts.
16348 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16349                                      Expr *CastExpr, CastKind &CastKind,
16350                                      ExprValueKind &VK, CXXCastPath &Path) {
16351   // The type we're casting to must be either void or complete.
16352   if (!CastType->isVoidType() &&
16353       RequireCompleteType(TypeRange.getBegin(), CastType,
16354                           diag::err_typecheck_cast_to_incomplete))
16355     return ExprError();
16356 
16357   // Rewrite the casted expression from scratch.
16358   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16359   if (!result.isUsable()) return ExprError();
16360 
16361   CastExpr = result.get();
16362   VK = CastExpr->getValueKind();
16363   CastKind = CK_NoOp;
16364 
16365   return CastExpr;
16366 }
16367 
16368 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16369   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16370 }
16371 
16372 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16373                                     Expr *arg, QualType &paramType) {
16374   // If the syntactic form of the argument is not an explicit cast of
16375   // any sort, just do default argument promotion.
16376   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16377   if (!castArg) {
16378     ExprResult result = DefaultArgumentPromotion(arg);
16379     if (result.isInvalid()) return ExprError();
16380     paramType = result.get()->getType();
16381     return result;
16382   }
16383 
16384   // Otherwise, use the type that was written in the explicit cast.
16385   assert(!arg->hasPlaceholderType());
16386   paramType = castArg->getTypeAsWritten();
16387 
16388   // Copy-initialize a parameter of that type.
16389   InitializedEntity entity =
16390     InitializedEntity::InitializeParameter(Context, paramType,
16391                                            /*consumed*/ false);
16392   return PerformCopyInitialization(entity, callLoc, arg);
16393 }
16394 
16395 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16396   Expr *orig = E;
16397   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16398   while (true) {
16399     E = E->IgnoreParenImpCasts();
16400     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16401       E = call->getCallee();
16402       diagID = diag::err_uncasted_call_of_unknown_any;
16403     } else {
16404       break;
16405     }
16406   }
16407 
16408   SourceLocation loc;
16409   NamedDecl *d;
16410   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16411     loc = ref->getLocation();
16412     d = ref->getDecl();
16413   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16414     loc = mem->getMemberLoc();
16415     d = mem->getMemberDecl();
16416   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16417     diagID = diag::err_uncasted_call_of_unknown_any;
16418     loc = msg->getSelectorStartLoc();
16419     d = msg->getMethodDecl();
16420     if (!d) {
16421       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16422         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16423         << orig->getSourceRange();
16424       return ExprError();
16425     }
16426   } else {
16427     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16428       << E->getSourceRange();
16429     return ExprError();
16430   }
16431 
16432   S.Diag(loc, diagID) << d << orig->getSourceRange();
16433 
16434   // Never recoverable.
16435   return ExprError();
16436 }
16437 
16438 /// Check for operands with placeholder types and complain if found.
16439 /// Returns ExprError() if there was an error and no recovery was possible.
16440 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16441   if (!getLangOpts().CPlusPlus) {
16442     // C cannot handle TypoExpr nodes on either side of a binop because it
16443     // doesn't handle dependent types properly, so make sure any TypoExprs have
16444     // been dealt with before checking the operands.
16445     ExprResult Result = CorrectDelayedTyposInExpr(E);
16446     if (!Result.isUsable()) return ExprError();
16447     E = Result.get();
16448   }
16449 
16450   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16451   if (!placeholderType) return E;
16452 
16453   switch (placeholderType->getKind()) {
16454 
16455   // Overloaded expressions.
16456   case BuiltinType::Overload: {
16457     // Try to resolve a single function template specialization.
16458     // This is obligatory.
16459     ExprResult Result = E;
16460     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16461       return Result;
16462 
16463     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16464     // leaves Result unchanged on failure.
16465     Result = E;
16466     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16467       return Result;
16468 
16469     // If that failed, try to recover with a call.
16470     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16471                          /*complain*/ true);
16472     return Result;
16473   }
16474 
16475   // Bound member functions.
16476   case BuiltinType::BoundMember: {
16477     ExprResult result = E;
16478     const Expr *BME = E->IgnoreParens();
16479     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16480     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16481     if (isa<CXXPseudoDestructorExpr>(BME)) {
16482       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16483     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16484       if (ME->getMemberNameInfo().getName().getNameKind() ==
16485           DeclarationName::CXXDestructorName)
16486         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16487     }
16488     tryToRecoverWithCall(result, PD,
16489                          /*complain*/ true);
16490     return result;
16491   }
16492 
16493   // ARC unbridged casts.
16494   case BuiltinType::ARCUnbridgedCast: {
16495     Expr *realCast = stripARCUnbridgedCast(E);
16496     diagnoseARCUnbridgedCast(realCast);
16497     return realCast;
16498   }
16499 
16500   // Expressions of unknown type.
16501   case BuiltinType::UnknownAny:
16502     return diagnoseUnknownAnyExpr(*this, E);
16503 
16504   // Pseudo-objects.
16505   case BuiltinType::PseudoObject:
16506     return checkPseudoObjectRValue(E);
16507 
16508   case BuiltinType::BuiltinFn: {
16509     // Accept __noop without parens by implicitly converting it to a call expr.
16510     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16511     if (DRE) {
16512       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16513       if (FD->getBuiltinID() == Builtin::BI__noop) {
16514         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16515                               CK_BuiltinFnToFnPtr).get();
16516         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16517                                       VK_RValue, SourceLocation());
16518       }
16519     }
16520 
16521     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16522     return ExprError();
16523   }
16524 
16525   // Expressions of unknown type.
16526   case BuiltinType::OMPArraySection:
16527     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16528     return ExprError();
16529 
16530   // Everything else should be impossible.
16531 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16532   case BuiltinType::Id:
16533 #include "clang/Basic/OpenCLImageTypes.def"
16534 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16535 #define PLACEHOLDER_TYPE(Id, SingletonId)
16536 #include "clang/AST/BuiltinTypes.def"
16537     break;
16538   }
16539 
16540   llvm_unreachable("invalid placeholder type!");
16541 }
16542 
16543 bool Sema::CheckCaseExpression(Expr *E) {
16544   if (E->isTypeDependent())
16545     return true;
16546   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16547     return E->getType()->isIntegralOrEnumerationType();
16548   return false;
16549 }
16550 
16551 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16552 ExprResult
16553 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16554   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16555          "Unknown Objective-C Boolean value!");
16556   QualType BoolT = Context.ObjCBuiltinBoolTy;
16557   if (!Context.getBOOLDecl()) {
16558     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16559                         Sema::LookupOrdinaryName);
16560     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16561       NamedDecl *ND = Result.getFoundDecl();
16562       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16563         Context.setBOOLDecl(TD);
16564     }
16565   }
16566   if (Context.getBOOLDecl())
16567     BoolT = Context.getBOOLType();
16568   return new (Context)
16569       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16570 }
16571 
16572 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16573     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16574     SourceLocation RParen) {
16575 
16576   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16577 
16578   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16579                            [&](const AvailabilitySpec &Spec) {
16580                              return Spec.getPlatform() == Platform;
16581                            });
16582 
16583   VersionTuple Version;
16584   if (Spec != AvailSpecs.end())
16585     Version = Spec->getVersion();
16586 
16587   // The use of `@available` in the enclosing function should be analyzed to
16588   // warn when it's used inappropriately (i.e. not if(@available)).
16589   if (getCurFunctionOrMethodDecl())
16590     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16591   else if (getCurBlock() || getCurLambda())
16592     getCurFunction()->HasPotentialAvailabilityViolations = true;
16593 
16594   return new (Context)
16595       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16596 }
16597